public override void Send(ISendContext context)
		{
			GuardAgainstDisposed();

			LoopbackMessage message = null;
			try
			{
				message = new LoopbackMessage();

				if (context.ExpirationTime.HasValue)
				{
					message.ExpirationTime = context.ExpirationTime.Value;
				}

				context.SerializeTo(message.Body);
				message.ContentType = context.ContentType;

				lock (_messageLock)
				{
					GuardAgainstDisposed();

					_messages.AddLast(message);
				}
			}
			catch
			{
				if(message != null)
					message.Dispose();

				throw;
			}

			_messageReady.Set();
		}
        public void Send(ISendContext context)
        {
            AddProducerBinding();

            _connectionHandler.Use(connection =>
                {
                    try
                    {
                        IBasicProperties properties = _producer.CreateProperties();

                        properties.SetPersistent(context.DeliveryMode == DeliveryMode.Persistent);
                        properties.MessageId = context.MessageId ?? properties.MessageId ?? NewId.Next().ToString();
                        if (context.ExpirationTime.HasValue)
                        {
                            DateTime value = context.ExpirationTime.Value;
                            properties.Expiration =
                                (value.Kind == DateTimeKind.Utc
                                     ? value - SystemUtil.UtcNow
                                     : value - SystemUtil.Now).
                                    TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture);
                        }

                        using (var body = new MemoryStream())
                        {
                            context.SerializeTo(body);
                            properties.Headers = context.Headers.ToDictionary(entry => entry.Key, entry => (object)entry.Value);
                            properties.Headers["Content-Type"]=context.ContentType;

#if NET40
                            var task = _producer.PublishAsync(_address.Name, properties, body.ToArray());
                            if(context.WaitForAck)
                                task.Wait();
#else
                            _producer.Publish(_address.Name, properties, body.ToArray());
#endif

                            _address.LogSent(context.MessageId ?? properties.MessageId ?? "", context.MessageType);
                        }
                    }
#if NET40
                    catch (AggregateException ex)
                    {
                        throw new TransportException(_address.Uri, "Publisher did not confirm message", ex.InnerException);
                    }
#endif
                    catch (AlreadyClosedException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Connection was already closed", ex);
                    }
                    catch (EndOfStreamException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Connection was closed", ex);
                    }
                    catch (OperationInterruptedException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Operation was interrupted", ex);
                    }
                });
        }
        public void Send(ISendContext context)
        {
            AddProducerBinding();

            _connectionHandler.Use(connection =>
            {
                try
                {
                    IBasicProperties properties = _producer.CreateProperties();

                    properties.SetPersistent(context.DeliveryMode == DeliveryMode.Persistent);
                    properties.MessageId = context.MessageId ?? properties.MessageId ?? NewId.Next().ToString();
                    if (context.ExpirationTime.HasValue)
                    {
                        DateTime value        = context.ExpirationTime.Value;
                        properties.Expiration =
                            (value.Kind == DateTimeKind.Utc
                                     ? value - SystemUtil.UtcNow
                                     : value - SystemUtil.Now).
                            TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture);
                    }

                    using (var body = new MemoryStream())
                    {
                        context.SerializeTo(body);
                        properties.Headers = context.Headers.ToDictionary(entry => entry.Key, entry => (object)entry.Value);
                        properties.Headers["Content-Type"] = context.ContentType;

#if NET40
                        var task = _producer.PublishAsync(_address.Name, properties, body.ToArray());
                        task.Wait();
#else
                        _producer.Publish(_address.Name, properties, body.ToArray());
#endif

                        _address.LogSent(context.MessageId ?? properties.MessageId ?? "", context.MessageType);
                    }
                }
#if NET40
                catch (AggregateException ex)
                {
                    throw new TransportException(_address.Uri, "Publisher did not confirm message", ex.InnerException);
                }
#endif
                catch (AlreadyClosedException ex)
                {
                    throw new InvalidConnectionException(_address.Uri, "Connection was already closed", ex);
                }
                catch (EndOfStreamException ex)
                {
                    throw new InvalidConnectionException(_address.Uri, "Connection was closed", ex);
                }
                catch (OperationInterruptedException ex)
                {
                    throw new InvalidConnectionException(_address.Uri, "Operation was interrupted", ex);
                }
            });
        }
        // service bus best practices for performance:
        // http://msdn.microsoft.com/en-us/library/windowsazure/hh528527.aspx
        public void Send(ISendContext context)
        {
            _connectionHandler
            .Use(connection =>
            {
                // don't have too many outstanding at same time
                SpinWait.SpinUntil(() => _messagesInFlight < _settings.MaxOutstanding);

                using (var body = new MemoryStream())
                {
                    context.SerializeTo(body);

                    // the envelope is re-usable, so let's capture it in the below closure
                    // as a value
                    var envelope = new MessageEnvelope(body.ToArray());

                    var sending = Retries.Retry(FaultPolicies.FinalAzurePolicy,
                                                new Func <AsyncCallback, object, IAsyncResult>((cb, state) =>
                    {
                        return(SendMessage(connection, () =>
                        {
                            var brokeredMessage = new BrokeredMessage(envelope);

                            if (!string.IsNullOrWhiteSpace(context.CorrelationId))
                            {
                                brokeredMessage.CorrelationId = context.CorrelationId;
                            }

                            if (!string.IsNullOrWhiteSpace(context.MessageId))
                            {
                                brokeredMessage.MessageId = context.MessageId;
                            }

                            return brokeredMessage;
                        }, 1, cb, state));
                    }),
                                                (IAsyncResult ar) =>
                    {
                        var state = (StateHolder)ar.AsyncState;
                        Interlocked.Decrement(ref _messagesInFlight);

                        try
                        {
                            state.Sender.EndSend(ar);
                            Address.LogEndSend(state.Message.MessageId);
                        }
                        finally
                        {
                            // always dispose the message; it's only good once
                            state.Message.Dispose();
                        }
                    });
                    sending.Wait();
                }
            });
        }
        public override void Send(ISendContext context)
        {
            GuardAgainstDisposed();

            using (var body = new MemoryStream())
            {
                context.SerializeTo(body);

                var msg = Encoding.UTF8.GetString(body.ToArray());
                StompClient.Send(Address.Uri.PathAndQuery, msg);
            }
        }
        public void Send(ISendContext context)
        {
            _connectionHandler
                .Use(connection =>
                         {
                             using (var body = new MemoryStream())
                             {
                                 context.SerializeTo(body);

                                 var msg = Encoding.UTF8.GetString(body.ToArray());
                                 connection.Send(Address.Uri.PathAndQuery, msg);
                             }
                         });
        }
Beispiel #7
0
        public void Send(ISendContext context)
        {
            _connectionHandler
                .Use(connection =>
                         {
                             using (var body = new MemoryStream())
                             {
                                 context.SerializeTo(body);

                                 var msg = Encoding.UTF8.GetString(body.ToArray());
                                 connection.Send(Address.Uri.PathAndQuery, msg);
                             }
                         });
        }
Beispiel #8
0
        public void Send(ISendContext context)
        {
            GuardAgainstDisposed();

            LoopbackMessage message = null;

            try
            {
                message = new LoopbackMessage();

                if (context.ExpirationTime.HasValue)
                {
                    message.ExpirationTime = context.ExpirationTime.Value;
                }

                context.SerializeTo(message.Body);
                message.ContentType       = context.ContentType;
                message.OriginalMessageId = context.OriginalMessageId;

                if (!Monitor.TryEnter(_messageWriteLock, _deadlockTimeout))
                {
                    throw new Exception("Deadlock detected!");
                }

                try
                {
                    GuardAgainstDisposed();

                    _messages.AddLast(message);
                }
                finally
                {
                    Monitor.Exit(_messageWriteLock);
                }

                Address.LogSent(message.MessageId, context.MessageType);
            }
            catch
            {
                if (message != null)
                {
                    message.Dispose();
                }

                throw;
            }

            _messageReady.Set();
        }
Beispiel #9
0
        public void Send(ISendContext context)
        {
            AddProducerBinding();

            _connectionHandler.Use(connection =>
            {
                try
                {
                    IBasicProperties properties = _producer.CreateProperties();

                    properties.SetPersistent(true);
                    properties.MessageId = context.MessageId ?? properties.MessageId ?? NewId.Next().ToString();
                    if (context.ExpirationTime.HasValue)
                    {
                        DateTime value        = context.ExpirationTime.Value;
                        properties.Expiration =
                            (value.Kind == DateTimeKind.Utc
                                     ? value - SystemUtil.UtcNow
                                     : value - SystemUtil.Now).
                            TotalMilliseconds.ToString();
                    }

                    using (var body = new MemoryStream())
                    {
                        context.SerializeTo(body);
                        properties.Headers = new Hashtable {
                            { "Content-Type", context.ContentType }
                        };

                        _producer.Publish(_address.Name, properties, body.ToArray());

                        _address.LogSent(context.MessageId ?? "", context.MessageType);
                    }
                }
                catch (AlreadyClosedException ex)
                {
                    throw new InvalidConnectionException(_address.Uri, "Connection was already closed", ex);
                }
                catch (EndOfStreamException ex)
                {
                    throw new InvalidConnectionException(_address.Uri, "Connection was closed", ex);
                }
                catch (OperationInterruptedException ex)
                {
                    throw new InvalidConnectionException(_address.Uri, "Operation was interrupted", ex);
                }
            });
        }
        public void Send(ISendContext context)
        {
            AddProducerBinding();

            _connectionHandler.Use(connection =>
                {
                    try
                    {
                        IBasicProperties properties = _producer.CreateProperties();

                        properties.SetPersistent(true);
                        properties.MessageId = context.MessageId ?? properties.MessageId ?? NewId.Next().ToString();
                        if (context.ExpirationTime.HasValue)
                        {
                            DateTime value = context.ExpirationTime.Value;
                            properties.Expiration =
                                (value.Kind == DateTimeKind.Utc
                                     ? value - SystemUtil.UtcNow
                                     : value - SystemUtil.Now).
                                    TotalMilliseconds.ToString("F0", CultureInfo.InvariantCulture);
                        }

                        using (var body = new MemoryStream())
                        {
                            context.SerializeTo(body);
                            properties.Headers = context.Headers.ToDictionary(entry => entry.Key, entry => entry.Value);
                            properties.Headers["Content-Type"]=context.ContentType;

                            _producer.Publish(_address.Name, properties, body.ToArray());

                            _address.LogSent(context.MessageId ?? "", context.MessageType);
                        }
                    }
                    catch (AlreadyClosedException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Connection was already closed", ex);
                    }
                    catch (EndOfStreamException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Connection was closed", ex);
                    }
                    catch (OperationInterruptedException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Operation was interrupted", ex);
                    }
                });
        }
Beispiel #11
0
        public void Send(ISendContext context)
        {
            using (var message = new Message())
            {
                if (!string.IsNullOrEmpty(context.MessageType))
                {
                    message.Label = context.MessageType.Length > 250 ? context.MessageType.Substring(0, 250) : context.MessageType;
                }

                message.Recoverable        = _address.IsRecoverable;
                message.UseDeadLetterQueue = true; // in case lack of permission message will be redirected to dead letter

                if (context.ExpirationTime.HasValue)
                {
                    DateTime value = context.ExpirationTime.Value;
                    message.TimeToBeReceived = value.Kind == DateTimeKind.Utc ? value - SystemUtil.UtcNow : value - SystemUtil.Now;
                }

                context.SerializeTo(message.BodyStream);

                var headers = new TransportMessageHeaders();

                if (!string.IsNullOrEmpty(context.ContentType))
                {
                    headers.Add("Content-Type", context.ContentType);
                }
                if (!string.IsNullOrEmpty(context.OriginalMessageId))
                {
                    headers.Add("Original-Message-Id", context.OriginalMessageId);
                }

                message.Extension = headers.GetBytes();

                try
                {
                    _connectionHandler.Use(connection => SendMessage(connection.Queue, message));

                    _address.LogSent(message.Id, context.MessageType);
                }
                catch (MessageQueueException ex)
                {
                    HandleOutboundMessageQueueException(ex);
                }
            }
        }
Beispiel #12
0
        public void Send(ISendContext context)
        {
            GuardAgainstDisposed();

            LoopbackMessage message = null;

            try
            {
                message = new LoopbackMessage();

                if (context.ExpirationTime.HasValue)
                {
                    message.ExpirationTime = context.ExpirationTime.Value;
                }

                context.SerializeTo(message.Body);
                message.ContentType = context.ContentType;

                lock (_messageLock)
                {
                    GuardAgainstDisposed();

                    _messages.AddLast(message);
                }

                if (SpecialLoggers.Messages.IsInfoEnabled)
                {
                    SpecialLoggers.Messages.InfoFormat("SEND:{0}:{1}:{2}", Address, context.MessageType,
                                                       message.MessageId);
                }
            }
            catch
            {
                if (message != null)
                {
                    message.Dispose();
                }

                throw;
            }

            _messageReady.Set();
        }
Beispiel #13
0
        public void Send(ISendContext context)
        {
            using (var message = new Message())
            {
                if (!string.IsNullOrEmpty(context.MessageType))
                {
                    message.Label = context.MessageType.Length > 250 ? context.MessageType.Substring(0, 250) : context.MessageType;
                }

                message.Recoverable = true;

                if (context.ExpirationTime.HasValue)
                {
                    DateTime value = context.ExpirationTime.Value;
                    message.TimeToBeReceived = value.Kind == DateTimeKind.Utc ? value - SystemUtil.UtcNow : value - SystemUtil.Now;
                }

                context.SerializeTo(message.BodyStream);

                if (context.ContentType != null)
                {
                    var headers = new TransportMessageHeaders();
                    headers.Add("Content-Type", context.ContentType);

                    message.Extension = headers.GetBytes();
                }

                try
                {
                    _connectionHandler.Use(connection => SendMessage(connection.Queue, message));

                    if (_messageLog.IsDebugEnabled)
                    {
                        _messageLog.DebugFormat("SEND:{0}:{1}:{2}", _address.OutboundFormatName, message.Label, message.Id);
                    }
                }
                catch (MessageQueueException ex)
                {
                    HandleOutboundMessageQueueException(ex);
                }
            }
        }
        public void Send(ISendContext context)
        {
            using (var message = new Message())
            {
                if (!string.IsNullOrEmpty(context.MessageType))
                    message.Label = context.MessageType.Length > 250 ? context.MessageType.Substring(0, 250) : context.MessageType;

                message.Recoverable = _address.IsRecoverable;
                message.UseDeadLetterQueue = true; // in case lack of permission message will be redirected to dead letter

                if (context.ExpirationTime.HasValue)
                {
                    DateTime value = context.ExpirationTime.Value;
                    message.TimeToBeReceived = value.Kind == DateTimeKind.Utc ? value - SystemUtil.UtcNow : value - SystemUtil.Now;
                }

                context.SerializeTo(message.BodyStream);

                var headers = new TransportMessageHeaders();

                if (!string.IsNullOrEmpty(context.ContentType))
                    headers.Add("Content-Type", context.ContentType);
                if (!string.IsNullOrEmpty(context.OriginalMessageId))
                    headers.Add("Original-Message-Id", context.OriginalMessageId);
                
                message.Extension = headers.GetBytes();

                try
                {
                    _connectionHandler.Use(connection => SendMessage(connection.Queue, message));

                    _address.LogSent(message.Id, context.MessageType);

                }
                catch (MessageQueueException ex)
                {
                    HandleOutboundMessageQueueException(ex);
                }
            }
        }
Beispiel #15
0
        public void Send(ISendContext context)
        {
            GuardAgainstDisposed();

            LoopbackMessage message = null;

            try
            {
                message = new LoopbackMessage();

                if (context.ExpirationTime.HasValue)
                {
                    message.ExpirationTime = context.ExpirationTime.Value;
                }

                context.SerializeTo(message.Body);
                message.ContentType       = context.ContentType;
                message.OriginalMessageId = context.OriginalMessageId;

                lock (_messageLock)
                {
                    GuardAgainstDisposed();

                    _messages.AddLast(message);
                }

                Address.LogSent(message.MessageId, context.MessageType);
            }
            catch
            {
                if (message != null)
                {
                    message.Dispose();
                }

                throw;
            }

            _messageReady.Set();
        }
        public void Send(ISendContext context)
        {
            AddProducerBinding();

            _connectionHandler.Use(connection =>
                {
                    try
                    {
                        IBasicProperties properties = _producer.Channel.CreateBasicProperties();

                        properties.SetPersistent(true);
                        if (context.ExpirationTime.HasValue)
                        {
                            DateTime value = context.ExpirationTime.Value;
                            properties.Expiration =
                                (value.Kind == DateTimeKind.Utc ? value - SystemUtil.UtcNow : value - SystemUtil.Now).
                                    ToString();
                        }

                        using (var body = new MemoryStream())
                        {
                            context.SerializeTo(body);
                            properties.Headers = new Hashtable {{"Content-Type", context.ContentType}};

                            _producer.Channel.BasicPublish(_address.Name, "", properties, body.ToArray());

                            _address.LogSent("", context.MessageType);
                        }
                    }
                    catch (EndOfStreamException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Connection was closed", ex);
                    }
                    catch (OperationInterruptedException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Operation was interrupted", ex);
                    }
                });
        }
		public void Send(ISendContext context)
		{
			using (var message = new Message())
			{
				if (!string.IsNullOrEmpty(context.MessageType))
					message.Label = context.MessageType.Length > 250 ? context.MessageType.Substring(0, 250) : context.MessageType;

				message.Recoverable = true;

				if (context.ExpirationTime.HasValue)
				{
					DateTime value = context.ExpirationTime.Value;
					message.TimeToBeReceived = value.Kind == DateTimeKind.Utc ? value - SystemUtil.UtcNow : value - SystemUtil.Now;
				}

				context.SerializeTo(message.BodyStream);

				if (context.ContentType != null)
				{
					var headers = new TransportMessageHeaders();
					headers.Add("Content-Type", context.ContentType);

					message.Extension = headers.GetBytes();
				}

				try
				{
					_connectionHandler.Use(connection => SendMessage(connection.Queue, message));

					if (_messageLog.IsDebugEnabled)
						_messageLog.DebugFormat("SEND:{0}:{1}:{2}", _address.OutboundFormatName, message.Label, message.Id);
				}
				catch (MessageQueueException ex)
				{
					HandleOutboundMessageQueueException(ex);
				}
			}
		}
        public void Send(ISendContext context)
        {
            _connectionHandler.Use(connection =>
            {
                var
                message = new SqlMessage {
                    Label = context.MessageType
                };

                if (context.ExpirationTime.HasValue)
                {
                    DateTime value           = context.ExpirationTime.Value;
                    message.TimeToBeReceived = value.Kind == DateTimeKind.Utc ? value - SystemUtil.UtcNow : value - SystemUtil.Now;
                }

                var bodyStream = new MemoryStream();

                context.SerializeTo(bodyStream);

                message.Body = bodyStream.ToArray();

                var headers = new TransportMessageHeaders();

                if (!string.IsNullOrEmpty(context.ContentType))
                {
                    headers.Add("Content-Type", context.ContentType);
                }
                if (!string.IsNullOrEmpty(context.OriginalMessageId))
                {
                    headers.Add("Original-Message-Id", context.OriginalMessageId);
                }

                message.Extension = headers.GetBytes();

                connection.Queue.Enqueue(message);
                Console.WriteLine("{3} Sendt message: Label {1} Size {2}".FormatWith(message.Id, message.Label, message.Body.Length, Address.Uri));
            });
        }
        public void Send(ISendContext context)
        {
            GuardAgainstDisposed();

            LoopbackMessage message = null;
            try
            {
                message = new LoopbackMessage();

                if (context.ExpirationTime.HasValue)
                {
                    message.ExpirationTime = context.ExpirationTime.Value;
                }

                context.SerializeTo(message.Body);
                message.ContentType = context.ContentType;

                lock (_messageLock)
                {
                    GuardAgainstDisposed();

                    _messages.AddLast(message);
                }

                if (SpecialLoggers.Messages.IsInfoEnabled)
                    SpecialLoggers.Messages.InfoFormat("SEND:{0}:{1}:{2}", Address, context.MessageType,
                        message.MessageId);
            }
            catch
            {
                if (message != null)
                    message.Dispose();

                throw;
            }

            _messageReady.Set();
        }
		public void Send(ISendContext context)
		{
			DeclareBindings();

			IBasicProperties properties = _channel.CreateBasicProperties();

			properties.SetPersistent(true);
			if(context.ExpirationTime.HasValue)
			{
				var value = context.ExpirationTime.Value;
				properties.Expiration = (value.Kind == DateTimeKind.Utc ? value - SystemUtil.UtcNow : value - SystemUtil.Now).ToString();
			}

			using(var body = new MemoryStream())
			{
				context.SerializeTo(body);
				properties.Headers = new Hashtable {{"Content-Type", context.ContentType}};

				_channel.BasicPublish(_address.Name, "", properties, body.ToArray());

				if (SpecialLoggers.Messages.IsInfoEnabled)
					SpecialLoggers.Messages.InfoFormat("SEND:{0}:{1}", Address, context.MessageId);
			}
		}
        // service bus best practices for performance:
        // http://msdn.microsoft.com/en-us/library/windowsazure/hh528527.aspx
        public void Send(ISendContext context)
        {
            AddProducerBinding();

            _connectionHandler.Use(connection =>
                {
                    try
                    {
                        // don't have too many outstanding at same time
            //                        SpinWait.SpinUntil(() => _messagesInFlight < _settings.MaxOutstanding);

                        using (var body = new MemoryStream())
                        {
                            context.SerializeTo(body);

                            body.Seek(0, SeekOrigin.Begin);

                            // TODO put transient handling logic in here for retry

                            var brokeredMessage = new BrokeredMessage(body, false);

                            brokeredMessage.MessageId = context.MessageId
                                                        ?? brokeredMessage.MessageId ?? NewId.Next().ToString();
                            if (context.ExpirationTime.HasValue)
                            {
                                DateTime value = context.ExpirationTime.Value;
                                brokeredMessage.TimeToLive =
                                    (value.Kind == DateTimeKind.Utc
                                         ? value - DateTime.UtcNow
                                         : value - DateTime.Now);
                            }

                            if (!string.IsNullOrWhiteSpace(context.CorrelationId))
                                brokeredMessage.CorrelationId = context.CorrelationId;

                            foreach (var header in context.Headers)
                                brokeredMessage.Properties.Add(header.Key, header.Value);

                            brokeredMessage.ContentType = context.ContentType;

                            _producer.Send(brokeredMessage);
                        }
                    }
                    catch (TimeoutException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Send operation timed out", ex);
                    }
                    catch (OperationCanceledException ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Operation was cancelled", ex);
                    }
                    catch (Exception ex)
                    {
                        throw new InvalidConnectionException(_address.Uri, "Send threw an exception", ex);
                    }
                });
        }
        public override void Send(ISendContext context)
        {
            GuardAgainstDisposed();

            using (var body = new MemoryStream())
            {
                context.SerializeTo(body);

                var msg = Encoding.UTF8.GetString(body.ToArray());
                StompClient.Send(Address.Uri.PathAndQuery, msg);
            }
        }
		// service bus best practices for performance:
		// http://msdn.microsoft.com/en-us/library/windowsazure/hh528527.aspx
		public void Send(ISendContext context)
		{
			_connectionHandler
				.Use(connection =>
					{
						// don't have too many outstanding at same time
						SpinWait.SpinUntil(() => _messagesInFlight < _settings.MaxOutstanding);

						using (var body = new MemoryStream())
						{
							context.SerializeTo(body);
							
							// the envelope is re-usable, so let's capture it in the below closure
							// as a value
							var envelope = new MessageEnvelope(body.ToArray());

							TrySendMessage(connection, () =>
								{
									var brokeredMessage = new BrokeredMessage(envelope);

									if (!string.IsNullOrWhiteSpace(context.CorrelationId))
										brokeredMessage.CorrelationId = context.CorrelationId;

									if (!string.IsNullOrWhiteSpace(context.MessageId))
										brokeredMessage.MessageId = context.MessageId;
									
									return brokeredMessage;
								}, 1);
						}
					});
		}
Beispiel #24
0
        // service bus best practices for performance:
        // http://msdn.microsoft.com/en-us/library/windowsazure/hh528527.aspx
        public void Send(ISendContext context)
        {
            AddProducerBinding();

            _connectionHandler.Use(connection =>
            {
                try
                {
                    // don't have too many outstanding at same time
//                        SpinWait.SpinUntil(() => _messagesInFlight < _settings.MaxOutstanding);

                    using (var body = new MemoryStream())
                    {
                        context.SerializeTo(body);

                        body.Seek(0, SeekOrigin.Begin);

                        // TODO put transient handling logic in here for retry

                        var brokeredMessage = new BrokeredMessage(body, false);

                        brokeredMessage.MessageId = context.MessageId
                                                    ?? brokeredMessage.MessageId ?? NewId.Next().ToString();
                        if (context.ExpirationTime.HasValue)
                        {
                            DateTime value             = context.ExpirationTime.Value;
                            brokeredMessage.TimeToLive =
                                (value.Kind == DateTimeKind.Utc
                                         ? value - DateTime.UtcNow
                                         : value - DateTime.Now);
                        }

                        if (!string.IsNullOrWhiteSpace(context.CorrelationId))
                        {
                            brokeredMessage.CorrelationId = context.CorrelationId;
                        }

                        foreach (var header in context.Headers)
                        {
                            brokeredMessage.Properties.Add(header.Key, header.Value);
                        }

                        brokeredMessage.ContentType = context.ContentType;

                        _producer.Send(brokeredMessage);
                    }
                }
                catch (TimeoutException ex)
                {
                    throw new InvalidConnectionException(_address.Uri, "Send operation timed out", ex);
                }
                catch (OperationCanceledException ex)
                {
                    throw new InvalidConnectionException(_address.Uri, "Operation was cancelled", ex);
                }
                catch (Exception ex)
                {
                    throw new InvalidConnectionException(_address.Uri, "Send threw an exception", ex);
                }
            });
        }
		// service bus best practices for performance:
		// http://msdn.microsoft.com/en-us/library/windowsazure/hh528527.aspx
		public void Send(ISendContext context)
		{
			_connectionHandler
				.Use(connection =>
					{
						// don't have too many outstanding at same time
						SpinWait.SpinUntil(() => _messagesInFlight < _settings.MaxOutstanding);

						using (var body = new MemoryStream())
						{
							context.SerializeTo(body);

							// the envelope is re-usable, so let's capture it in the below closure
							// as a value
							var envelope = new MessageEnvelope(body.ToArray());

							var sending = Retries.Retry(FaultPolicies.FinalAzurePolicy,
								new Func<AsyncCallback, object, IAsyncResult>((cb, state) =>
								{
									return SendMessage(connection, () =>
										{
											var brokeredMessage = new BrokeredMessage(envelope);

											if (!string.IsNullOrWhiteSpace(context.CorrelationId))
												brokeredMessage.CorrelationId = context.CorrelationId;

											if (!string.IsNullOrWhiteSpace(context.MessageId))
												brokeredMessage.MessageId = context.MessageId;

											return brokeredMessage;
										}, 1, cb, state);
								}),
								(IAsyncResult ar) =>
								{
									var state = (StateHolder)ar.AsyncState;
									Interlocked.Decrement(ref _messagesInFlight);

									try
									{
										state.Sender.EndSend(ar);
										Address.LogEndSend(state.Message.MessageId);
									}
									finally
									{
										// always dispose the message; it's only good once
										state.Message.Dispose();
									}
								});
							sending.Wait();
						}
					});
		}
        public void Send(ISendContext context)
        {
            GuardAgainstDisposed();

            LoopbackMessage message = null;
            try
            {
                message = new LoopbackMessage();

                if (context.ExpirationTime.HasValue)
                {
                    message.ExpirationTime = context.ExpirationTime.Value;
                }

                context.SerializeTo(message.Body);
                message.ContentType = context.ContentType;
                message.OriginalMessageId = context.OriginalMessageId;

                if (!Monitor.TryEnter(_messageWriteLock, _deadlockTimeout))
                    throw new Exception("Deadlock detected!");

                try
                {
                    GuardAgainstDisposed();

                    _messages.AddLast(message);
                }
                finally
                {
                    Monitor.Exit(_messageWriteLock);
                }

                Address.LogSent(message.MessageId, context.MessageType);
            }
            catch
            {
                if (message != null)
                    message.Dispose();

                throw;
            }

            _messageReady.Set();
        }