internal void Send(Message message, DeliveryState deliveryState, OutcomeCallback callback, object state)
        {
            this.ThrowIfDetaching("Send");
            Delivery delivery = new Delivery()
            {
                Message   = message,
                Buffer    = message.Encode(),
                State     = deliveryState,
                Link      = this,
                OnOutcome = callback,
                UserToken = state,
                Settled   = this.settleMode == SenderSettleMode.Settled || callback == null
            };

            lock (this.ThisLock)
            {
                if (this.credit <= 0 || this.writing)
                {
                    this.outgoingList.Add(delivery);
                    return;
                }

                delivery.Tag = GetDeliveryTag(this.deliveryCount);
                this.credit--;
                this.deliveryCount++;
                this.writing = true;
            }

            this.WriteDelivery(delivery);
        }
Exemple #2
0
        //[TestMethod]
        public void PerfAtLeastOnceSend()
        {
            string     testName   = "PerfAtLeastOnceSend";
            Connection connection = new Connection(address);
            Session    session    = new Session(connection);

            this.sender = new SenderLink(session, "sender-" + testName, "q1");

            this.onOutcome      = OnSendComplete;
            this.done           = new ManualResetEvent(false);
            this.totalCount     = 1000000;
            this.completedCount = 0;
            this.initialCount   = 300;
            this.batchCount     = 100;
            Trace.TraceLevel    = TraceLevel.Information;

            var watch = new System.Diagnostics.Stopwatch();

            watch.Start();

            this.SendMessages(initialCount);

            this.done.WaitOne();
            watch.Stop();
            Trace.WriteLine(TraceLevel.Information, "total: {0}, time: {1}ms", this.totalCount, watch.ElapsedMilliseconds);

            connection.Close();
        }
Exemple #3
0
        void SendSync(Message message, int waitMilliseconds)
        {
            ManualResetEvent acked    = new ManualResetEvent(false);
            Outcome          outcome  = null;
            OutcomeCallback  callback = (l, m, o, s) =>
            {
                outcome = o;
                acked.Set();
            };

            this.SendInternal(message, this.GetTxnState(), callback, acked, true);

            bool signaled = acked.WaitOne(waitMilliseconds);

            if (!signaled)
            {
                this.OnTimeout(message);
                throw new TimeoutException(Fx.Format(SRAmqp.AmqpTimeout, "send", waitMilliseconds, "message"));
            }

            if (outcome != null)
            {
                if (outcome.Descriptor.Code == Codec.Released.Code)
                {
                    Released released = (Released)outcome;
                    throw new AmqpException(ErrorCode.MessageReleased, null);
                }
                else if (outcome.Descriptor.Code == Codec.Rejected.Code)
                {
                    Rejected rejected = (Rejected)outcome;
                    throw new AmqpException(rejected.Error);
                }
            }
        }
        public void PerfAtLeastOnceSend()
        {
            string testName = "PerfAtLeastOnceSend";
            Connection connection = new Connection(address);
            Session session = new Session(connection);
            this.sender = new SenderLink(session, "sender-" + testName, "q1");

            this.onOutcome = OnSendComplete;
            this.done = new ManualResetEvent(false);
            this.totalCount = 1000000;
            this.completedCount = 0;
            this.initialCount = 300;
            this.batchCount = 100;
            Trace.TraceLevel = TraceLevel.Information;

            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            this.SendMessages(initialCount);

            this.done.WaitOne();
            watch.Stop();
            Trace.WriteLine(TraceLevel.Information, "total: {0}, time: {1}ms", this.totalCount, watch.ElapsedMilliseconds);

            connection.Close();
        }
        /// <summary>
        /// Sends a message asynchronously. If callback is null, the message is sent without requesting for an acknowledgement (best effort).
        /// </summary>
        /// <param name="message">The message to send.</param>
        /// <param name="callback">The callback to invoke when acknowledgement is received.</param>
        /// <param name="state">The object that is passed back to the outcome callback.</param>
        public void Send(Message message, OutcomeCallback callback, object state)
        {
            DeliveryState deliveryState = null;

#if NETFX || NETFX40
            deliveryState = Amqp.Transactions.ResourceManager.GetTransactionalStateAsync(this).Result;
#endif
            this.Send(message, deliveryState, callback, state);
        }
Exemple #6
0
 protected void DoAMQPSendAsync(Amqp.Message amqpMessage, OutcomeCallback ackCallback)
 {
     try
     {
         this.link.Send(amqpMessage, ackCallback, this);
         MsgsSentOnLink++;
     }
     catch (Exception ex)
     {
         Tracer.ErrorFormat("Encountered Error on sending message from Producer {0}. Message: {1}. Stack : {2}.", Id, ex.Message, ex.StackTrace);
         throw ExceptionSupport.Wrap(ex);
     }
 }
Exemple #7
0
        void SendInternal(Message message, DeliveryState deliveryState, OutcomeCallback callback, object state, bool sync)
        {
            const int reservedBytes = 40;

#if NETFX || NETFX40 || DOTNET
            var buffer = message.Encode(this.Session.Connection.BufferManager, reservedBytes);
#else
            var buffer = message.Encode(reservedBytes);
#endif
            if (buffer.Length < 1)
            {
                throw new ArgumentException("Cannot send an empty message.");
            }

            Delivery delivery = new Delivery()
            {
                Message            = message,
                Buffer             = buffer,
                ReservedBufferSize = reservedBytes,
                State     = deliveryState,
                Link      = this,
                OnOutcome = callback,
                UserToken = state,
                Settled   = this.settleMode == SenderSettleMode.Settled || callback == null,
                Batchable = !sync
            };

            IHandler handler = this.Session.Connection.Handler;
            if (handler != null && handler.CanHandle(EventId.SendDelivery))
            {
                handler.Handle(Event.Create(EventId.SendDelivery, this.Session.Connection, this.Session, this, context: delivery));
            }

            lock (this.ThisLock)
            {
                this.ThrowIfDetaching("Send");

                if (this.credit <= 0 || this.writing)
                {
                    this.outgoingList.Add(delivery);
                    return;
                }

                this.credit--;
                this.deliveryCount++;
                this.writing = true;
            }

            this.WriteDelivery(delivery);
        }
        private void Send(string address,
                          RoutingType?routingType,
                          Message message,
                          DeliveryState deliveryState,
                          OutcomeCallback callback,
                          object state)
        {
            if (_senderLink.IsDetaching() || _senderLink.IsClosed)
            {
                throw new ProducerClosedException("Producer detached.");
            }

            try
            {
                if (_configuration.SetMessageCreationTime && !message.CreationTime.HasValue)
                {
                    message.CreationTime = DateTime.UtcNow;
                }

                if (message.GetMessageId <object>() == null && _configuration.MessageIdPolicy != null && !(_configuration.MessageIdPolicy is DisableMessageIdPolicy))
                {
                    message.SetMessageId(_configuration.MessageIdPolicy.GetNextMessageId());
                }

                message.Priority ??= _configuration.MessagePriority;
                message.Properties.To = address;
                message.MessageAnnotations[SymbolUtils.RoutingType] ??= routingType.GetRoutingAnnotation();

                _senderLink.Send(message.InnerMessage, deliveryState, callback, state);
                Log.MessageSent(_logger, message);
            }
            catch (AmqpException e) when(IsClosed || IsDetaching)
            {
                throw new ProducerClosedException(e.Error.Description, e.Error.Condition, e);
            }
            catch (AmqpException e)
            {
                throw new MessageSendException(e.Error.Description, e.Error.Condition, e);
            }
            catch (ObjectDisposedException e)
            {
                throw new ProducerClosedException("Producer detached.", e);
            }
            catch (Exception e)
            {
                throw new MessageSendException("Failed to send the message.", e);
            }
        }
Exemple #9
0
        /// <summary>
        /// Sends a message and synchronously waits for an acknowledgement.
        /// </summary>
        /// <param name="message">The message to send.</param>
        /// <param name="millisecondsTimeout">The time in milliseconds to wait for the acknowledgement.</param>
        //chris public void Send(Message message, int millisecondsTimeout = 60000)
        public void Send(Message message, int millisecondsTimeout)
        {
            //chris added
            //millisecondsTimeout = 60000;

            ManualResetEvent acked    = new ManualResetEvent(false);
            Outcome          outcome  = null;
            OutcomeCallback  callback = (m, o, s) =>
            {
                outcome = o;
                acked.Set();
            };

            this.Send(message, callback, acked);

            bool signaled = acked.WaitOne(millisecondsTimeout, false);

            //chris bool signaled = acked.WaitOne(millisecondsTimeout);
            if (!signaled)
            {
                lock (this.ThisLock)
                {
                    this.outgoingList.Remove(message.Delivery);
                }

                if (message.Delivery.BytesTransfered > 0)
                {
                    this.Session.DisposeDelivery(false, message.Delivery, new Released(), true);
                }

                throw new TimeoutException();
            }

            if (outcome != null)
            {
                if (outcome.Descriptor.Code == Codec.Released.Code)
                {
                    Released released = (Released)outcome;
                    throw new AmqpException(ErrorCode.MessageReleased, null);
                }
                else if (outcome.Descriptor.Code == Codec.Rejected.Code)
                {
                    Rejected rejected = (Rejected)outcome;
                    throw new AmqpException(rejected.Error);
                }
            }
        }
        public void TestMethod_SendAck()
        {
            string     testName   = "SendAck";
            const int  nMsgs      = 20;
            Connection connection = new Connection(address);
            Session    session    = new Session(connection);

            SenderLink       sender   = new SenderLink(session, "sender-" + testName, "q1");
            ManualResetEvent done     = new ManualResetEvent(false);
            OutcomeCallback  callback = (m, o, s) =>
            {
                Trace.WriteLine(TraceLevel.Information, "send complete: sn {0} outcome {1}", m.ApplicationProperties["sn"], o.Descriptor.Name);
                if ((int)m.ApplicationProperties["sn"] == (nMsgs - 1))
                {
                    done.Set();
                }
            };

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

            done.WaitOne(10000, waitExitContext);

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

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

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Exemple #11
0
        public void produce()
        {
            Address address = new Address(addr);

            Connection connection = new Connection(address);


            Session    session = new Session(connection);
            SenderLink sender  = new SenderLink(session, "sender", queue);

            OutcomeCallback callback = (l, msg, o, s) => {
                Interlocked.Increment(ref messagesSent);
                Interlocked.Increment(ref totalSent);
            };

            // This is just to limit the number of messages per second we are sending
            TokenBucketLimiterImpl tokens = new TokenBucketLimiterImpl(messagesPerSecond);

            Task.Factory.StartNew(() => {
                Console.WriteLine("Sending {0} messages...", numberOfMessages);
                for (var i = 0; i < numberOfMessages; i++)
                {
                    tokens.limit();
                    Message message        = new Message("a message!" + i);
                    message.Header         = new Header();
                    message.Header.Durable = true;

                    // The callback here is to make the sending to happen as fast as possible
                    sender.Send(message, callback, null);
                }
                Console.WriteLine(".... Done sending");
            }, TaskCreationOptions.LongRunning);

            // Trace.TraceLevel = TraceLevel.Verbose | TraceLevel.Error |
            // TraceLevel.Frame | TraceLevel.Information | TraceLevel.Warning;
            // Trace.TraceListener = (l, f, o) => Console.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, o));

            // sender.Close();

            // Task.Factory.StartNew(() =>  {
            //     while (true) {
            //         Console.WriteLine("Sent " + Interlocked.Read(ref messagesSent) + " on queue " + queue + " producer " + this.name);
            //         Thread.Sleep(1000);
            //     }
            // }, TaskCreationOptions.LongRunning);
        }
        internal void Send(Message message, DeliveryState deliveryState, OutcomeCallback callback, object state)
        {
            const int reservedBytes = 40;

#if NETFX || NETFX40 || DOTNET
            var buffer = message.Encode(this.Session.Connection.BufferManager, reservedBytes);
#else
            var buffer = message.Encode(reservedBytes);
#endif
            if (buffer.Length < 1)
            {
                throw new ArgumentException("Cannot send an empty message.");
            }

            Delivery delivery = new Delivery()
            {
                Message            = message,
                Buffer             = buffer,
                ReservedBufferSize = reservedBytes,
                State     = deliveryState,
                Link      = this,
                OnOutcome = callback,
                UserToken = state,
                Settled   = this.settleMode == SenderSettleMode.Settled || callback == null
            };

            lock (this.ThisLock)
            {
                this.ThrowIfDetaching("Send");

                if (this.credit <= 0 || this.writing)
                {
                    this.outgoingList.Add(delivery);
                    return;
                }

                delivery.Tag = Delivery.GetDeliveryTag(this.deliveryCount);
                this.credit--;
                this.deliveryCount++;
                this.writing = true;
            }

            this.WriteDelivery(delivery);
        }
        /// <summary>
        /// Sends a message and synchronously waits for an acknowledgement.
        /// </summary>
        /// <param name="message">The message to send.</param>
        /// <param name="millisecondsTimeout">The time in milliseconds to wait for the acknowledgement.</param>
        public void Send(Message message, int millisecondsTimeout = 60000)
        {
            ManualResetEvent acked    = new ManualResetEvent(false);
            Outcome          outcome  = null;
            OutcomeCallback  callback = (m, o, s) =>
            {
                outcome = o;
                acked.Set();
            };

            this.Send(message, callback, acked);

#if !COMPACT_FRAMEWORK
            bool signaled = acked.WaitOne(millisecondsTimeout, true);
#else
            bool signaled = acked.WaitOne(millisecondsTimeout, false);
#endif
            if (!signaled)
            {
                throw new TimeoutException();
            }

            if (outcome != null)
            {
                if (outcome.Descriptor.Code == Codec.Released.Code)
                {
                    Released released = (Released)outcome;
                    throw new AmqpException(ErrorCode.MessageReleased, null);
                }
                else if (outcome.Descriptor.Code == Codec.Rejected.Code)
                {
                    Rejected rejected = (Rejected)outcome;
                    throw new AmqpException(rejected.Error);
                }
            }
        }
Exemple #14
0
        internal void Send(Message message, DeliveryState deliveryState, OutcomeCallback callback, object state)
        {
            const int reservedBytes = 40;
            #if NETFX || NETFX40 || DOTNET
            var buffer = message.Encode(this.Session.Connection.BufferManager, reservedBytes);
            #else
            var buffer = message.Encode(reservedBytes);
            #endif
            if (buffer.Length < 1)
            {
                throw new ArgumentException("Cannot send an empty message.");
            }

            Delivery delivery = new Delivery()
            {
                Message = message,
                Buffer = buffer,
                ReservedBufferSize = reservedBytes,
                State = deliveryState,
                Link = this,
                OnOutcome = callback,
                UserToken = state,
                Settled = this.settleMode == SenderSettleMode.Settled || callback == null
            };

            lock (this.ThisLock)
            {
                this.ThrowIfDetaching("Send");

                if (this.credit <= 0 || this.writing)
                {
                    this.outgoingList.Add(delivery);
                    return;
                }

                delivery.Tag = Delivery.GetDeliveryTag(this.deliveryCount);
                this.credit--;
                this.deliveryCount++;
                this.writing = true;
            }

            this.WriteDelivery(delivery);
        }
Exemple #15
0
 /// <summary>
 /// Sends a message asynchronously. If callback is null, the message is sent without requesting for an acknowledgement (best effort).
 /// </summary>
 /// <param name="message">The message to send.</param>
 /// <param name="callback">The callback to invoke when acknowledgement is received.</param>
 /// <param name="state">The object that is passed back to the outcome callback.</param>
 public void Send(Message message, OutcomeCallback callback, object state)
 {
     DeliveryState deliveryState = null;
     #if NETFX
     deliveryState = Amqp.Transactions.ResourceManager.GetTransactionalStateAsync(this).Result;
     #endif
     this.Send(message, deliveryState, callback, state);
 }
Exemple #16
0
        internal void Send(Message message, DeliveryState deliveryState, OutcomeCallback callback, object state)
        {
            var buffer = message.Encode();
            if (buffer.Length < 1)
            {
                throw new ArgumentException("Cannot send an empty message.");
            }

            Delivery delivery = new Delivery()
            {
                Message = message,
                Buffer = buffer,
                State = deliveryState,
                Link = this,
                OnOutcome = callback,
                UserToken = state,
                Settled = this.settleMode == SenderSettleMode.Settled || callback == null
            };

            lock (this.ThisLock)
            {
                this.ThrowIfDetaching("Send");

                if (this.credit <= 0 || this.writing)
                {
                    this.outgoingList.Add(delivery);
                    return;
                }

                delivery.Tag = GetDeliveryTag(this.deliveryCount);
                this.credit--;
                this.deliveryCount++;
                this.writing = true;
            }

            this.WriteDelivery(delivery);
        }
Exemple #17
0
 /// <summary>
 /// Sends a message asynchronously. If callback is null, the message is sent without
 /// requesting for an acknowledgement (best effort). This method is not transaction aware. If you need transaction support,
 /// use <see cref="Send(Amqp.Message,Amqp.OutcomeCallback,object)"/>.
 /// </summary>
 /// <param name="message">The message to send.</param>
 /// <param name="deliveryState">The transactional state of the message. If null, no transaction is used.</param>
 /// <param name="callback">The callback to invoke when acknowledgement is received.</param>
 /// <param name="state">The object that is passed back to the outcome callback.</param>
 public void Send(Message message, DeliveryState deliveryState, OutcomeCallback callback, object state)
 {
     this.SendInternal(message, deliveryState, callback, state, false);
 }