Example #1
0
        public void MessageExpirationWorks()
        {
            // arrange
            var timeToBeReceived = 2.Seconds().ToString();

            const string recipientInputQueueName = "test.expiration.recipient";
            const string senderInputQueueName    = "test.expiration.sender";

            using (var recipientQueue = new RabbitMqMessageQueue(ConnectionString, recipientInputQueueName))
                using (var senderQueue = new RabbitMqMessageQueue(ConnectionString, senderInputQueueName))
                {
                    senderQueue.Send(recipientInputQueueName,
                                     serializer.Serialize(new Message
                    {
                        Messages = new object[] { "HELLO WORLD!" },
                        Headers  =
                            new Dictionary <string, object>
                        {
                            {
                                Headers.TimeToBeReceived,
                                timeToBeReceived
                            }
                        },
                    }),
                                     new NoTransaction());

                    // act
                    Thread.Sleep(2.Seconds() + 1.Seconds());

                    // assert
                    var receivedTransportMessage = recipientQueue.ReceiveMessage(new NoTransaction());
                    Assert.That(receivedTransportMessage, Is.Null);
                }
        }
Example #2
0
        public void simple_object()
        {
            var obj = new Simple {
                Test = "test"
            };

            var serialized = _serializer.Serialize(obj);

            var deserialized = _serializer.Deserialize <Simple>(serialized);

            Assert.AreEqual(obj.Test, deserialized.Test);
        }
        public void can_deserialize_from_either_fully_or_partially_qualified_names()
        {
            //n.b. the previous version of the JsonMessageSerializer was fully qualified, and
            //this test demonstrates cross compability with that version
            var obj1 = new TestObject {
                Data1 = Guid.NewGuid().ToString("N")
            };
            var obj2 = new TestObject {
                Data1 = Guid.NewGuid().ToString("N")
            };
            var fullyQualifiedSerializer = new JsonMessageSerializer {
                FullyQualify = true
            };
            var partiallyQualifiedSerializer = new JsonMessageSerializer();

            //serialize with and without fully qualified names
            var eventData1 = fullyQualifiedSerializer.Serialize(obj1);
            var eventData2 = partiallyQualifiedSerializer.Serialize(obj2);
            //switch serializers
            var deserialized1 = partiallyQualifiedSerializer.Deserialize(eventData1);
            var deserialized2 = partiallyQualifiedSerializer.Deserialize(eventData2);

            Assert.IsType <TestObject>(deserialized1);
            Assert.IsType <TestObject>(deserialized2);

            var result1 = (TestObject)deserialized1;
            var result2 = (TestObject)deserialized2;

            Assert.True(string.CompareOrdinal(result1.Data1, obj1.Data1) == 0);
            Assert.True(string.CompareOrdinal(result2.Data1, obj2.Data1) == 0);
        }
Example #4
0
        public void FromScheduledEnvelope_generates_PendingScheduledCommand_correctly()
        {
            // Arrange
            var random         = new Random();
            var processManager = new FakeProcessManager();
            var messageId      = Guid.NewGuid();
            var correlationId  = Guid.NewGuid();
            var message        = new FakeCommand
            {
                Int32Value  = random.Next(),
                StringValue = Guid.NewGuid().ToString(),
            };
            var scheduledEnvelope =
                new ScheduledEnvelope(
                    new Envelope(messageId, message, correlationId: correlationId),
                    DateTime.Now.AddTicks(random.Next()));
            var serializer = new JsonMessageSerializer();

            // Act
            var actual = PendingScheduledCommand.FromScheduledEnvelope(processManager, scheduledEnvelope, serializer);

            // Assert
            actual.ProcessManagerType.Should().Be(typeof(FakeProcessManager).FullName);
            actual.ProcessManagerId.Should().Be(processManager.Id);
            actual.MessageId.Should().Be(messageId);
            actual.CorrelationId.Should().Be(correlationId);
            actual.CommandJson.Should().Be(serializer.Serialize(message));
            actual.ScheduledTimeUtc.Should().Be(scheduledEnvelope.ScheduledTimeUtc);
        }
Example #5
0
        void VerifyMessageHeaderIsPassed(Action <ISendContext <PingMessage> > setHeaderAction,
                                         Action <IConsumeContext> checkHeaderAction)
        {
            byte[] data;
            var    serializer = new JsonMessageSerializer();

            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);
            }
        }
        public void Deserialize_message_with_concrete_implementation_and_interface()
        {
            var map           = new[] { typeof(SuperMessageWithConcreteImpl), typeof(ISuperMessageWithConcreteImpl) };
            var messageMapper = new MessageMapper();

            messageMapper.Initialize(map);
            var serializer = new JsonMessageSerializer(messageMapper);

            using (var stream = new MemoryStream())
            {
                var msg = new SuperMessageWithConcreteImpl
                {
                    SomeProperty = "test"
                };

                serializer.Serialize(msg, stream);

                stream.Position = 0;

                var result = (ISuperMessageWithConcreteImpl)serializer.Deserialize(stream, map)[0];

                Assert.IsInstanceOf <SuperMessageWithConcreteImpl>(result);
                Assert.AreEqual("test", result.SomeProperty);
            }
        }
    public void TestInterfaces()
    {
        var output = new MemoryStream();

        var obj = messageMapper.CreateInstance <IA>(
            x =>
        {
            x.S    = "kalle";
            x.I    = 42;
            x.Data = new byte[23];
            x.B    = new B
            {
                BString = "BOO",
                C       = new C
                {
                    Cstr = "COO"
                }
            };
        }
            );

        new Random().NextBytes(obj.Data);

        messageMapper = new MessageMapper();
        messageMapper.Initialize(new[]
        {
            typeof(IA), typeof(IAImpl)
        });
        serializer = new JsonMessageSerializer(messageMapper, null, null, null, null);

        serializer.Serialize(obj, output);

        output.Position = 0;

        var filename = $"{GetType().Name}.{MethodBase.GetCurrentMethod().Name}.txt";

        File.WriteAllBytes(filename, output.ToArray());

        output.Position = 0;

        var result = serializer.Deserialize(output, new[]
        {
            typeof(IAImpl)
        });

        Assert.DoesNotThrow(() => output.Position = 0, "Stream should still be open");

        Assert.IsNotEmpty(result);
        Assert.That(result, Has.Length.EqualTo(1));

        Assert.That(result[0], Is.AssignableTo(typeof(IA)));
        var a = (IA)result[0];

        Assert.AreEqual(a.Data, obj.Data);
        Assert.AreEqual(42, a.I);
        Assert.AreEqual("kalle", a.S);
        Assert.IsNotNull(a.B);
        Assert.AreEqual("BOO", a.B.BString);
        Assert.AreEqual("COO", ((C)a.B.C).Cstr);
    }
    public void Run()
    {
        var map = new[]
        {
            typeof(SuperMessageWithConcreteImpl),
            typeof(ISuperMessageWithConcreteImpl)
        };
        var messageMapper = new MessageMapper();

        messageMapper.Initialize(map);
        var serializer = new JsonMessageSerializer(messageMapper, null, null, null, null);

        var message = new SuperMessageWithConcreteImpl
        {
            SomeProperty = "test"
        };

        using (var stream = new MemoryStream())
        {
            serializer.Serialize(message, stream);

            stream.Position = 0;

            var result = (ISuperMessageWithConcreteImpl)serializer.Deserialize(stream, map)[0];

            Assert.IsInstanceOf <SuperMessageWithConcreteImpl>(result);
            Assert.AreEqual("test", result.SomeProperty);
        }
    }
    public void Run()
    {
        var messageMapper = new MessageMapper();
        var messageTypes  = new[]
        {
            typeof(IMyEventA),
            typeof(IMyEventB)
        };

        messageMapper.Initialize(messageTypes);
        var serializer = new JsonMessageSerializer(messageMapper, null, null, null, null);

        var message = new CompositeMessage
        {
            IntValue    = 42,
            StringValue = "Answer"
        };

        using (var stream = new MemoryStream())
        {
            serializer.Serialize(message, stream);

            stream.Position = 0;

            var result = serializer.Deserialize(stream, messageTypes);
            var a      = (IMyEventA)result[0];
            var b      = (IMyEventB)result[1];
            Assert.AreEqual(42, b.IntValue);
            Assert.AreEqual("Answer", a.StringValue);
        }
    }
Example #10
0
    public void Deserialize()
    {
        var messageMapper = new MessageMapper();
        var messageTypes  = new[]
        {
            typeof(IWithoutConcrete)
        };

        messageMapper.Initialize(messageTypes);
        var serializer = new JsonMessageSerializer(messageMapper, null, null, null, null);

        var message = messageMapper.CreateInstance <IWithoutConcrete>();

        message.SomeProperty = "test";
        using (var stream = new MemoryStream())
        {
            serializer.Serialize(message, stream);

            stream.Position = 0;

            var result = (IWithoutConcrete)serializer.Deserialize(stream, messageTypes)[0];

            Assert.AreEqual("test", result.SomeProperty);
        }
    }
Example #11
0
    public void Should_not_emit_UTF8_BOM_if_configured_not_to()
    {
        var messageMapper = new MessageMapper();

        Func <Stream, JsonWriter> writerCreator = stream =>
        {
            var streamWriter = new StreamWriter(stream, new UTF8Encoding(false, false));
            return(new JsonTextWriter(streamWriter)
            {
                Formatting = Formatting.None
            });
        };

        var serializer = new JsonMessageSerializer(messageMapper, null, writerCreator, null, null);

        var message = new SimpleMessage();

        using (var stream = new MemoryStream())
        {
            serializer.Serialize(message, stream);

            stream.Position = 0;

            var result  = stream.ToArray();
            var utf8bom = new UTF8Encoding(true).GetPreamble();

            for (var i = 0; i < utf8bom.Length; i++)
            {
                Assert.AreNotEqual(utf8bom[i], result[i]);
            }
        }
    }
        public void can_write_qualified_name_header()
        {
            var serializer = new JsonMessageSerializer();

            var eventData        = serializer.Serialize(testObject);
            var clrQualifiedName = (string)JObject.Parse(Encoding.UTF8.GetString(eventData.Metadata))
                                   .Property(serializer.EventClrQualifiedTypeHeader).Value;
            var partialName = $"{testObject.GetType().FullName},{testObject.GetType().Assembly.GetName()}";

            Assert.True(string.CompareOrdinal(clrQualifiedName, partialName) == 0);

            serializer.FullyQualify = true;
            eventData        = serializer.Serialize(testObject);
            clrQualifiedName = (string)JObject.Parse(Encoding.UTF8.GetString(eventData.Metadata))
                               .Property(serializer.EventClrQualifiedTypeHeader).Value;
            Assert.True(string.CompareOrdinal(clrQualifiedName, testObject.GetType().AssemblyQualifiedName) == 0);
        }
Example #13
0
        public void can_round_trip()
        {
            var employee1 = new Employee()
            {
                Name = "Austin"
            };

            var stream = new MemoryStream();

            _serializer.Serialize(employee1, stream);

            stream.Position = 0;

            var employee2 = _serializer.Deserialize(stream).ShouldBeOfType <Employee>();

            employee1.ShouldBe(employee2);
        }
        public void TestMethod()
        {
            int msgCount = 5000;
            IMessageSerializer json = new JsonMessageSerializer();
            IMessageSerializer bson = new BsonMessageSerializer();
            long elapsed1;
            long elapsed2;

            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < msgCount; i++)
            {
                IMessage msg = new MessageSerDes() { Content = "Hello world people" };
                using (MemoryStream ms = new MemoryStream())
                {
                    json.Serialize(msg, ms);

                    if (ms.CanSeek)
                        ms.Seek(0, SeekOrigin.Begin);

                    var des = json.Deserialize(ms);
                    if ((des as MessageSerDes).Content != (msg as MessageSerDes).Content ||
                        (des as MessageSerDes).Id != (msg as MessageSerDes).Id ||
                        (des as MessageSerDes).Age != (msg as MessageSerDes).Age)
                        Assert.Fail();
                }
                msg = null;
            }

            sw.Stop();
            elapsed1 = sw.ElapsedMilliseconds;
            sw.Reset();

            sw.Start();
            for (int i = 0; i < msgCount; i++)
            {
                IMessage msg = new MessageSerDes() { Content = "Hello world people" };
                using (MemoryStream ms = new MemoryStream())
                {
                    bson.Serialize(msg, ms);

                    if (ms.CanSeek)
                        ms.Seek(0, SeekOrigin.Begin);

                    var des = bson.Deserialize(ms);
                    if ((des as MessageSerDes).Content != (msg as MessageSerDes).Content ||
                        (des as MessageSerDes).Id != (msg as MessageSerDes).Id ||
                        (des as MessageSerDes).Age != (msg as MessageSerDes).Age)
                        Assert.Fail();
                }
                msg = null;
            }
            sw.Stop();
            elapsed2 = sw.ElapsedMilliseconds;

            Assert.AreNotEqual(elapsed1, elapsed2);
        }
        public void can_write_typename_header()
        {
            var serializer = new JsonMessageSerializer();

            var eventData = serializer.Serialize(testObject);
            var typeName  = (string)JObject.Parse(Encoding.UTF8.GetString(eventData.Metadata))
                            .Property(serializer.EventClrTypeHeader).Value;

            Assert.True(string.CompareOrdinal(typeName, testObject.GetType().Name) == 0);
        }
        public void can_serialize_objects()
        {
            var serializer   = new JsonMessageSerializer();
            var eventData    = serializer.Serialize(testObject);
            var deserialized = serializer.Deserialize(eventData);

            Assert.IsType <TestObject>(deserialized);
            var testObject2 = (TestObject)deserialized;

            Assert.True(testObject.Equals(testObject2));

            serializer.FullyQualify = true;
            eventData    = serializer.Serialize(testObject);
            deserialized = serializer.Deserialize(eventData);
            Assert.IsType <TestObject>(deserialized);
            var testObject3 = (TestObject)deserialized;

            Assert.True(testObject.Equals(testObject3));
        }
Example #17
0
        public void Serialize <T>(Stream stream, SendContext <T> context) where T : class
        {
            var messageContainer = context.Message as MessageContainer;

            if (messageContainer != null)
            {
                _changeMessageTypeSerializer.Serialize(stream, context);
            }
            _jsonSerializer.Serialize(stream, context);
        }
        public void Serialize_ByteArray_ReturnedUnmodified()
        {
            var messageBytes = Encoding.UTF8.GetBytes("test");

            var serializer = new JsonMessageSerializer();

            var serialized = serializer.Serialize(messageBytes, new MessageHeaderCollection());

            serialized.Should().BeSameAs(messageBytes);
        }
        public void When_Using_Property_WithXContainerAssignable_should_preserve_xml()
        {
            const string XmlElement  = "<SomeClass xmlns=\"http://nservicebus.com\"><SomeProperty value=\"Bar\" /></SomeClass>";
            const string XmlDocument = "<?xml version=\"1.0\" encoding=\"utf-8\" ?>" + XmlElement;

            var messageWithXDocument = new MessageWithXDocument {
                Document = XDocument.Load(new StringReader(XmlDocument))
            };
            var messageWithXElement = new MessageWithXElement {
                Document = XElement.Load(new StringReader(XmlElement))
            };

            var messageMapper = new MessageMapper();
            var serializer    = new JsonMessageSerializer(messageMapper);

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(messageWithXDocument, stream);

                stream.Position = 0;
                var json = new StreamReader(stream).ReadToEnd();
                stream.Position = 0;

                var result = serializer.Deserialize(stream, new[] { typeof(MessageWithXDocument) }).Cast <MessageWithXDocument>().Single();

                Assert.AreEqual(messageWithXDocument.Document.ToString(), result.Document.ToString());
                Assert.AreEqual(XmlElement, json.Substring(13, json.Length - 15).Replace("\\", string.Empty));
            }

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(messageWithXElement, stream);

                stream.Position = 0;
                var json = new StreamReader(stream).ReadToEnd();
                stream.Position = 0;

                var result = serializer.Deserialize(stream, new[] { typeof(MessageWithXElement) }).Cast <MessageWithXElement>().Single();

                Assert.AreEqual(messageWithXElement.Document.ToString(), result.Document.ToString());
                Assert.AreEqual(XmlElement, json.Substring(13, json.Length - 15).Replace("\\", string.Empty));
            }
        }
Example #20
0
        private async Task ProcessMessageAsync(RestoreMessage restoreMessage)
        {
            var currentDate = restoreMessage.FromDate.ToUniversalTime();
            var to          = restoreMessage.ToDate.ToUniversalTime();
            var bindings    = await _rabbitService.GetAllBindingsAsync();

            var exchangeBindings =
                bindings[restoreMessage.ExchangeName]
                .Where(x => x.DestinationType == "queue")
                .ToList();

            while (currentDate.Date <= to.Date)
            {
                string continuationToken = null;

                do
                {
                    var result =
                        await _rabbitService.RestoreMessageAsync(restoreMessage.ExchangeName, currentDate, 100,
                                                                 continuationToken);

                    var factory = new ConnectionFactory()
                    {
                        Uri = _connectionString,
                    };
                    foreach (var binding in exchangeBindings)
                    {
                        using (var connection = factory.CreateConnection())
                            using (var channel = connection.CreateModel())
                            {
                                foreach (var message in result.Messages)
                                {
                                    //channel.QueueDeclare(queue: "hello",
                                    //    durable: false,
                                    //    exclusive: false,
                                    //    autoDelete: false,
                                    //    arguments: null);

                                    var body = _messageSerializer.Serialize(message.Payload);

                                    channel.BasicPublish(exchange: "",
                                                         routingKey: binding.Destination,
                                                         basicProperties: null,
                                                         body: body);
                                }
                            }

                        continuationToken = result.ContinuationToken;
                    }

                    currentDate = currentDate.AddDays(1.0);
                } while (!string.IsNullOrEmpty(continuationToken));
            }
        }
    public void Serialize_ShouldSerialize(
        [Frozen] Mock <ISerializer> serializer,
        JsonMessageSerializer sut,
        object data, string serialized)
    {
        serializer.Setup(x => x.Serialize(data))
        .Returns(serialized);

        var result = sut.Serialize(data);

        Assert.Equal(serialized, result);
    }
Example #22
0
        public void Low_Level_Transport_Test()
        {
            var clientManager = new PooledRedisClientManager();

            var messageMapper = new MessageMapper();

            messageMapper.Initialize(new[] { typeof(TestMessage), typeof(TestEvent) });

            var sendAddress = Address.Parse("lowlevel@localhost");

            var queue = new RedisQueue(new JsonSerializer(), clientManager, new QueueKeyNameProvider(true));

            queue.Init(sendAddress, true);

            var nsbSerializer = new JsonMessageSerializer(messageMapper);

            var message = new TestMessage()
            {
                Name = "Bob"
            };

            var transportMessage = new TransportMessage()
            {
                MessageIntent = MessageIntentEnum.Send
            };

            using (var ms = new MemoryStream())
            {
                nsbSerializer.Serialize(new [] { message }, ms);
                transportMessage.Body = ms.ToArray();
            }

            using (var tran = new TransactionScope())
            {
                for (int x = 0; x < 2; x++)
                {
                    queue.Send(transportMessage, sendAddress);
                }
                tran.Complete();
            }

            for (int x = 0; x < 2; x++)
            {
                if (queue.HasMessage())
                {
                    using (var tran = new TransactionScope())
                    {
                        queue.Receive();
                        tran.Complete();
                    }
                }
            }
        }
Example #23
0
 public static string Serialize(object sagaEntity)
 {
     using (var memoryStream = new MemoryStream())
     {
         serializer.Serialize(new[] { sagaEntity }, memoryStream);
         memoryStream.Position = 0;
         using (var streamReader = new StreamReader(memoryStream))
         {
             return(streamReader.ReadToEnd());
         }
     }
 }
Example #24
0
        public void MessageExpirationWorks()
        {
            // arrange
            var timeToBeReceived = 2.Seconds()
                                   .ToString();

            senderQueue.Send(destinationQueueName,
                             serializer.Serialize(new Message
            {
                Messages = new object[] { "HELLO WORLD!" },
                Headers  = new Dictionary <string, string> {
                    { Headers.TimeToBeReceived, timeToBeReceived }
                },
            }));

            // act
            Thread.Sleep(2.Seconds() + 1.Seconds());

            // assert
            Assert.Throws <MessageQueueException>(() => destinationQueue.Receive(0.1.Seconds()));
        }
        public void JsonMessageSerializer_SerializesEventProperly()
        {
            var sut         = new JsonMessageSerializer();
            var value       = Guid.NewGuid().ToString();
            var aggregateId = Guid.NewGuid();
            var @event      = new FakeEvent(aggregateId, 1, value);

            var bytes = sut.Serialize(@event);

            Assert.NotNull(bytes);
            Assert.NotEmpty(bytes);
        }
        public void can_use_json_message_serializer()
        {
            var evt  = new TestEvent(CorrelatedMessage.NewRoot());
            var evt2 = new TestEvent(evt);

            var serializer = new JsonMessageSerializer();

            var data  = serializer.Serialize(evt);
            var data2 = serializer.Serialize(evt2);

            var dEvent  = (TestEvent)serializer.Deserialize(data);
            var dEvent2 = (TestEvent)serializer.Deserialize(data2);

            Assert.Equal(evt.MsgId, dEvent.MsgId);
            Assert.Equal(evt.SourceId, dEvent.SourceId);
            Assert.Equal(evt.CorrelationId, dEvent.CorrelationId);

            Assert.Equal(evt2.MsgId, dEvent2.MsgId);
            Assert.Equal(evt2.SourceId, dEvent2.SourceId);
            Assert.Equal(evt2.CorrelationId, dEvent2.CorrelationId);
        }
        public void ShouldDeserializeFromJson()
        {
            IMessageSerializer serializer = new JsonMessageSerializer();
            IMessageDeserializer <TestMessageProto> deserializer = new JsonMessageDeserializer <TestMessageProto>();

            var message = new TestMessageProto {
                Id = 123, Name = "SomeName"
            };
            var serialize   = serializer.Serialize(message);
            var deserialize = deserializer.Deserialize(serialize);

            Assert.AreEqual(message, deserialize);
        }
Example #28
0
        public void WorksWithCustomEncodingAsWell(string encodingWebName)
        {
            // arrange
            var encoding = Encoding.GetEncoding(encodingWebName);

            serializer.SpecifyEncoding(encoding);

            // act
            var transportMessageToSend = serializer.Serialize(new Message {
                Messages = new object[] { "hej!" }
            });

            // assert
            transportMessageToSend.Headers.ShouldContainKeyAndValue(Headers.Encoding, encoding.WebName);
            transportMessageToSend.Headers.ShouldContainKeyAndValue(Headers.ContentType, "text/json");

            encoding.GetString(transportMessageToSend.Body)
            .Replace("\r", "")
            .Replace("\n", "")
            .Replace(" ", "")
            .ShouldBe(@"{""$type"":""System.Object[],mscorlib"",""$values"":[""hej!""]}");
        }
            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());
            }
        public void ShouldSerializeToJson()
        {
            IMessageSerializer serializer = new JsonMessageSerializer();

            var message = new TestMessageProto {
                Id = 123, Name = "SomeName"
            };
            var serialize = JsonMessageDefaults.Encoding.GetString(serializer.Serialize(message));

            Assert.NotNull(serialize);
            StringAssert.Contains(message.Id.ToString(), serialize);
            StringAssert.Contains(message.Name, serialize);
        }
		public void An_interface_message_is_bound()
		{
			_serializer = new JsonMessageSerializer();

			var message = new A {TextA = "ValueA"};

			using(var buffer = new MemoryStream())
			{
				_serializer.Serialize<A>(buffer, message.ToSendContext());

				_message = Encoding.UTF8.GetString(buffer.ToArray());

			//	Trace.WriteLine(_message);
			}
		}
        public void Test()
        {
            var expectedDate = new DateTime(2010, 10, 13, 12, 32, 42, DateTimeKind.Unspecified);
            var expectedDateLocal = new DateTime(2010, 10, 13, 12, 32, 42, DateTimeKind.Local);
            var expectedDateUtc = new DateTime(2010, 10, 13, 12, 32, 42, DateTimeKind.Utc);
            var expectedGuid = Guid.NewGuid();

            var obj = new A
                        {
                            AGuid = expectedGuid,
                            Data = new byte[32],
                            I = 23,
                            S = "Foo",
                            Ints = new List<int> { 12, 42 },
                            Bs = new List<B> { new B { BString = "aaa", C = new C { Cstr = "ccc" } }, new BB { BString = "bbbb", C = new C { Cstr = "dddd" }, BBString = "BBStr"} },
                            DateTime = expectedDate,
                            DateTimeLocal = expectedDateLocal,
                            DateTimeUtc = expectedDateUtc
                        };

            new Random().NextBytes(obj.Data);

            var output = new MemoryStream();

            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(IA), typeof(A) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            Serializer.Serialize(obj, output);

            output.Position = 0;

            var result = Serializer.Deserialize(output, new[] { typeof(A) });

            Assert.DoesNotThrow(() => output.Position = 0, "Stream should still be open");

            Assert.That(result[0], Is.TypeOf(typeof(A)));
            var a = ((A)result[0]);

            Assert.AreEqual(obj.Data, a.Data);
            Assert.AreEqual(23, a.I);
            Assert.AreEqual("Foo", a.S);
            Assert.AreEqual(expectedDate.Kind, a.DateTime.Kind);
            Assert.AreEqual(expectedDate, a.DateTime);
            Assert.AreEqual(expectedDateLocal.Kind, a.DateTimeLocal.Kind);
            Assert.AreEqual(expectedDateLocal, a.DateTimeLocal);
            Assert.AreEqual(expectedDateUtc.Kind, a.DateTimeUtc.Kind);
            Assert.AreEqual(expectedDateUtc, a.DateTimeUtc);
            Assert.AreEqual("ccc", ((C)a.Bs[0].C).Cstr);
            Assert.AreEqual(expectedGuid, a.AGuid);

            Assert.IsInstanceOf<B>(a.Bs[0]);
            Assert.IsInstanceOf<BB>(a.Bs[1]);
        }
        public void Deserialize_message_without_concrete_implementation()
        {
            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(ISuperMessageWithoutConcreteImpl) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            using (var stream = new MemoryStream())
            {
                var msg = MessageMapper.CreateInstance<ISuperMessageWithoutConcreteImpl>();
                msg.SomeProperty = "test";

                Serializer.Serialize(msg, stream);

                stream.Position = 0;

                var result = (ISuperMessageWithoutConcreteImpl)Serializer.Deserialize(stream, new[] { typeof(ISuperMessageWithoutConcreteImpl) })[0];

                Assert.AreEqual("test", result.SomeProperty);
            }
        }
        public void Deserialize_message_with_concrete_implementation_and_interface()
        {
            var map = new[] {typeof(SuperMessageWithConcreteImpl), typeof(ISuperMessageWithConcreteImpl)};
            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(map);
            Serializer = new JsonMessageSerializer(MessageMapper);

            using (var stream = new MemoryStream())
            {
                var msg = new SuperMessageWithConcreteImpl
                {
                    SomeProperty = "test"
                };

                Serializer.Serialize(msg, stream);

                stream.Position = 0;

                var result = (ISuperMessageWithConcreteImpl)Serializer.Deserialize(stream, map)[0];

                Assert.IsInstanceOf<SuperMessageWithConcreteImpl>(result);
                Assert.AreEqual("test", result.SomeProperty);
            }
        }
        public void TestInterfaces()
        {
            var output = new MemoryStream();

            var obj = MessageMapper.CreateInstance<IA>(
              x =>
              {
                  x.S = "kalle";
                  x.I = 42;
                  x.Data = new byte[23];
                  x.B = new B { BString = "BOO", C = new C { Cstr = "COO" } };
              }
              );

            new Random().NextBytes(obj.Data);

            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(IA), typeof(IAImpl) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            Serializer.Serialize(obj, output);

            output.Position = 0;

            var filename = string.Format("{0}.{1}.txt", GetType().Name, MethodBase.GetCurrentMethod().Name);

            File.WriteAllBytes(filename, output.ToArray());

            output.Position = 0;

            var result = Serializer.Deserialize(output, new[] { typeof(IAImpl) });

            Assert.DoesNotThrow(() => output.Position = 0, "Stream should still be open");

            Assert.IsNotEmpty(result);
            Assert.That(result, Has.Length.EqualTo(1));

            Assert.That(result[0], Is.AssignableTo(typeof(IA)));
            var a = ((IA)result[0]);

            Assert.AreEqual(a.Data, obj.Data);
            Assert.AreEqual(42, a.I);
            Assert.AreEqual("kalle", a.S);
            Assert.IsNotNull(a.B);
            Assert.AreEqual("BOO", a.B.BString);
            Assert.AreEqual("COO", ((C)a.B.C).Cstr);
        }
        public void Serialize_message_without_concrete_implementation()
        {
            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(ISuperMessageWithoutConcreteImpl) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            using (var stream = new MemoryStream())
            {
                Serializer.Serialize(MessageMapper.CreateInstance<ISuperMessageWithoutConcreteImpl>(), stream);

                stream.Position = 0;
                var result = new StreamReader(stream).ReadToEnd();

                Assert.That(!result.Contains("$type"), result);
                Assert.That(result.Contains("SomeProperty"), result);
            }
        }
        public void Deserialize_private_message_with_two_unrelated_interface_without_wrapping()
        {
            MessageMapper = new MessageMapper();
            MessageMapper.Initialize(new[] { typeof(IMyEventA), typeof(IMyEventB) });
            Serializer = new JsonMessageSerializer(MessageMapper);

            using (var stream = new MemoryStream())
            {
                var msg = new CompositeMessage
                {
                    IntValue = 42,
                    StringValue = "Answer"
                };

                Serializer.Serialize(msg, stream);

                stream.Position = 0;

                var result = Serializer.Deserialize(stream, new[] { typeof(IMyEventA), typeof(IMyEventB) });
                var a = (IMyEventA) result[0];
                var b = (IMyEventB) result[1];
                Assert.AreEqual(42, b.IntValue);
                Assert.AreEqual("Answer", a.StringValue);
            }
        }