void Invoke(LogicalMessage message)
        {
           
            var context = new SendLogicalMessageContext(null, new SendOptions(), message);

            sendBehavior.Invoke(context, () => { });
        }
        public void Incoming_databus_properties_should_be_hydrated()
        {
            var propertyKey = Guid.NewGuid().ToString();
            var databusKey = Guid.NewGuid().ToString();

            var message = new LogicalMessage(null, new MessageWithDataBusProperty
                              {
                                  DataBusProperty = new DataBusProperty<string>("not used in this test")
                                  {
                                      Key = propertyKey
                                  }
                              }, new Dictionary<string, string> { { "NServiceBus.DataBus." + propertyKey, databusKey } }, null);
                
            using (var stream = new MemoryStream())
            {
                new BinaryFormatter().Serialize(stream, "test");
                stream.Position = 0;

                dataBus.Stub(s => s.Get(databusKey)).Return(stream);

                receiveBehavior.Invoke(new ReceiveLogicalMessageContext(null,message), ()=>{});
            }

            var instance = (MessageWithDataBusProperty)message.Instance;

            Assert.AreEqual(instance.DataBusProperty.Value, "test");
        }
 public IncomingLogicalMessageContext(LogicalMessage logicalMessage, string messageId, string replyToAddress, Dictionary<string, string> headers, IBehaviorContext parentContext)
     : base(messageId, replyToAddress, headers, parentContext)
 {
     Message = logicalMessage;
     Headers = headers;
     Set(logicalMessage);
 }
        public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
        {
            if (returnInfo == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(transportMessage.CorrelationId))
            {
                return;
            }

            if (transportMessage.Headers.ContainsKey(Headers.HttpTo) ||
                transportMessage.Headers.ContainsKey(Headers.DestinationSites))
            {
                return;
            }

            transportMessage.Headers[Headers.HttpTo] = returnInfo.HttpFrom;
            transportMessage.Headers[Headers.OriginatingSite] = returnInfo.OriginatingSite;

            if (!transportMessage.Headers.ContainsKey(Headers.RouteTo))
            {
                transportMessage.Headers[Headers.RouteTo] = returnInfo.ReplyToAddress.ToString();
            }

            // send to be backwards compatible with Gateway 3.X
            transportMessage.Headers[GatewayHeaders.LegacyMode] = returnInfo.LegacyMode.ToString();
        }
        void Invoke(LogicalMessage message)
        {
           
            var context = new OutgoingContext(null, new SendOptions(Address.Parse("MyEndpoint")), message);

            sendBehavior.Invoke(context, () => { });
        }
 public OutgoingTransportContext(LogicalMessage message, TransportMessage outgoingTransportMessage, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration, TransportMessage incomingTransportMessage = null)
     : base(configuration)
 {
     this.Set(message);
     this.Set(OutgoingTransportMessageKey, outgoingTransportMessage);
     this.Set(IncomingTransportMessageKey, incomingTransportMessage);
     this.Set(options);
 }
 public IncomingLogicalContext(LogicalMessage logicalMessage, TransportMessage message, EndpointConfiguration.ReadOnly configuration)
     : base(configuration)
 {
     this.Set(logicalMessage);
     this.Set(message);
     this.Set<MessageHandler>(null, ShouldBeSnapshotted.Yes);
     this.Set(HandlerInvocationAbortPendingKey, false);
 }
Ejemplo n.º 8
0
        void DispatchMessageToHandlersBasedOnType(IBuilder builder, LogicalMessage toHandle, LoadedMessageHandlers loadedHandlers, BehaviorContext context)
        {
            foreach (var loadedHandler in loadedHandlers.GetHandlersFor(toHandle.MessageType))
            {
                if (loadedHandler.InvocationDisabled)
                    continue;

                var handlerInstance = loadedHandler.Instance;
                try
                {
                    //until we have a outgoing pipeline that inherits context from the main one
                    if (handlerInstance is ISaga)
                    {
                        SagaContext.Current = (ISaga) handlerInstance;
                    }

                    var handlerTypeToInvoke = handlerInstance.GetType();

                    //for backwards compatibility (users can have registered their own factory
                    var factory = GetDispatcherFactoryFor(handlerTypeToInvoke, builder);

                    if (factory != null)
                    {
                        var dispatchers = factory.GetDispatcher(handlerTypeToInvoke, builder, toHandle.Instance).ToList();

                        dispatchers.ForEach(dispatch =>
                        {
                            log.DebugFormat("Dispatching message '{0}' to handler '{1}'", toHandle.MessageType, handlerTypeToInvoke);
                            try
                            {
                                dispatch();
                            }
                            catch (Exception e)
                            {
                                log.Warn(handlerTypeToInvoke.Name + " failed handling message.", e);

                                throw new TransportMessageHandlingFailedException(e);
                            }
                        });
                    }
                    else
                    {
                        loadedHandler.Invocation(handlerInstance, toHandle.Instance);
                    }

                    //for now we have to check of the chain is aborted but this will go away when we refactor the handlers to be a subpipeline
                    if (context.ChainAborted)
                    {
                        log.DebugFormat("Handler {0} requested downstream handlers of message {1} to not be invoked", handlerTypeToInvoke,toHandle.MessageType);
                        return;
                    }
                }
                finally
                {
                    SagaContext.Current = null;
                }
            }
        }
Ejemplo n.º 9
0
        public ActiveSagaInstance(ISaga saga, LoadedMessageHandlers.LoadedHandler messageHandler, LogicalMessage message)
        {
            Instance = saga;
            SagaType = saga.GetType();
            MessageToProcess = message;
            Handler = messageHandler;

            //default the invocation to disabled until we have a entity attached
            Handler.InvocationDisabled = true;
        }
        public void Outgoing_databus_properties_should_be_dehydrated()
        {
            var metadata = new MessageMetadata();
            var message = new LogicalMessage(metadata, new MessageWithDataBusProperty
            {
                DataBusProperty = new DataBusProperty<string>("test")
            }, new Dictionary<string, string>(), null);

            Invoke(message);

            dataBus.AssertWasCalled(
                x => x.Put(Arg<Stream>.Is.Anything, Arg<TimeSpan>.Is.Equal(TimeSpan.MaxValue)));
        }
        public void Time_to_live_should_be_passed_on_the_databus()
        {
            var metadata = new MessageMetadata(timeToBeReceived: TimeSpan.FromMinutes(1));
            var message = new LogicalMessage(metadata, new MessageWithExplicitTimeToLive
            {
                DataBusProperty = new DataBusProperty<string>("test")
            }, new Dictionary<string, string>(), null);

            Invoke(message);
           
            dataBus.AssertWasCalled(
                x => x.Put(Arg<Stream>.Is.Anything, Arg<TimeSpan>.Is.Equal(TimeSpan.FromMinutes(1))));
        }
Ejemplo n.º 12
0
        public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
        {
            if (Thread.CurrentPrincipal != null && Thread.CurrentPrincipal.Identity != null && !string.IsNullOrEmpty(Thread.CurrentPrincipal.Identity.Name))
            {
                transportMessage.Headers[Headers.WindowsIdentityName] = Thread.CurrentPrincipal.Identity.Name;
                return;
            }
            var windowsIdentity = WindowsIdentity.GetCurrent();
            if (windowsIdentity != null)
            {
                transportMessage.Headers[Headers.WindowsIdentityName] = windowsIdentity.Name;
            }

        }
        public void Should_not_blow_up()
        {
            var metadata = new MessageMetadata(timeToBeReceived: TimeSpan.FromDays(1));
            var message = new LogicalMessage(metadata, new MessageWithNullDataBusProperty(), new Dictionary<string, string>(), null);
            var context = new OutgoingContext(null,new SendOptions(Address.Parse("MyEndpoint")), message);

            
            using (var stream = new MemoryStream())
            {
                new BinaryFormatter().Serialize(stream, "test");
                stream.Position = 0;

                sendBehavior.Invoke(context, () => { });            
            }
        }
Ejemplo n.º 14
0
        public virtual async Task Invoke(LogicalMessage outgoingLogicalMessage, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration, TransportMessage incomingTransportMessage = null)
        {
            executingLogicalPipeline = new Queue<IOutgoingLogicalStep>(registeredlogicalPipelineSteps);
            var logicalContext = new OutgoingLogicalContext(outgoingLogicalMessage, options, configuration);
            await InvokeLogical(logicalContext)
                .ConfigureAwait(false);

            // We assume that someone in the pipeline made transport message
            var outgoingTransportMessage = logicalContext.Get<TransportMessage>();

            executingTransportPipeline = new Queue<IOutgoingTransportStep>(registeredTransportPipelineSteps);
            var transportContext = new OutgoingTransportContext(outgoingLogicalMessage, outgoingTransportMessage, options, configuration, incomingTransportMessage);
            await InvokeTransport(transportContext)
                .ConfigureAwait(false);
        }
        public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
        {
            if (transportMessage.Headers.ContainsKey(CorrIdHeader))
                return;

            var correlationIdToUse = transportMessage.CorrelationId;
            Guid correlationId;

            if (Guid.TryParse(correlationIdToUse, out correlationId))
            {
                //msmq requires the id's to be in the {guid}\{incrementing number} format so we need to fake a \0 at the end to make it compatible                
                correlationIdToUse += "\\0";
            }
            transportMessage.Headers[CorrIdHeader] = correlationIdToUse;
        }
        static bool IsMessageAllowedToStartTheSaga(LogicalMessage message, SagaMetadata sagaMetadata)
        {
            string sagaType;

            if (message.Headers.ContainsKey(Headers.SagaId) &&
                message.Headers.TryGetValue(Headers.SagaType, out sagaType))
            {
                //we want to move away from the assembly fully qualified name since that will break if you move sagas
                // between assemblies. We use the fullname instead which is enough to identify the saga
                if (sagaType.StartsWith(sagaMetadata.Name))
                {
                    //so now we have a saga id for this saga and if we can't find it we shouldn't start a new one
                    return(false);
                }
            }

            return(message.Metadata.MessageHierarchy.Any(messageType => sagaMetadata.IsMessageAllowedToStartTheSaga(messageType.FullName)));
        }
Ejemplo n.º 17
0
        IContainSagaData CreateNewSagaEntity(SagaMetadata metadata, LogicalMessage message)
        {
            var sagaEntityType = metadata.SagaEntityType;

            var sagaEntity = (IContainSagaData)Activator.CreateInstance(sagaEntityType);

            sagaEntity.Id = CombGuid.Generate();
            sagaEntity.OriginalMessageId = message.Headers[Headers.MessageId];

            string replyToAddress;

            if (message.Headers.TryGetValue(Headers.ReplyToAddress, out replyToAddress))
            {
                sagaEntity.Originator = replyToAddress;
            }

            return(sagaEntity);
        }
        public void Should_not_blow_up()
        {
            var metadata = new MessageMetadata
            {
                TimeToBeReceived = TimeSpan.FromDays(1)
            };

            var message = new LogicalMessage(metadata, new MessageWithNullDataBusProperty(), new Dictionary <string, string>(), null);
            var context = new SendLogicalMessageContext(null, new SendOptions(), message);


            using (var stream = new MemoryStream())
            {
                new BinaryFormatter().Serialize(stream, "test");
                stream.Position = 0;

                sendBehavior.Invoke(context, () => { });
            }
        }
Ejemplo n.º 19
0
        private static void CreateOutboundHeaders(IAgent agent, LogicalMessage logicalMessage)
        {
            if (logicalMessage.Headers == null)
            {
                return;
            }

            var setHeaders = new Action <LogicalMessage, string, string>((carrier, key, value) =>
            {
                if (carrier.Headers.ContainsKey(key))
                {
                    carrier.Headers.Remove(key);
                }

                carrier.Headers.Add(key, value);
            });

            agent.CurrentTransaction.InsertDistributedTraceHeaders(logicalMessage, setHeaders);
        }
Ejemplo n.º 20
0
        public virtual async Task Invoke(LogicalMessage outgoingLogicalMessage, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration, TransportMessage incomingTransportMessage = null)
        {
            this.executingLogicalPipeline = new Queue <IOutgoingLogicalStep>(this.registeredlogicalPipelineSteps);
            var logicalContext = new OutgoingLogicalContext(outgoingLogicalMessage, options, configuration);

            logicalContext.SetChain(this);
            await this.InvokeLogical(logicalContext)
            .ConfigureAwait(false);

            // We assume that someone in the pipeline made transport message
            var outgoingTransportMessage = logicalContext.Get <TransportMessage>();

            this.executingTransportPipeline = new Queue <IOutgoingTransportStep>(this.registeredTransportPipelineSteps);
            var transportContext = new OutgoingTransportContext(outgoingLogicalMessage, outgoingTransportMessage, options, configuration, incomingTransportMessage);

            transportContext.SetChain(this);
            await this.InvokeTransport(transportContext)
            .ConfigureAwait(false);
        }
Ejemplo n.º 21
0
    public void Invoke(SendLogicalMessageContext context, Action next)
    {
        #endregion
        #region copy-stream-properties-to-disk
        LogicalMessage logicalMessage   = context.MessageToSend;
        TimeSpan       timeToBeReceived = logicalMessage.Metadata.TimeToBeReceived;

        object message = logicalMessage.Instance;

        foreach (PropertyInfo property in StreamStorageHelper.GetStreamProperties(message))
        {
            Stream sourceStream = (Stream)property.GetValue(message, null);

            //Ignore null stream properties
            if (sourceStream == null)
            {
                continue;
            }
            string fileKey = GenerateKey(timeToBeReceived);

            string filePath = Path.Combine(location, fileKey);
            Directory.CreateDirectory(Path.GetDirectoryName(filePath));

            using (FileStream target = File.OpenWrite(filePath))
            {
                sourceStream.CopyTo(target);
            }

            //Reset the property to null so no other serializer attempts to use the property
            property.SetValue(message, null);

            //Dispose of the stream
            sourceStream.Dispose();

            //Store the header so on the receiving endpoint the file name is known
            string headerKey = StreamStorageHelper.GetHeaderKey(message, property);
            logicalMessage.Headers["NServiceBus.PropertyStream." + headerKey] = fileKey;
        }

        next();
        #endregion
    }
Ejemplo n.º 22
0
        /// <summary>
        /// Keeps track of related messages to make auditing possible
        /// </summary>
        public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
        {
            if (transportMessage.Headers.ContainsKey(Headers.ConversationId))
                return;

            var conversationId = CombGuid.Generate().ToString();

            if (Bus.CurrentMessageContext != null)
            {
                transportMessage.Headers[Headers.RelatedTo] = Bus.CurrentMessageContext.Id;

                string conversationIdFromCurrentMessageContext;
                if (Bus.CurrentMessageContext.Headers.TryGetValue(Headers.ConversationId, out conversationIdFromCurrentMessageContext))
                {
                    conversationId = conversationIdFromCurrentMessageContext;
                }
            }

            transportMessage.Headers[Headers.ConversationId] = conversationId;
        }
Ejemplo n.º 23
0
        IContainSagaData TryLoadSagaEntity(ISaga saga, LogicalMessage message)
        {
            var sagaType = saga.GetType();

            var sagaEntityType = Features.Sagas.GetSagaEntityTypeForSagaType(sagaType);

            var finders = GetFindersFor(message.MessageType, sagaEntityType);

            foreach (var finder in finders)
            {
                var sagaEntity = UseFinderToFindSaga(finder, message.Instance);

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

            return(null);
        }
Ejemplo n.º 24
0
        public async Task Incoming_databus_properties_should_be_hydrated()
        {
            var propertyKey = Guid.NewGuid().ToString();
            var databusKey  = Guid.NewGuid().ToString();

            var message = new LogicalMessage(new MessageMetadata(typeof(MessageWithDataBusProperty)), new MessageWithDataBusProperty
            {
                DataBusProperty = new DataBusProperty <string>("not used in this test")
                {
                    Key = propertyKey
                }
            });

            var fakeDatabus     = new FakeDataBus();
            var receiveBehavior = new DataBusReceiveBehavior(fakeDatabus, new XmlDataBusSerializer <string>(), new Conventions());

            using (var stream = new MemoryStream())
            {
                var serializer = new System.Xml.Serialization.XmlSerializer(typeof(string));
                serializer.Serialize(stream, "test");
                stream.Position = 0;

                fakeDatabus.StreamsToReturn[databusKey] = stream;

                await receiveBehavior.Invoke(
                    new IncomingLogicalMessageContext(
                        message,
                        "messageId",
                        "replyToAddress",
                        new Dictionary <string, string>
                {
                    { "NServiceBus.DataBus." + propertyKey, databusKey }
                },
                        null),
                    ctx => Task.CompletedTask);
            }

            var instance = (MessageWithDataBusProperty)message.Instance;

            Assert.AreEqual(instance.DataBusProperty.Value, "test");
        }
Ejemplo n.º 25
0
    TransportMessage GetTransportMessage(ToposMessage message)
    {
        var body          = message.Body;
        var headersOrNull = message.Headers;
        var headers       = headersOrNull?.Clone() ?? new Dictionary <string, string>();

        if (!headers.ContainsKey(ToposHeaders.MessageId))
        {
            headers[ToposHeaders.MessageId] = Guid.NewGuid().ToString();
        }

        if (!headers.ContainsKey(ToposHeaders.Time))
        {
            headers[ToposHeaders.Time] = DateTimeOffset.Now.ToIso8601DateTimeOffset();
        }

        var logicalMessage   = new LogicalMessage(headers, body);
        var transportMessage = _messageSerializer.Serialize(logicalMessage);

        return(transportMessage);
    }
Ejemplo n.º 26
0
        /// <summary>
        /// Keeps track of related messages to make auditing possible
        /// </summary>
        public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
        {
            if (transportMessage.Headers.ContainsKey(Headers.ConversationId))
            {
                return;
            }

            var conversationId = CombGuid.Generate().ToString();

            if (Bus.CurrentMessageContext != null)
            {
                transportMessage.Headers[Headers.RelatedTo] = Bus.CurrentMessageContext.Id;

                string conversationIdFromCurrentMessageContext;
                if (Bus.CurrentMessageContext.Headers.TryGetValue(Headers.ConversationId, out conversationIdFromCurrentMessageContext))
                {
                    conversationId = conversationIdFromCurrentMessageContext;
                }
            }

            transportMessage.Headers[Headers.ConversationId] = conversationId;
        }
Ejemplo n.º 27
0
        public async Task Send(object message, string partitionKey = null, Dictionary <string, string> optionalHeaders = null)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            var topic   = _topicMapper.GetTopic(message);
            var headers = optionalHeaders ?? new Dictionary <string, string>();

            if (!headers.ContainsKey(ToposHeaders.MessageId))
            {
                headers[ToposHeaders.MessageId] = Guid.NewGuid().ToString();
            }

            var logicalMessage   = new LogicalMessage(headers, message);
            var transportMessage = _messageSerializer.Serialize(logicalMessage);

            _logger.Debug("Sending message with ID {messageId} to topic {topic}", logicalMessage.GetMessageId(), topic);

            await _producerImplementation.Send(topic, partitionKey ?? "", transportMessage);
        }
        IContainSagaData TryLoadSagaEntity(SagaMetadata metadata, LogicalMessage message)
        {
            string sagaId;

            if (message.Headers.TryGetValue(Headers.SagaId, out sagaId) && !string.IsNullOrEmpty(sagaId))
            {
                var sagaEntityType = metadata.SagaEntityType;

                //since we have a saga id available we can now shortcut the finders and just load the saga
                var loaderType = typeof(LoadSagaByIdWrapper <>).MakeGenericType(sagaEntityType);

                var loader = (SagaLoader)Activator.CreateInstance(loaderType);

                return(loader.Load(SagaPersister, sagaId));
            }

            SagaFinderDefinition finderDefinition = null;

            foreach (var messageType in message.Metadata.MessageHierarchy)
            {
                if (metadata.TryGetFinder(messageType.FullName, out finderDefinition))
                {
                    break;
                }
            }

            //check if we could find a finder
            if (finderDefinition == null)
            {
                return(null);
            }

            var finderType = finderDefinition.Type;

            var finder = currentContext.Builder.Build(finderType);

            return(((SagaFinder)finder).Find(currentContext.Builder, finderDefinition, message));
        }
Ejemplo n.º 29
0
        public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
        {
            // the outgoing message instance
            var instance = logicalMessage.Instance;

            // the bytes containing the serialized outgoing messages.
            var bytes = transportMessage.Body;

            // optionally replace the Body.
            // this can be done using either the information from the logicalMessage or transportMessage
            transportMessage.Body = ServiceThatChangesBody.Mutate(logicalMessage.Instance);

            // the outgoing headers
            var headers = transportMessage.Headers;

            // optional manipulate headers

            // add a header
            headers.Add("MyHeaderKey1", "MyHeaderValue");

            // remove a header
            headers.Remove("MyHeaderKey2");
        }
 public IncomingLogicalContext(LogicalMessage message, Context parent) : base(parent)
 {
     Set(message);
 }
 public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
 {
     transportMessage.Headers["Debug"] = Debug.ToString();
 }
Ejemplo n.º 32
0
    public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
    {
        var headers = transportMessage.Headers;

        headers.Add("MutateTransportMessages_Outgoing", "ValueMutateTransportMessages_Outgoing");
    }
Ejemplo n.º 33
0
 public MessageProcessingFailedException(string message, LogicalMessage incomingMessage, Exception innerException) : base(message, innerException)
 {
     this.message         = message;
     this.incomingMessage = incomingMessage;
     this.innerException  = innerException;
 }
 public ReceiveLogicalMessageContext(BehaviorContext parentContext, LogicalMessage message)
     : base(parentContext)
 {
     Set(message);
 }
Ejemplo n.º 35
0
        private Task SendMessage(LogicalMessage outgoingLogicalMessage, DeliveryOptions options, TransportMessage incoming)
        {
            if (options.ReplyToAddress == null)
            {
                options.ReplyToAddress = this.configuration.EndpointQueue;
            }

            OutgoingPipeline outgoingPipeline = this.outgoingPipelineFactory.Create();
            return outgoingPipeline.Invoke(outgoingLogicalMessage, options, this.readOnlyConfiguration, incoming);
        }
Ejemplo n.º 36
0
 public static string GetMessageId(this LogicalMessage message)
 {
     return(message.Headers.GetValue(ToposHeaders.MessageId));
 }
Ejemplo n.º 37
0
        IContainSagaData TryLoadSagaEntity(ISaga saga, LogicalMessage message)
        {
            var sagaType = saga.GetType();

            var sagaEntityType = Features.Sagas.GetSagaEntityTypeForSagaType(sagaType);

            var finders = GetFindersFor(message.MessageType, sagaEntityType);

            foreach (var finder in finders)
            {
                var sagaEntity = UseFinderToFindSaga(finder, message.Instance);

                if (sagaEntity != null)
                    return sagaEntity;
            }

            return null;
        }
Ejemplo n.º 38
0
 public OutgoingLogicalContext(LogicalMessage message, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration)
     : base(configuration)
 {
     Set(message);
     Set(options);
 }
        void Invoke(LogicalMessage message)
        {
            var context = new OutgoingContext(null, new SendOptions(Address.Parse("MyEndpoint")), message);

            sendBehavior.Invoke(context, () => { });
        }
Ejemplo n.º 40
0
 public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
 {
     transportMessage.Headers[Headers.WindowsIdentityName] = Thread.CurrentPrincipal.Identity.Name;
 }
Ejemplo n.º 41
0
 public TransportMessage Serialize(LogicalMessage message)
 {
     throw new NotImplementedException();
 }
Ejemplo n.º 42
0
 static bool IsTimeoutMessage(LogicalMessage message)
 {
     return(!string.IsNullOrEmpty(Headers.GetMessageHeader(message.Instance, Headers.IsSagaTimeoutMessage)));
 }
Ejemplo n.º 43
0
 public IncomingLogicalContext(LogicalMessage message, Context parent) : base(parent)
 {
     Set(message);
 }
Ejemplo n.º 44
0
 static bool IsTimeoutMessage(LogicalMessage message)
 {
     return !string.IsNullOrEmpty(Headers.GetMessageHeader(message.Instance, Headers.IsSagaTimeoutMessage));
 }
 internal IncomingLogicalMessageContext(LogicalMessage logicalMessage, IIncomingPhysicalMessageContext parentContext)
     : this(logicalMessage, parentContext.MessageId, parentContext.ReplyToAddress, parentContext.Message.Headers, parentContext)
 {
 }
 public SendLogicalMessageContext(BehaviorContext parentContext, SendOptions sendOptions, LogicalMessage message)
     : base(parentContext)
 {
     Set(sendOptions);
     Set(message);
 }
 public OutgoingLogicalContext(LogicalMessage message, DeliveryOptions options, EndpointConfiguration.ReadOnly configuration)
     : base(configuration)
 {
     this.Set(message);
     this.Set(options);
 }
Ejemplo n.º 48
0
 private static string GetMessageProperty(LogicalMessage message, string propertyName)
 {
     return(message.Instance.GetType().GetProperty(propertyName)?.GetValue(message.Instance, null)?.ToString());
 }
Ejemplo n.º 49
0
 public SendLogicalMessageContext(BehaviorContext parentContext, SendOptions sendOptions, LogicalMessage message)
     : base(parentContext)
 {
     Set(sendOptions);
     Set(message);
 }
 /// <summary>
 /// Updates the message instance contained in <see cref="LogicalMessage" />.
 /// </summary>
 /// <param name="newInstance">The new instance.</param>
 public virtual void UpdateMessageInstance(object newInstance)
 {
     Message = new LogicalMessage(new MessageMetadata(newInstance.GetType()), newInstance);
 }
Ejemplo n.º 51
0
 public TransportMessage Serialize(LogicalMessage message) =>
 message.Body is byte[] bytes
Ejemplo n.º 52
0
 public void MutateOutgoing(LogicalMessage logicalMessage, TransportMessage transportMessage)
 {
 }
        LogicalMessage[] Extract(IncomingMessage physicalMessage)
        {
            // We need this check to be compatible with v3.3 endpoints, v3.3 control messages also include a body
            if (IsControlMessage(physicalMessage))
            {
                log.Debug("Received a control message. Skipping deserialization as control message data is contained in the header.");
                return(NoMessagesFound);
            }

            if (physicalMessage.Body == null || physicalMessage.Body.Length == 0)
            {
                log.Debug("Received a message without body. Skipping deserialization.");
                return(NoMessagesFound);
            }

            var messageMetadata = new List <MessageMetadata>();

            if (physicalMessage.Headers.TryGetValue(Headers.EnclosedMessageTypes, out var messageTypeIdentifier))
            {
                foreach (var messageTypeString in messageTypeIdentifier.Split(EnclosedMessageTypeSeparator))
                {
                    var typeString = messageTypeString;

                    if (DoesTypeHaveImplAddedByVersion3(typeString))
                    {
                        continue;
                    }

                    MessageMetadata metadata;

                    if (IsV4OrBelowScheduledTask(typeString))
                    {
                        metadata = messageMetadataRegistry.GetMessageMetadata(typeof(ScheduledTask));
                    }
                    else
                    {
                        metadata = messageMetadataRegistry.GetMessageMetadata(typeString);
                    }

                    if (metadata == null)
                    {
                        continue;
                    }

                    messageMetadata.Add(metadata);
                }

                if (messageMetadata.Count == 0 && physicalMessage.GetMessageIntent() != MessageIntentEnum.Publish)
                {
                    log.WarnFormat("Could not determine message type from message header '{0}'. MessageId: {1}", messageTypeIdentifier, physicalMessage.MessageId);
                }
            }

            var messageTypes      = messageMetadata.Select(metadata => metadata.MessageType).ToList();
            var messageSerializer = deserializerResolver.Resolve(physicalMessage.Headers);

            mapper.Initialize(messageTypes);

            // For nested behaviors who have an expectation ContentType existing
            // add the default content type
            physicalMessage.Headers[Headers.ContentType] = messageSerializer.ContentType;

            using (var stream = new MemoryStream(physicalMessage.Body))
            {
                var deserializedMessages = messageSerializer.Deserialize(stream, messageTypes);
                var logicalMessages      = new LogicalMessage[deserializedMessages.Length];
                for (var i = 0; i < deserializedMessages.Length; i++)
                {
                    var x = deserializedMessages[i];
                    logicalMessages[i] = logicalMessageFactory.Create(x.GetType(), x);
                }
                return(logicalMessages);
            }
        }
Ejemplo n.º 54
0
 /// <summary>
 /// Creates a new instance of <see cref="OutgoingContext"/>.
 /// </summary>
 /// <param name="parentContext">The parent context.</param>
 /// <param name="deliveryOptions">The delivery options.</param>
 /// <param name="message">The actual message to be sent out.</param>
 public OutgoingContext(BehaviorContext parentContext, DeliveryOptions deliveryOptions, LogicalMessage message)
     : base(parentContext)
 {
     Set(deliveryOptions);
     Set(OutgoingLogicalMessageKey, message);
 }
 public static bool IsControlMessage(this LogicalMessage transportMessage)
 {
     return(transportMessage.Headers != null &&
            transportMessage.Headers.ContainsKey(Headers.ControlMessageHeader));
 }
Ejemplo n.º 56
0
        internal override IContainSagaData Find(IBuilder builder, SagaFinderDefinition finderDefinition, LogicalMessage message)
        {
            var customFinderType = (Type)finderDefinition.Properties["custom-finder-clr-type"];

            var finder = (IFindSagas <TSagaData> .Using <TMessage>)builder.Build(customFinderType);

            return(finder.FindBy((TMessage)message.Instance));
        }
Ejemplo n.º 57
0
 internal abstract IContainSagaData Find(IBuilder builder, SagaFinderDefinition finderDefinition, LogicalMessage message);
        /// <summary>
        /// Creates a <see cref="IIncomingLogicalMessageContext" /> based on the current context.
        /// </summary>
        public static IIncomingLogicalMessageContext CreateIncomingLogicalMessageContext(this StageConnector<IIncomingPhysicalMessageContext, IIncomingLogicalMessageContext> stageConnector, LogicalMessage logicalMessage, IIncomingPhysicalMessageContext sourceContext)
        {
            Guard.AgainstNull(nameof(logicalMessage), logicalMessage);
            Guard.AgainstNull(nameof(sourceContext), sourceContext);

            return new IncomingLogicalMessageContext(logicalMessage, sourceContext);
        }