public void Deliver(Message message)
        {
            var transportMessageToSend = serializer.Serialize(message);
            var receivedTransportMessage = transportMessageToSend.ToReceivedTransportMessage();

            messageQueue.Enqueue(receivedTransportMessage);
        }
예제 #2
0
 /// <summary>
 /// Serializes the given <see cref="Message"/> into a <see cref="TransportMessage"/>
 /// </summary>
 public async Task<TransportMessage> Serialize(Message message)
 {
     var jsonText = JsonConvert.SerializeObject(message.Body, _settings);
     var bytes = _encoding.GetBytes(jsonText);
     var headers = message.Headers.Clone();
     headers[Headers.ContentType] = $"{JsonContentType};charset={_encoding.HeaderName}";
     return new TransportMessage(headers, bytes);
 }
예제 #3
0
 /// <summary>
 /// Serializes the given <see cref="Message"/> into a <see cref="TransportMessage"/>
 /// </summary>
 public async Task<TransportMessage> Serialize(Message message)
 {
     var jsonText = JsonConvert.SerializeObject(message.Body, _settings);
     var bytes = _encoding.GetBytes(jsonText);
     var headers = message.Headers.Clone();
     var messageType = message.Body.GetType();
     headers[Headers.Type] = messageType.GetSimpleAssemblyQualifiedName();
     headers[Headers.ContentType] = string.Format("{0};charset={1}", JsonContentType, _encoding.HeaderName);
     return new TransportMessage(headers, bytes);
 }
예제 #4
0
 public async Task<TransportMessage> Serialize(Message message)
 {
     var jsonText = JsonConvert.SerializeObject(message.Body, _settings);
     var bytes = DefaultEncoding.GetBytes(jsonText);
     var headers = message.Headers.Clone();
     var messageType = message.Body.GetType();
     headers[Headers.Type] = messageType.GetSimpleAssemblyQualifiedName();
     headers[Headers.ContentType] = JsonUtf8ContentType;
     return new TransportMessage(headers, bytes);
 }
예제 #5
0
 /// <summary>
 /// Serializes the given <see cref="Message"/> into a <see cref="TransportMessage"/>
 /// </summary>
 public async Task<TransportMessage> Serialize(Message message)
 {
     var body = message.Body;
     var jsonText = JSON.Serialize(body);
     var bytes = Encoding.GetBytes(jsonText);
     var headers = message.Headers.Clone();
     var messageType = body.GetType();
     headers[Headers.Type] = messageType.GetSimpleAssemblyQualifiedName();
     headers[Headers.ContentType] = JsonUtf8ContentType;
     return new TransportMessage(headers, bytes);
 }
예제 #6
0
 Dictionary<string, string> GetMetadata(ISagaData sagaData, object handler, Message message)
 {
     return new Dictionary<string, string>
     {
         {SagaAuditingMetadataKeys.HandleQueue, _transport.Address},
         {SagaAuditingMetadataKeys.SagaDataType, sagaData.GetType().GetSimpleAssemblyQualifiedName()},
         {SagaAuditingMetadataKeys.SagaHandlerType, handler.GetType().GetSimpleAssemblyQualifiedName()},
         {SagaAuditingMetadataKeys.MessageType, message.GetMessageType()},
         {SagaAuditingMetadataKeys.MessageId, message.GetMessageId()},
         {SagaAuditingMetadataKeys.MachineName, Environment.MachineName},
     };
 }
예제 #7
0
        /// <summary>
        /// Serializes the given logical message to a transport message using MsgPack. Adds the
        /// <see cref="Headers.ContentType"/> with the <code>application/x-msgpack</code> value
        /// and sets the <see cref="Headers.Type"/> to the short assembly-qualified .NET type name of the message body
        /// </summary>
        public async Task<TransportMessage> Serialize(Message message)
        {
            var headers = message.Headers.Clone();
            var body = message.Body;

            headers[Headers.ContentType] = MsgPackContentType;
            headers[Headers.Type] = body.GetType().GetSimpleAssemblyQualifiedName();

            var bytes = _packer.Pack(body);

            return new TransportMessage(headers, bytes);
        }
예제 #8
0
 public async Task CanCaptureIdentityInTheMessage()
 {
     var step = new CapturePrincipalInOutgoingMessage(new DummySerializer());
     var instance = new Message(new Dictionary<string, string>(), new object());
     var context = new OutgoingStepContext(instance, new DefaultTransactionContext(),
         new DestinationAddresses(new[] { "Larry" }));
     
     context.Save(instance);
     await step.Process(context, async () => { });
     Assert.That(instance.Headers.ContainsKey(CapturePrincipalInOutgoingMessage.PrincipalCaptureKey));
     Assert.AreEqual(instance.Headers[CapturePrincipalInOutgoingMessage.PrincipalCaptureKey], "Larry");
 }
        public void Deliver(Message message)
        {
            var transportMessageToSend = serializer.Serialize(message);
            var receivedTransportMessage = new ReceivedTransportMessage
                                               {
                                                   Id = NewMessageId(),
                                                   Body = transportMessageToSend.Body,
                                                   Label = transportMessageToSend.Label,
                                               };

            messageQueue.Enqueue(receivedTransportMessage);
        }
예제 #10
0
 public async Task CanRestoreIdentity()
 {
     var step = new RestorePrincipalFromIncomingMessage(new DummySerializer());
     var instance = new Message(new Dictionary<string, string>(), new object());
     var context = new IncomingStepContext(new TransportMessage(new Dictionary<string, string>(), new byte[0] ), new DefaultTransactionContext() );
     instance.Headers[CapturePrincipalInOutgoingMessage.PrincipalCaptureKey] = "Larry";
     context.Save(instance);
     await step.Process(context, async () =>
     {
         Assert.AreEqual(ClaimsPrincipal.Current.Identity.Name, "Larry");
     });
 }
        ClaimsPrincipal GetClaimsPrincipalOrNull(Message message)
        {
            string serializedPrincipal;
            if (!message.Headers.TryGetValue(CapturePrincipalInOutgoingMessage.PrincipalCaptureKey, out serializedPrincipal))
            {
                return null;
            }

            var newPrincipal = _serializer.Deserialize(serializedPrincipal);

            return newPrincipal;
        }
예제 #12
0
        static TimeSpan RunTest(int numberOfMessages, PipelineStepProfilerStats profilerStats)
        {
            using (var adapter = new BuiltinHandlerActivator())
            {
                var network = new InMemNetwork();

                Configure.With(adapter)
                    .Logging(l => l.Console(LogLevel.Warn))
                    .Transport(t => t.UseInMemoryTransport(network, "perftest"))
                    .Options(o =>
                    {
                        o.SetNumberOfWorkers(0);
                        o.SetMaxParallelism(1);

                        o.Decorate<IPipeline>(c => new PipelineStepProfiler(c.Get<IPipeline>(), profilerStats));
                    })
                    .Start();

                var serializer = new JsonSerializer();
                var boy = new SomeMessage("hello there!");

                numberOfMessages.Times(() =>
                {
                    var headers = new Dictionary<string, string> { { Headers.MessageId, Guid.NewGuid().ToString() } };
                    var message = new Message(headers, boy);
                    var transportMessage = serializer.Serialize(message).Result;
                    var inMemTransportMessage = transportMessage.ToInMemTransportMessage();

                    network.Deliver("perftest", inMemTransportMessage);
                });


                var numberOfReceivedMessages = 0;
                var gotAllMessages = new ManualResetEvent(false);

                adapter.Handle<SomeMessage>(async m =>
                {
                    numberOfReceivedMessages++;
                    if (numberOfReceivedMessages == numberOfMessages)
                    {
                        gotAllMessages.Set();
                    }
                });

                var stopwatch = Stopwatch.StartNew();

                adapter.Bus.Advanced.Workers.SetNumberOfWorkers(1);
                gotAllMessages.WaitOrDie(TimeSpan.FromSeconds(30));

                return stopwatch.Elapsed;
            }
        }
예제 #13
0
        /// <summary>
        /// Serializes the given <see cref="Message"/> into a <see cref="TransportMessage"/> using the Wire format,
        /// adding a <see cref="Headers.ContentType"/> header with the value of <see cref="WireContentType"/>
        /// </summary>
        public async Task<TransportMessage> Serialize(Message message)
        {
            using (var destination = new MemoryStream())
            {
                _serializer.Serialize(message.Body, destination);

                var headers = message.Headers.Clone();

                headers[Headers.ContentType] = WireContentType;

                return new TransportMessage(headers, destination.ToArray());
            }
        }
예제 #14
0
파일: TestMessage.cs 프로젝트: JanRou/Rebus
        public void CanGenerateSensibleLabelEvenWhenSendingRawStringsOfArbitraryLengthAndFormatting(string crazyMessageThatMustBeHandled, string expectedLabel)
        {
            // arrange
            var message = new Message
                {
                    Messages = new object[] {crazyMessageThatMustBeHandled}
                };

            // act
            var label = message.GetLabel();

            // assert
            label.ShouldBe(expectedLabel);
        }
예제 #15
0
        static string GetCorrelationIdToAssign(IncomingStepContext incomingStepContext, Message outgoingMessage)
        {
            // if we're handling an incoming message right now, let either current correlation ID or the message ID flow
            if (incomingStepContext == null)
            {
                return outgoingMessage.Headers.GetValue(Headers.MessageId);
            }
            
            var incomingMessage = incomingStepContext.Load<Message>();

            var correlationId = incomingMessage.Headers.GetValueOrNull(Headers.CorrelationId)
                                ?? incomingMessage.Headers.GetValue(Headers.MessageId);

            return correlationId;
        }
예제 #16
0
        public TransportMessageToSend Serialize(Message message)
        {
            using (var memoryStream = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(memoryStream, message);
                memoryStream.Position = 0;

                return new TransportMessageToSend
                           {
                               Label = message.GetLabel(),
                               Headers = message.Headers.ToDictionary(k => k.Key, v => v.Value),
                               Body = memoryStream.ToArray(),
                           };
            }
        }
예제 #17
0
        public async Task<TransportMessage> Serialize(Message message)
        {
            using (var destination = new MemoryStream())
            {
                var headers = message.Headers.Clone();

                if (!headers.ContainsKey(Headers.Type))
                {
                    headers[Headers.Type] = message.Body.GetType().GetSimpleAssemblyQualifiedName();
                }

                _runtimeTypeModel.Serialize(destination, message.Body);

                return new TransportMessage(headers, destination.ToArray());
            }
        }
예제 #18
0
        public async Task<TransportMessage> Serialize(Message message)
        {
            var transportMessage = await _serializer.Serialize(message);
            var body = transportMessage.Body;

            if (body.Length < _bodySizeThresholdBytes)
            {
                return transportMessage;
            }

            var headers = transportMessage.Headers.Clone();
            var compressedBody = _zipper.Zip(transportMessage.Body);

            headers[Headers.ContentEncoding] = GzipEncodingHeader;

            var compressedTransportMessage = new TransportMessage(headers, compressedBody);

            return compressedTransportMessage;
        }
예제 #19
0
파일: RebusBus.cs 프로젝트: geffzhang/Rebus
        async Task InnerSend(IEnumerable<string> destinationAddresses, Message logicalMessage)
        {
            var currentTransactionContext = AmbientTransactionContext.Current;

            if (currentTransactionContext != null)
            {
                await SendUsingTransactionContext(destinationAddresses, logicalMessage, currentTransactionContext);
            }
            else
            {
                using (var context = new DefaultTransactionContext())
                {
                    await SendUsingTransactionContext(destinationAddresses, logicalMessage, context);

                    await context.Complete();
                }
            }
        }
            public void Deliver(string text)
            {
                var message =
                    new Message
                    {
                        Headers = new Dictionary<string, object>(),
                        Messages = new object[] { text }
                    };

                var transportMessage = serializer.Serialize(message);

                subliminalMessages.Enqueue(transportMessage.ToReceivedTransportMessage());
            }
예제 #21
0
 /// <summary>
 /// Constructs the step context, initially stashing the given <see cref="Message"/>, list of <see cref="DestinationAddresses"/> and <see cref="ITransactionContext"/> into its bag of objects
 /// </summary>
 public OutgoingStepContext(Message logicalMessage, ITransactionContext transactionContext, DestinationAddresses destinationAddresses)
 {
     Save(logicalMessage);
     Save(destinationAddresses);
     Save(transactionContext);
 }
 public void Deliver(Message message)
 {
     messageQueue.Enqueue(serializer.Serialize(message));
 }
예제 #23
0
        /// <summary>
        /// Establishes the idempotent context for the specified message context.
        /// </summary>
        /// <param name="idempotentSagaData">The idempotent saga data.</param>
        /// <param name="messageContext">The message context.</param>
        private void EstablishIdempotencyContextFor(IIdempotentSagaData idempotentSagaData, IMessageContext messageContext)
        {
            var id = messageContext.RebusTransportMessageId;
            var serializer = backbone.SerializeMessages;

            log.Debug("Established idempotent saga context for: {0} (Handler: {1})", id, idempotentSagaData.GetType());

            var message = new Message()
            {
                Headers = messageContext.Headers,
                Messages = new object[] { messageContext.CurrentMessage }
            };
            var serializedMessage = serializer.Serialize(message);

            var executionResults = new IdempotentSagaResults(id, serializedMessage, serializer.GetType());
            messageContext.Items[Headers.IdempotentSagaResults] = executionResults;
        }
예제 #24
0
        /// <summary>
        /// Stores any sent message during an idempotence message processing into a list which allows future re-playing.
        /// </summary>
        /// <param name="destinations">The destinations.</param>
        /// <param name="message">The message.</param>
        /// <param name="published">if set to <c>true</c> [published].</param>
        private void StoreHandlingSideEffects(IEnumerable<string> destinations, Message message, bool published)
        {
            if (MessageContext.HasCurrent)
            {
                var messageContext = MessageContext.GetCurrent();

                if (messageContext.Items.ContainsKey(Headers.IdempotentSagaResults))
                {
                    var handlingData = messageContext.Items[Headers.IdempotentSagaResults] as IdempotentSagaResults;

                    if (handlingData != null)
                    {
                        log.Debug("Intercepting message {0} to [{1}] as an idempotent side-effect.", 
                            published ? "publication" : "transmission", destinations.Aggregate((cur, next) => cur + ", " + next));

                        var serializer = backbone.SerializeMessages;
                        var serializedMessage = serializer.Serialize(message);
                        handlingData.SideEffects.Add(
                            new IdempotentSagaResults.SideEffect(
                                destinations, serializedMessage.Headers, serializedMessage.Body, serializer.GetType()));
                    }
                }
            }
        }
예제 #25
0
        public TransportMessage Serialize(Message message)
        {
            var messageAsString = JsonConvert.SerializeObject(message, Formatting.Indented, Settings);

            return new TransportMessage {Data = Encoding.GetBytes(messageAsString)};
        }
예제 #26
0
 internal void RaiseBeforeInternalSend(IEnumerable<string> destinations, Message message, bool published)
 {
     BeforeInternalSend(destinations, message, published);
 }
예제 #27
0
 public TimedMessage(Message message)
 {
     Message = message;
     Time = DateTime.UtcNow;
 }
예제 #28
0
        /// <summary>
        /// Called when sending messages
        /// </summary>
        public async Task<string> GetDestinationAddress(Message message)
        {
            if (message == null) throw new ArgumentNullException("message");

            throw new NotImplementedException("don't know what to do here yet");
        }
예제 #29
0
파일: RebusBus.cs 프로젝트: geffzhang/Rebus
        async Task SendUsingTransactionContext(IEnumerable<string> destinationAddresses, Message logicalMessage, ITransactionContext transactionContext)
        {
            var context = new OutgoingStepContext(logicalMessage, transactionContext, new DestinationAddresses(destinationAddresses));

            await _pipelineInvoker.Invoke(context, _pipeline.SendPipeline());
        }