private static EventData ToEventData(TransportMessage transportMessage, EventStoreMessageMetadata metadata)
        {
            metadata.CorrelationId = transportMessage.CorrelationId;
            metadata.MessageId = transportMessage.Id;
            metadata.ReplyTo = transportMessage.ReplyToAddress.ToString();
            metadata.Headers = transportMessage.Headers;
            var type = transportMessage.IsControlMessage() 
                              ? "ControlMessage" 
                              : transportMessage.Headers[Headers.EnclosedMessageTypes];

            byte[] data;
            string contentType;
            if (transportMessage.Headers.TryGetValue(Headers.ContentType, out contentType))
            {
                if (contentType != ContentTypes.Json)
                {
                    throw new InvalidOperationException("Invalid content type: "+contentType);
                }
                data = transportMessage.Body;
            }
            else
            {
                data = new byte[0];
            }
            return new EventData(Guid.NewGuid(), type, true, data, metadata.ToJsonBytes());
        }
        public void Send(TransportMessage message, Address address)
        {
            try
            {
                XmsAddress addr = address.ToXmsAddress();
                using (var producer = provider.GetProducer(addr))
                {
                    var xmsMessage = producer.CreateBytesMessage();
                    XmsUtilities.Convert(message, xmsMessage);
                    producer.Send(xmsMessage);
                    message.Id = xmsMessage.JMSMessageID;
                   
                }
            }
            // TODO: QueueNotFoundException
            catch (Exception ex)
            {
                if (address == null)
                    throw new FailedToSendMessageException("Failed to send message.", ex);

                throw new FailedToSendMessageException(
                    string.Format("Failed to send message to address: {0}@{1}", address.Queue, address.Machine), ex);
            }
         
        }
        public void Defer(TransportMessage message, DateTime processAt, Address address)
        {
            message.Headers[ScheduledMessage.AMQ_SCHEDULED_DELAY] =
                ((int)processAt.Subtract(DateTime.UtcNow).TotalMilliseconds).ToString(CultureInfo.InvariantCulture);

            this.MessageSender.Send(message, address);
        }
 public void SetUp()
 {
     destination = Target.Input;
     XmsUtilities.Purge(destination);
     received = null;
     sent = new TransportMessage().WithBody();;
 }
 public void MutateIncoming(TransportMessage transportMessage)
 {
     string bodyAsString = Encoding.UTF8
         .GetString(transportMessage.Body);
     Console.WriteLine("Serialized Message Body:");
     Console.WriteLine(bodyAsString);
 }
 public void MutateIncoming(TransportMessage transportMessage)
 {
     string bodyAsString = Encoding.UTF8
         .GetString(transportMessage.Body);
     log.Info("Serialized Message Body:");
     log.Info(bodyAsString);
 }
示例#7
0
        public void IncrementFailuresForMessage(TransportMessage message, Exception e)
        {
            var item = failuresPerMessage.AddOrUpdate(message.Id, s => new Tuple<int, Exception>(1, e),
                (s, i) => new Tuple<int, Exception>(i.Item1 + 1, e));

            notifications.Errors.InvokeMessageHasFailedAFirstLevelRetryAttempt(item.Item1, message, e);
        }
示例#8
0
        void ISendMessages.Send(TransportMessage message, Address address)
        {
            var queuePath = MsmqUtilities.GetFullPath(address);

            using (var q = new MessageQueue(queuePath, QueueAccessMode.Send))
            {
                var toSend = MsmqUtilities.Convert(message);

                toSend.UseDeadLetterQueue = UseDeadLetterQueue;
                toSend.UseJournalQueue = UseJournalQueue;

                if (message.ReplyToAddress != null)
                    toSend.ResponseQueue = new MessageQueue(MsmqUtilities.GetReturnAddress(message.ReplyToAddress.ToString(), address.ToString()));

                try
                {
                    q.Send(toSend, GetTransactionTypeForSend());
                }
                catch (MessageQueueException ex)
                {
                    if (ex.MessageQueueErrorCode == MessageQueueErrorCode.QueueNotFound)
                        throw new QueueNotFoundException { Queue = address };

                    throw;
                }

                message.Id = toSend.Id;
            }
        }
示例#9
0
        void CloneAndSendLocal(TransportMessage messageToDispatch, Site destinationSite)
        {
            //todo - do we need to clone? check with Jonathan O
            messageToDispatch.Headers[Headers.DestinationSites] = destinationSite.Key;

            messageSender.Send(messageToDispatch, localAddress);
        }
示例#10
0
        void IManageMessageFailures.ProcessingAlwaysFailsForMessage(TransportMessage message, Exception e)
        {
            if (SanitizeProcessingExceptions)
                e = ExceptionSanitizer.Sanitize(e);

            this.SendFailureMessage(message, e, "ProcessingFailed");
        }
        private bool TryInvokeFaultManager(TransportMessage message, Exception exception)
        {
            try
            {
                Exception e = exception;

                if (e is AggregateException)
                {
                    e = e.GetBaseException();
                }

                if (e is TransportMessageHandlingFailedException)
                {
                    e = e.InnerException;
                }

                message.RevertToOriginalBodyIfNeeded();

                failureManager.ProcessingAlwaysFailsForMessage(message, e);

                return true;
            }
            catch (Exception ex)
            {
                Configure.Instance.RaiseCriticalError(
                    String.Format("Fault manager failed to process the failed message with id {0}", message.Id), ex);
            }

            return false;
        }
        void IMutateOutgoingTransportMessages.MutateOutgoing(IMessage[] messages, TransportMessage transportMessage)
        {
            if (transportMessage.Headers.ContainsKey(WindowsIdentityName))
                transportMessage.Headers.Remove(WindowsIdentityName);

            transportMessage.Headers.Add(WindowsIdentityName, Thread.CurrentPrincipal.Identity.Name);
        }
        public void Send(TransportMessage message, string destination)
        {
            var address = MsmqUtilities.GetFullPath(destination);

            using (var q = new MessageQueue(address, QueueAccessMode.Send))
            {
                var toSend = new Message();

                if (message.Body != null)
                    toSend.BodyStream = new MemoryStream(message.Body);

                if (message.CorrelationId != null)
                    toSend.CorrelationId = message.CorrelationId;

                toSend.Recoverable = message.Recoverable;
                toSend.UseDeadLetterQueue = UseDeadLetterQueue;
                toSend.UseJournalQueue = UseJournalQueue;

                if (!string.IsNullOrEmpty(message.ReturnAddress))
                    toSend.ResponseQueue = new MessageQueue(MsmqUtilities.GetReturnAddress(message.ReturnAddress, destination));

                if (message.TimeToBeReceived < MessageQueue.InfiniteTimeout)
                    toSend.TimeToBeReceived = message.TimeToBeReceived;

                if (message.Headers == null)
                    message.Headers = new Dictionary<string, string>();

                if (!message.Headers.ContainsKey(HeaderKeys.IDFORCORRELATION))
                    message.Headers.Add(HeaderKeys.IDFORCORRELATION, null);

                if (String.IsNullOrEmpty(message.Headers[HeaderKeys.IDFORCORRELATION]))
                    message.Headers[HeaderKeys.IDFORCORRELATION] = message.IdForCorrelation;

                using (var stream = new MemoryStream())
                {
                    headerSerializer.Serialize(stream, message.Headers.Select(pair => new HeaderInfo { Key = pair.Key, Value = pair.Value }).ToList());
                    toSend.Extension = stream.GetBuffer();
                }

                toSend.AppSpecific = (int)message.MessageIntent;

                try
                {
                    if (MsmqUtilities.CurrentTransaction != null)
                        q.Send(toSend, MsmqUtilities.CurrentTransaction);
                    else
                        q.Send(toSend, GetTransactionTypeForSend());
                }
                catch (MessageQueueException ex)
                {
                    if (ex.MessageQueueErrorCode == MessageQueueErrorCode.QueueNotFound)
                        throw new QueueNotFoundException { Queue = destination };

                    throw;
                }

                message.Id = toSend.Id;
            }
        }
示例#14
0
 public void SerializationFailedForMessage(TransportMessage message, Exception e)
 {
     if (_logger.IsDebugEnabled)
      {
     _logger.Debug(string.Format("Serialization failed for message {0} -- persisting to failure store.", message.Id));
      }
      Save(new FailureInfo(message, e, true));
 }
示例#15
0
 public void ProcessingAlwaysFailsForMessage(TransportMessage message, Exception e)
 {
     if (_logger.IsDebugEnabled)
      {
     _logger.Debug(string.Format("All processing attempts failed for message {0} -- pesisting to failure store.", message.Id));
      }
      Save(new FailureInfo(message, e, false));
 }
 public void SendPopulatesMessageId()
 {
     var message = new TransportMessage().WithBody();
     Assert.That(message.Id, Is.Null);
     transport.Send(message, Target.Input.ToString());
     Assert.That(message.Id, Is.Not.Null);
     Console.WriteLine(message.Id);
 }
示例#17
0
        void IMapOutgoingTransportMessages.MapOutgoing(IMessage[] messages, TransportMessage transportMessage)
        {
            if (messages[0] is ReadyMessage)
                return;

            //when not talking to the distributor, pretend that our address is that of the distributor
            transportMessage.ReturnAddress = DistributorDataAddress;
        }
示例#18
0
 private static void SetExceptionHeaders(TransportMessage message, Exception e, string reason)
 {
     message.Headers["ExceptionInfo.Reason"] = reason;
     message.Headers["ExceptionInfo.HelpLink"] = e.HelpLink;
     message.Headers["ExceptionInfo.Message"] = e.Message;
     message.Headers["ExceptionInfo.Source"] = e.Source;
     message.Headers["ExceptionInfo.StackTrace"] = e.StackTrace;
 }
 public void SetUp()
 {
     destination = Target.Input;
     XmsUtilities.Purge(destination);
     transport = new XmsTransport(){Aliases = new Dictionary<string, string>()};
     received = null;
     sent = new TransportMessage().WithBody();
     ;
 }
        public void The_message_id_should_be_updated_with_the_native_id()
        {
            GetDestinationQueue();
            var message = new TransportMessage();

            queue.Send(message, destinationQueueName);

            Assert.NotNull(message.Id);
        }
        public void MutateOutgoing(IMessage[] messages, TransportMessage transportMessage)
        {
            if (messages[0] is ReadyMessage)
                return;

            //when not talking to the distributor, pretend that our address is that of the distributor
            if (DistributorDataQueue != null)
                transportMessage.ReturnAddress = DistributorDataQueue;
        }
示例#22
0
 //Intentionally service-locate the bus to avoid circular
 //resolution problem in the container
 void IManageMessageFailures.SerializationFailedForMessage(TransportMessage message, Exception e)
 {
     Configure.Instance.Builder.Build<IBus>()
         .Send(ErrorQueue, new SerializationFailedMessage
         {
             ExceptionInfo = e.GetInfo(),
             FailedMessage = message
         });
 }
示例#23
0
        public static TimeSpan Validate(TransportMessage message)
        {
            var numberOfRetries = TransportMessageHelpers.GetNumberOfRetries(message);

            var timeToIncreaseInTicks = TimeIncrease.Ticks*(numberOfRetries + 1);
            var timeIncrease = TimeSpan.FromTicks(timeToIncreaseInTicks);

            return numberOfRetries >= NumberOfRetries ? TimeSpan.MinValue : timeIncrease;
        }
        public void MutateIncoming(TransportMessage message)
        {
            string routingSlipJson;

            if (_bus.CurrentMessageContext.Headers.TryGetValue(Router.RoutingSlipHeaderKey, out routingSlipJson))
            {
                _routingSlip = JsonConvert.DeserializeObject<RoutingSlip>(routingSlipJson);
            }
        }
 void IMessageNotifier.RaiseMessageForwarded(ChannelType from, ChannelType to, TransportMessage message)
 {
     if (MessageForwarded != null)
         MessageForwarded(this, new MessageForwardingArgs
                                    {
                                        FromChannel = from,
                                        ToChannel = to,
                                        Message = message
                                    });
 }
 /// <summary>
 /// Make MessageIntent to be compatible between NServiceBus V3.0.0 and later versions.
 /// In publish/subscribe/unsubscribe in V3.0.0 there is no Version header.
 /// In send in V3.0.0 the header is set with 3.0.0 value.
 /// In both cases, do not mutate the MessageIntent.
 /// </summary>
 /// <param name="transportMessage">Transport Message to mutate.</param>
 public void MutateIncoming(TransportMessage transportMessage)
 {
     if (transportMessage.Headers.ContainsKey("NServiceBus.Version") && transportMessage.Headers["NServiceBus.Version"] != "3.0.0")
     {
         if ((int)transportMessage.MessageIntent == 0)
             transportMessage.MessageIntent = Enum.GetValues(typeof(MessageIntentEnum)).Cast<MessageIntentEnum>().Max();
         else
             transportMessage.MessageIntent--;
     }
 }
 /// <summary>
 /// Re-Adjust V3.0.0 subscribe and  unsubscribe messages. 
 /// Version 3.0.0 subscribe and unsubscribe message have no NServiceBus.Version set it the headers.
 /// Version 3.0.0 Send message have it with "3.0.0" set as value.
 /// Do nothing If it is  a V2.6 message (contains EnclosedMessageTypes key).
 /// </summary>
 /// <param name="transportMessage"></param>
 public void MutateIncoming(TransportMessage transportMessage)
 {
     if ((!transportMessage.Headers.ContainsKey(Headers.NServiceBusVersion) ||
         (transportMessage.Headers.ContainsKey(Headers.NServiceBusVersion)) && (transportMessage.Headers[Headers.NServiceBusVersion] == "3.0.0")) &&
         (!transportMessage.Headers.ContainsKey("EnclosedMessageTypes")))
     {
         transportMessage.MessageIntent++;
         Log.Debug("Just mutated V3.0.0 to message intent: " + transportMessage.MessageIntent);
     }
 }
        void IMutateOutgoingTransportMessages.MutateOutgoing(IMessage[] messages, TransportMessage transportMessage)
        {
            foreach(var key in staticOutgoingHeaders.Keys)
                transportMessage.Headers.Add(key, staticOutgoingHeaders[key]);

            if (messageHeaders != null)
                if (messageHeaders.ContainsKey(messages[0]))
                    foreach(var key in messageHeaders[messages[0]].Keys)
                        transportMessage.Headers.Add(key, messageHeaders[messages[0]][key]);
        }
示例#29
0
        public void Handle(TransportMessage msg)
        {
            var header = msg.Headers.Find(h => h.Key == NServiceBus.Headers.HttpTo);
            if (header == null)
            {
                Logger.Warn("Message received without the " + NServiceBus.Headers.HttpTo +
                               " header indicating to which HTTP address it should be sent."); 
                // we don't throw so that if we try to reply to bad clients, we don't DOS our system

                return;
            }

            var request = WebRequest.Create(header.Value);
            request.Method = "POST";

            var buffer = new byte[msg.BodyStream.Length];
            msg.BodyStream.Read(buffer, 0, (int)msg.BodyStream.Length);

            request.ContentType = "application/x-www-form-urlencoded";

            HeaderMapper.Map(msg, request.Headers);

            string hash = Hasher.Hash(buffer);
            request.Headers[Headers.ContentMd5Key] = hash;
            request.Headers["NServiceBus.Gateway"] = "true";
            request.Headers[Headers.FromKey] = from;

            request.ContentLength = buffer.Length;

            var stream = request.GetRequestStream();
            stream.Write(buffer, 0, buffer.Length);

            Logger.Debug("Sending message to: " + header.Value);

            var response = request.GetResponse();

            Logger.Debug("Got HTTP Response, going to check MD5.");

            var md5 = response.Headers[Headers.ContentMd5Key];
            response.Close();
            
            if (md5 == null)
            {
                Logger.Error("Integration Error: Response did not contain necessary header " + Headers.ContentMd5Key + ". Can't be sure that data arrived intact at target " + header.Value);
                return;
            }

            if (md5 == hash)
                Logger.Debug("Message transferred successfully.");
            else
            {
                Logger.Info(Headers.ContentMd5Key + " header received from client not the same as that sent. Message not transferred successfully. Trying again...");
                throw new Exception("Retrying");
            }
        }
 public static void SetHeader(TransportMessage message, string key, string value)
 {
     if (message.Headers.ContainsKey(key))
     {
         message.Headers[key] = value;
     }
     else
     {
         message.Headers.Add(key, value);
     }
 }
示例#31
0
 public void IncrementFailuresForMessage(TransportMessage message, Exception e)
 {
     failuresPerMessage.AddOrUpdate(message.Id, new Tuple<int, Exception>(1, e),
                                    (s, i) => new Tuple<int, Exception>(i.Item1 + 1, e));
 }
示例#32
0
 public void ClearFailuresForMessage(TransportMessage message)
 {
     var messageId = message.Id;
     Tuple<int, Exception> e;
     failuresPerMessage.TryRemove(messageId, out e);
 }
示例#33
0
 /// <summary>
 /// True if the transport message is a control message
 /// </summary>
 /// <param name="transportMessage"></param>
 /// <returns></returns>
 public static bool IsControlMessage(this TransportMessage transportMessage)
 {
     return(transportMessage.Headers != null &&
            transportMessage.Headers.ContainsKey(Headers.ControlMessageHeader));
 }