public void Should_serialize_an_empty_message() { byte[] serializedMessageData; var serializer = new TSerializer(); var message = new SubscriptionRefresh(Enumerable.Empty <SubscriptionInformation>()); using (var output = new MemoryStream()) { serializer.Serialize(output, new SendContext <SubscriptionRefresh>(message)); serializedMessageData = output.ToArray(); Trace.WriteLine(Encoding.UTF8.GetString(serializedMessageData)); } using (var input = new MemoryStream(serializedMessageData)) { var receiveContext = ReceiveContext.FromBodyStream(input); serializer.Deserialize(receiveContext); IConsumeContext <SubscriptionRefresh> context; receiveContext.TryGetContext(out context).ShouldBeTrue(); context.ShouldNotBeNull(); context.Message.Subscriptions.Count.ShouldEqual(message.Subscriptions.Count); } }
public void ShouldWork() { byte[] serializedMessageData; var serializer = new TSerializer(); using (var output = new MemoryStream()) { serializer.Serialize(output, new SendContext <PingMessage>(Message)); serializedMessageData = output.ToArray(); Trace.WriteLine(Encoding.UTF8.GetString(serializedMessageData)); } using (var input = new MemoryStream(serializedMessageData)) { var receiveContext = ReceiveContext.FromBodyStream(input); serializer.Deserialize(receiveContext); IConsumeContext <PingMessage> context; receiveContext.TryGetContext <PingMessage>(out context).ShouldBeTrue(); context.ShouldNotBeNull(); context.Message.ShouldEqual(Message); } }
void VerifyMessageHeaderIsPassed(Action <ISendContext <PingMessage> > setHeaderAction, Action <IConsumeContext> checkHeaderAction) { byte[] data; var serializer = new XmlMessageSerializer(); var message = new PingMessage(); using (var output = new MemoryStream()) { var sendContext = new SendContext <PingMessage>(message); setHeaderAction(sendContext); serializer.Serialize(output, sendContext); data = output.ToArray(); } //Trace.WriteLine(Encoding.UTF8.GetString(data)); using (var input = new MemoryStream(data)) { var receiveContext = ReceiveContext.FromBodyStream(input); serializer.Deserialize(receiveContext); checkHeaderAction(receiveContext); } }
protected T SerializeAndReturn <T>(T obj) where T : class { byte[] serializedMessageData; using (var output = new MemoryStream()) { _serializer.Serialize(output, obj.ToSendContext()); serializedMessageData = output.ToArray(); // Trace.WriteLine(Encoding.UTF8.GetString(serializedMessageData)); } using (var input = new MemoryStream(serializedMessageData)) { IReceiveContext receiveContext = ReceiveContext.FromBodyStream(input); _serializer.Deserialize(receiveContext); IConsumeContext <T> context; receiveContext.TryGetContext(out context).ShouldBeTrue(); context.ShouldNotBeNull(); return(context.Message); } }
public void MoveErrorMessageToOriginQueue(QueueItem itm) { if (string.IsNullOrEmpty(itm.Id)) { throw new ArgumentException("MessageId can not be null or empty"); } if (itm.Queue.Type != QueueType.Error) { throw new ArgumentException("Queue is not of type Error, " + itm.Queue.Type); } var mgr = new ErrorManager(); // TODO: // Check if Clustered Queue, due if Clustered && NonTransactional, then Error //var deserializer = new XmlMessageSerializer(); XmlMessageSerializer _serializer = new XmlMessageSerializer(); using (var stream = new MemoryStream(UTF8Encoding.Default.GetBytes(itm.Content ?? ""))) { var rcx = ReceiveContext.FromBodyStream(stream); _serializer.Deserialize(rcx); //var query = rcx.DestinationAddress.Query; //var errorQueue = rcx.DestinationAddress.OriginalString.Replace(query, "") + "_error"; //mgr.InputQueue = new EndpointAddress(errorQueue); mgr.ReturnMessageToSourceQueue(itm.Id, rcx); } }
public void The_encrypted_serializer_should_be_awesome() { byte[] serializedMessageData; string key = "eguhidbehumjdemy1234567890123456"; var serializer = new PreSharedKeyEncryptedMessageSerializer(key, new TSerializer()); using (var output = new MemoryStream()) { serializer.Serialize(output, _message.ToSendContext()); serializedMessageData = output.ToArray(); // Trace.WriteLine(Encoding.UTF8.GetString(serializedMessageData)); } using (var input = new MemoryStream(serializedMessageData)) { ReceiveContext receiveContext = ReceiveContext.FromBodyStream(input); serializer.Deserialize(receiveContext); IConsumeContext <PartialSerializationTestMessage> context; receiveContext.TryGetContext(out context).ShouldBeTrue(); context.ShouldNotBeNull(); context.Message.ShouldEqual(_message); } }
public void Receive(Func <IReceiveContext, Action <IReceiveContext> > callback, TimeSpan timeout) { AddManagementBinding(); AddReceiverBinding(); _connectionHandler.Use(connection => { BrokeredMessage message = _receiver.Get(timeout); if (message == null) { return; } using (var body = new MemoryStream(message.GetBody <MessageEnvelope>().ActualBody, false)) { ReceiveContext context = ReceiveContext.FromBodyStream(body); context.SetMessageId(message.MessageId); context.SetInputAddress(Address); context.SetCorrelationId(message.CorrelationId); context.SetContentType(message.ContentType); if (_logger.IsDebugEnabled) { TraceMessage(context); } Action <IReceiveContext> receive = callback(context); if (receive == null) { Address.LogSkipped(message.MessageId); return; } receive(context); try { message.Complete(); } catch (MessageLockLostException ex) { if (_logger.IsErrorEnabled) { _logger.Error("Message Lock Lost on message Complete()", ex); } } catch (MessagingException ex) { if (_logger.IsErrorEnabled) { _logger.Error("Generic MessagingException thrown", ex); } } } }); }
public SanitizedRoutingSlip(IConsumeContext <RoutingSlip> context) { using (var ms = new MemoryStream()) { context.BaseContext.CopyBodyTo(ms); ReceiveContext receiveContext = ReceiveContext.FromBodyStream(ms, false); if (string.Compare(context.ContentType, "application/vnd.masstransit+json", StringComparison.OrdinalIgnoreCase) == 0) { _jsonContext = TranslateJsonBody(receiveContext); } else if (string.Compare(context.ContentType, "application/vnd.masstransit+xml", StringComparison.OrdinalIgnoreCase) == 0) { _jsonContext = TranslateXmlBody(receiveContext); } else { throw new InvalidOperationException("Only JSON and XML messages can be scheduled"); } } IConsumeContext <JToken> messageTokenContext; if (!_jsonContext.TryGetContext(out messageTokenContext)) { throw new InvalidOperationException("Unable to retrieve JSON token"); } _messageToken = messageTokenContext.Message; RoutingSlip routingSlip = _jsonContext.Message; TrackingNumber = routingSlip.TrackingNumber; _variablesToken = _messageToken["variables"]; Variables = routingSlip.Variables ?? GetEmptyObject(); Itinerary = (routingSlip.Itinerary ?? new List <Activity>()) .Select(x => (Activity) new SanitizedActivity(x)) .ToList(); ActivityLogs = (routingSlip.ActivityLogs ?? new List <ActivityLog>()) .Select(x => (ActivityLog) new SanitizedActivityLog(x)) .ToList(); ActivityExceptions = (routingSlip.ActivityExceptions ?? new List <ActivityException>()) .Select(x => (ActivityException) new SanitizedActivityException(x)) .ToList(); }
public void Should_receive_the_message_in_the_type_requested() { using (var buffer = new MemoryStream(Encoding.UTF8.GetBytes(_message))) { IReceiveContext receiveContext = ReceiveContext.FromBodyStream(buffer); _serializer.Deserialize(receiveContext); IConsumeContext <A> context; receiveContext.TryGetContext <A>(out context).ShouldBeTrue(); context.ShouldNotBeNull(); } }
protected void TestSerialization <T>(T message) where T : class { byte[] data; var serializer = new TSerializer(); _sourceUri = new Uri("loopback://localhost/source"); _responseUri = new Uri("loopback://localhost/response"); _faultUri = new Uri("loopback://localhost/fault"); _destinationUri = new Uri("loopback://localhost/destination"); _retryCount = 69; using (var output = new MemoryStream()) { ISendContext <T> context = message.ToSendContext(); context.SetSourceAddress(_sourceUri); context.SendResponseTo(_responseUri); context.SendFaultTo(_faultUri); context.SetDestinationAddress(_destinationUri); context.SetRetryCount(_retryCount); serializer.Serialize(output, context); data = output.ToArray(); } // Trace.WriteLine(Encoding.UTF8.GetString(data)); using (MemoryStream input = new MemoryStream(data)) { IReceiveContext context = ReceiveContext.FromBodyStream(input); serializer.Deserialize(context); IConsumeContext <T> messageContext; context.TryGetContext <T>(out messageContext).ShouldBeTrue(); messageContext.ShouldNotBeNull(); message.Equals(messageContext.Message).ShouldBeTrue(); message.ShouldNotBeTheSameAs(messageContext.Message); Assert.AreEqual(_retryCount, context.RetryCount); Assert.AreEqual(_sourceUri, context.SourceAddress); Assert.AreEqual(_responseUri, context.ResponseAddress); Assert.AreEqual(_faultUri, context.FaultAddress); Assert.AreEqual(_destinationUri, context.DestinationAddress); // Assert.AreEqual(message.GetType().ToMessageName(), CurrentMessage.Headers.MessageType); } }
public void Should_handle_the_uri_type() { var serializer = new VersionOneXmlMessageSerializer(); using (var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(AnotherVersion4Message))) { var receiveContext = ReceiveContext.FromBodyStream(bodyStream); serializer.Deserialize(receiveContext); IConsumeContext <ComplaintAdded> context; receiveContext.TryGetContext <ComplaintAdded>(out context).ShouldBeTrue(); context.ShouldNotBeNull(); } }
protected T Return <T>(byte[] serializedMessageData) where T : class { using (var input = new MemoryStream(serializedMessageData)) { IReceiveContext receiveContext = ReceiveContext.FromBodyStream(input); _serializer.Deserialize(receiveContext); IConsumeContext <T> context; receiveContext.TryGetContext(out context).ShouldBeTrue(); context.ShouldNotBeNull(); return(context.Message); } }
public void Should_not_cause_fatal_explosions_of_the_fiery_death_kind() { var serializer = new VersionOneXmlMessageSerializer(); using (var bodyStream = new MemoryStream(Encoding.UTF8.GetBytes(Version4Message))) { var receiveContext = ReceiveContext.FromBodyStream(bodyStream); serializer.Deserialize(receiveContext); IConsumeContext <ComplaintAdded> context; receiveContext.TryGetContext <ComplaintAdded>(out context).ShouldBeTrue(); context.ShouldNotBeNull(); } }
public void Receive(Func <IReceiveContext, Action <IReceiveContext> > lookupSinkChain, TimeSpan timeout) { var handler = new TimeoutHandler(timeout); handler.Run((timedOut) => _connectionHandler.Use(connection => { foreach (var message in connection.Queue.Messages) { if (timedOut()) { break; } using (var body = new MemoryStream(message.Body)) { var context = ReceiveContext.FromBodyStream(body, Address.IsTransactional); context.SetMessageId("{0}".FormatWith(message.Id)); context.SetInputAddress(Address); byte[] extension = message.Extension; if (extension.Length > 0) { var headers = TransportMessageHeaders.Create(extension); context.SetContentType(headers["Content-Type"]); context.SetOriginalMessageId(headers["Original-Message-Id"]); } Action <IReceiveContext> receive = lookupSinkChain(context); if (receive != null) { if (!connection.Queue.TryRemoveMessage(message)) { continue; } receive(context); } } } })); }
public void Just_how_fast_are_you() { Trace.WriteLine("Serializer: " + typeof(TSerializer).Name); var message = new SerializationTestMessage { DecimalValue = 123.45m, LongValue = 098123213, BoolValue = true, ByteValue = 127, IntValue = 123, DateTimeValue = new DateTime(2008, 9, 8, 7, 6, 5, 4), TimeSpanValue = 30.Seconds(), GuidValue = Guid.NewGuid(), StringValue = "Chris's Sample Code", DoubleValue = 1823.172, }; var serializer = new TSerializer(); //warm it up for (int i = 0; i < 10; i++) { byte[] data; using (var output = new MemoryStream()) { serializer.Serialize(output, message.ToSendContext()); data = output.ToArray(); } using (var input = new MemoryStream(data)) { serializer.Deserialize(ReceiveContext.FromBodyStream(input)); } } Stopwatch timer = Stopwatch.StartNew(); const int iterations = 50000; for (int i = 0; i < iterations; i++) { using (var output = new MemoryStream()) { serializer.Serialize(output, message.ToSendContext()); } } timer.Stop(); long perSecond = iterations * 1000 / timer.ElapsedMilliseconds; var msg = string.Format("Serialize: {0}ms, Rate: {1} m/s", timer.ElapsedMilliseconds, perSecond); Trace.WriteLine(msg); byte[] sample; using (var output = new MemoryStream()) { serializer.Serialize(output, message.ToSendContext()); sample = output.ToArray(); } timer = Stopwatch.StartNew(); for (int i = 0; i < 50000; i++) { using (var input = new MemoryStream(sample)) { serializer.Deserialize(ReceiveContext.FromBodyStream(input)); } } timer.Stop(); perSecond = iterations * 1000 / timer.ElapsedMilliseconds; msg = string.Format("Deserialize: {0}ms, Rate: {1} m/s", timer.ElapsedMilliseconds, perSecond); Trace.WriteLine(msg); }
protected bool EnumerateQueue(Func <IReceiveContext, Action <IReceiveContext> > receiver, TimeSpan timeout) { if (_disposed) { throw new ObjectDisposedException("The transport has been disposed: '{0}'".FormatWith(Address)); } bool received = false; _connectionHandler.Use(connection => { using (MessageEnumerator enumerator = connection.Queue.GetMessageEnumerator2()) { // if (_log.IsDebugEnabled) // _log.DebugFormat("Enumerating endpoint: {0} ({1}ms)", Address, timeout); while (enumerator.MoveNext(timeout)) { if (enumerator.Current == null) { if (_log.IsDebugEnabled) { _log.DebugFormat("Current message was null while enumerating endpoint"); } continue; } Message peekMessage = enumerator.Current; using (peekMessage) { IReceiveContext context = ReceiveContext.FromBodyStream(peekMessage.BodyStream); context.SetMessageId(peekMessage.Id); context.SetInputAddress(_address); byte[] extension = peekMessage.Extension; if (extension.Length > 0) { TransportMessageHeaders headers = TransportMessageHeaders.Create(extension); context.SetContentType(headers["Content-Type"]); } Action <IReceiveContext> receive = receiver(context); if (receive == null) { if (_log.IsDebugEnabled) { _log.DebugFormat("SKIP:{0}:{1}", Address, peekMessage.Id); } continue; } ReceiveMessage(enumerator, timeout, message => { if (message == null) { throw new TransportException(Address.Uri, "Unable to remove message from queue: " + context.MessageId); } if (message.Id != context.MessageId) { throw new TransportException(Address.Uri, string.Format( "Received message does not match current message: ({0} != {1})", message.Id, context.MessageId)); } if (_messageLog.IsDebugEnabled) { _messageLog.DebugFormat("RECV:{0}:{1}:{2}", _address.InboundFormatName, message.Label, message.Id); } receive(context); received = true; }); } } } }); return(received); }
public void Receive(Func <IReceiveContext, Action <IReceiveContext> > callback, TimeSpan timeout) { AddConsumerBinding(); _connectionHandler.Use(connection => { BrokeredMessage message = _consumer.Get(timeout); if (message == null) { return; } using (var stream = message.GetBody <Stream>()) { ReceiveContext context = ReceiveContext.FromBodyStream(stream); context.SetMessageId(message.MessageId); context.SetInputAddress(Address); context.SetCorrelationId(message.CorrelationId); context.SetContentType(message.ContentType); Action <IReceiveContext> receive = callback(context); if (receive == null) { Address.LogSkipped(message.MessageId); return; } try { receive(context); } catch (Exception ex) { if (_logger.IsErrorEnabled) { _logger.Error("Consumer threw an exception", ex); } message.Abandon(); } try { message.Complete(); } catch (MessageLockLostException ex) { if (_logger.IsErrorEnabled) { _logger.Error("Message Lock Lost on message Complete()", ex); } } catch (MessagingException ex) { if (_logger.IsErrorEnabled) { _logger.Error("Generic MessagingException thrown", ex); } } } }); }
public void Receive(Func <IReceiveContext, Action <IReceiveContext> > callback, TimeSpan timeout) { int messageCount = Count; bool waited = false; if (messageCount == 0) { if (!_messageReady.WaitOne(timeout, true)) { return; } waited = true; } bool monitorExitNeeded = true; if (!Monitor.TryEnter(_messageLock, timeout)) { return; } try { for (LinkedListNode <LoopbackMessage> iterator = _messages.First; iterator != null; iterator = iterator.Next) { if (iterator.Value != null) { LoopbackMessage message = iterator.Value; if (message.ExpirationTime.HasValue && message.ExpirationTime <= DateTime.UtcNow) { _messages.Remove(iterator); return; } ReceiveContext context = ReceiveContext.FromBodyStream(message.Body); context.SetMessageId(message.MessageId); context.SetContentType(message.ContentType); context.SetOriginalMessageId(message.OriginalMessageId); if (message.ExpirationTime.HasValue) { context.SetExpirationTime(message.ExpirationTime.Value); } Action <IReceiveContext> receive = callback(context); if (receive == null) { continue; } _messages.Remove(iterator); using (message) { Monitor.Exit(_messageLock); monitorExitNeeded = false; receive(context); return; } } } if (waited) { return; } // we read to the end and none were accepted, so we are going to wait until we get another in the queue _messageReady.WaitOne(timeout, true); } finally { if (monitorExitNeeded) { Monitor.Exit(_messageLock); } } }
protected void EnumerateQueue(Func <IReceiveContext, Action <IReceiveContext> > receiver, TimeSpan timeout) { if (_disposed) { throw new ObjectDisposedException("The transport has been disposed: '{0}'".FormatWith(Address)); } _connectionHandler.Use(connection => { try { using (MessageEnumerator enumerator = connection.Queue.GetMessageEnumerator2()) { while (enumerator.MoveNext(timeout)) { if (enumerator.Current == null) { if (_log.IsDebugEnabled) { _log.DebugFormat("Current message was null while enumerating endpoint"); } continue; } Message peekMessage = enumerator.Current; using (peekMessage) { IReceiveContext context = ReceiveContext.FromBodyStream(peekMessage.BodyStream, _address.IsTransactional); context.SetMessageId(peekMessage.Id); context.SetInputAddress(_address); byte[] extension = peekMessage.Extension; if (extension.Length > 0) { TransportMessageHeaders headers = TransportMessageHeaders.Create(extension); context.SetContentType(headers["Content-Type"]); context.SetOriginalMessageId(headers["Original-Message-Id"]); } Action <IReceiveContext> receive = receiver(context); if (receive == null) { continue; } ReceiveMessage(enumerator, timeout, message => { if (message == null) { throw new TransportException(Address.Uri, "Unable to remove message from queue: " + context.MessageId); } if (message.Id != context.MessageId) { throw new TransportException(Address.Uri, string.Format( "Received message does not match current message: ({0} != {1})", message.Id, context.MessageId)); } receive(context); }); } } } } catch (MessageQueueException ex) { HandleInboundMessageQueueException(ex); } }); }
public void Receive(Func <IReceiveContext, Action <IReceiveContext> > lookupSinkChain, TimeSpan timeout) { AddConsumerBinding(); _connectionHandler.Use(connection => { BasicGetResult result = null; try { result = _consumer.Get(); if (result == null) { Thread.Sleep(10); return; } using (var body = new MemoryStream(result.Body, false)) { ReceiveContext context = ReceiveContext.FromBodyStream(body); context.SetMessageId(result.BasicProperties.MessageId ?? result.DeliveryTag.ToString()); result.BasicProperties.MessageId = context.MessageId; context.SetInputAddress(_address); byte[] contentType = result.BasicProperties.IsHeadersPresent() ? (byte[])result.BasicProperties.Headers["Content-Type"] : null; if (contentType != null) { context.SetContentType(Encoding.UTF8.GetString(contentType)); } Action <IReceiveContext> receive = lookupSinkChain(context); if (receive == null) { Address.LogSkipped(result.BasicProperties.MessageId); _consumer.MessageSkipped(result); } else { receive(context); _consumer.MessageCompleted(result); } } } 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); } catch (Exception ex) { _log.Error("Failed to consume message from endpoint", ex); if (result != null) { _consumer.MessageFailed(result); } throw; } }); }