public void CorrectlyHandlesDeserializationWhenAlternativeEncodingIsUsed(string encodingWebName)
        {
            // arrange
            var encoding = Encoding.GetEncoding(encodingWebName);
            var bytes    = encoding.GetBytes(SerializedMessage);

            Console.WriteLine(@"This is how it looks as ASCII:

{0}", Encoding.ASCII.GetString(bytes));

            var receivedTransportMessage =
                new ReceivedTransportMessage
            {
                Headers = new Dictionary <string, object>
                {
                    { Headers.ContentType, "text/json" },
                    { Headers.Encoding, encodingWebName },
                },
                Body = bytes,
            };

            // act
            var deserializedMessage = serializer.Deserialize(receivedTransportMessage);

            // assert
            deserializedMessage.Messages.Length.ShouldBe(1);
            var message = deserializedMessage.Messages.Single();

            message.ShouldBeOfType <SomeComplexObjectThatRequïresÜnicódeToWørk>();
            ((SomeComplexObjectThatRequïresÜnicódeToWørk)message).ThisIsÜnicøde.ShouldBe("thiß ís jüst tæxt");
        }
        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);
        }
Exemple #3
0
        public void MessageIsSentWhenAmbientTransactionIsCommitted()
        {
            using (var tx = new TransactionScope())
            {
                var ctx = new AmbientTransactionContext();
                senderQueue.Send(DestinationQueueName,
                                 serializer.Serialize(new Message
                {
                    Messages = new object[]
                    {
                        "W00t!"
                    },
                }),
                                 ctx);

                tx.Complete();
            }

            var msmqMessage = Receive();

            Assert.IsNotNull(msmqMessage, "No message was received within timeout!");
            var transportMessage = (ReceivedTransportMessage)msmqMessage.Body;
            var message          = serializer.Deserialize(transportMessage);

            message.Messages[0].ShouldBe("W00t!");
        }
Exemple #4
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_to_a_specified_type()
        {
            var serializer = new JsonMessageSerializer();
            var eventData  = serializer.Serialize(testObject);
            //n.b. testObject is type TestObject
            var deserialized = serializer.Deserialize(eventData, typeof(TestObject2));

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

            Assert.True(string.CompareOrdinal(testObject.Data2, testObject2.Data2) == 0);

            var newTestObject2 = serializer.Deserialize <TestObject2>(eventData);

            Assert.True(string.CompareOrdinal(testObject.Data2, newTestObject2.Data2) == 0);
        }
    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 WorksWhenMovingToErrorQueue()
        {
            using (var messageQueue = new MsmqMessageQueue("error"))
            {
                // make sure error queue is empty
                messageQueue.PurgeInputQueue();

                adapter.Handle <Request>(req =>
                {
                    throw new ApplicationException("oh crap");
                });

                var request = new Request();
                bus.AttachHeader(request, Headers.CorrelationId, "super-unique!!!!111");
                bus.SendLocal(request);

                // let it fail
                Thread.Sleep(2.Seconds());

                var receivedTransportMessage = messageQueue.ReceiveMessage(new NoTransaction());
                receivedTransportMessage.ShouldNotBe(null);

                var serializer = new JsonMessageSerializer();
                var message    = serializer.Deserialize(receivedTransportMessage);

                message.Headers.ShouldContainKeyAndValue(Headers.CorrelationId, "super-unique!!!!111");
            }
        }
Exemple #9
0
    public void Should_throw_for_array()
    {
        var xml = @"[{
$type: ""IA, NServiceBus.Core.Tests"",
Data: ""rhNAGU4dr/Qjz6ocAsOs3wk3ZmxHMOg="",
S: ""kalle"",
I: 42,
B: {
}
}, {
$type: ""IA, NServiceBus.Core.Tests"",
Data: ""AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="",
S: ""kalle"",
I: 42,
B: {
}
}]";

        using (var stream = new MemoryStream())
        {
            var streamWriter = new StreamWriter(stream);
            streamWriter.Write(xml);
            streamWriter.Flush();
            stream.Position = 0;

            var messageMapper = new MessageMapper();
            var serializer    = new JsonMessageSerializer(messageMapper, null, null, null, null);
            var exception     = Assert.Throws <Exception>(() => serializer.Deserialize(stream, new List <Type>()));
            Approvals.Verify(exception.Message);
        }
    }
        public void ItHasBeenFixed()
        {
            using (var adapter = new BuiltinContainerAdapter())
            {
                adapter.Handle <string>(s =>
                {
                    throw new ApplicationException("Will trigger that the message gets moved to the error queue");
                });

                Configure.With(adapter)
                .Transport(t => t.UseRabbitMq(ConnectionString, "test.input", "test.error")
                           .UseExchange("AlternativeExchange"))
                .CreateBus()
                .Start();

                adapter.Bus.SendLocal("hello there!!!");

                // wait until we're sure
                Thread.Sleep(2.Seconds());

                using (var errorQueue = new RabbitMqMessageQueue(ConnectionString, "test.error"))
                {
                    var serializer = new JsonMessageSerializer();
                    var receivedTransportMessage = errorQueue.ReceiveMessage(new NoTransaction());
                    receivedTransportMessage.ShouldNotBe(null);

                    var errorMessage = serializer.Deserialize(receivedTransportMessage);
                    errorMessage.Messages.Length.ShouldBe(1);
                    errorMessage.Messages[0].ShouldBeOfType <string>();
                    ((string)errorMessage.Messages[0]).ShouldBe("hello there!!!");
                }
            }
        }
Exemple #11
0
    public void Should_throw_for_multiple_passed_type()
    {
        var text = @"
[{
    SomeProperty: 'Value1'
},
{
    SomeProperty: 'Value2'
}]";

        using (var stream = new MemoryStream())
        {
            WriteToStream(stream, text);

            var messageMapper = new MessageMapper();
            var serializer    = new JsonMessageSerializer(messageMapper, null, null, null, null);
            var messageTypes  = new List <Type>
            {
                typeof(ArrayMessage)
            };
            var exception = Assert.Throws <Exception>(() =>
            {
                serializer.Deserialize(stream, messageTypes);
            });
            Approver.Verify(exception.Message);
        }
    }
        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);
            }
        }
Exemple #13
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_private_message_with_two_unrelated_interface_without_wrapping()
        {
            var messageMapper = new MessageMapper();

            messageMapper.Initialize(new[] { typeof(IMyEventA), typeof(IMyEventB) });
            var 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);
            }
        }
        public void Deserialize_messages_wrapped_in_array_from_older_endpoint()
        {
            var messageMapper            = new MessageMapper();
            var serializer               = new JsonMessageSerializer(messageMapper);
            var jsonWithMultipleMessages = @"
[
  {
    $type: 'NServiceBus.Serializers.Json.Tests.JsonMessageSerializerTest+SimpleMessage1, NServiceBus.Core.Tests',
    PropertyOnMessage1: 'Message1'
  },
  {
    $type: 'NServiceBus.Serializers.Json.Tests.JsonMessageSerializerTest+SimpleMessage2, NServiceBus.Core.Tests',
    PropertyOnMessage2: 'Message2'
  }
]";

            using (var stream = new MemoryStream())
            {
                var streamWriter = new StreamWriter(stream);
                streamWriter.Write(jsonWithMultipleMessages);
                streamWriter.Flush();
                stream.Position = 0;
                var result = serializer.Deserialize(stream, new[]
                {
                    typeof(SimpleMessage2),
                    typeof(SimpleMessage1)
                });

                Assert.AreEqual(2, result.Length);
                Assert.AreEqual("Message1", ((SimpleMessage1)result[0]).PropertyOnMessage1);
                Assert.AreEqual("Message2", ((SimpleMessage2)result[1]).PropertyOnMessage2);
            }
        }
Exemple #16
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);
        }
    }
    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);
        }
    }
        public async Task Send_works_for_already_passed_scheduled_time()
        {
            // Arrange
            await ReceiveAndForgetAll();

            IMessageSerializer serializer = new JsonMessageSerializer();
            var sut = new ServiceBusMessageBus(_connectionStringBuilder, serializer);

            var scheduled = new ScheduledEnvelope(
                new Envelope(new Fixture().Create <SomeMessage>()),
                DateTime.UtcNow.AddTicks(-TimeSpan.FromDays(1).Ticks));

            // Act
            await sut.Send(scheduled, CancellationToken.None);

            // Assert
            (Message received, DateTime receivedAt) = await ReceiveSingle();

            var precision = TimeSpan.FromMilliseconds(1000);

            receivedAt.Should().BeOnOrAfter(scheduled.ScheduledTimeUtc.AddTicks(-precision.Ticks));

            object message = serializer.Deserialize(Encoding.UTF8.GetString(received.Body));

            message.Should().BeEquivalentTo(scheduled.Envelope.Message);
        }
        public async Task Save_inserts_Memento_entity_correctly()
        {
            // Arrange
            var sourceId = Guid.NewGuid();
            var memento  = new FakeUserMemento();

            var serializer = new JsonMessageSerializer();

            var sut = new SqlMementoStore(
                () => new MementoStoreDbContext(_dbContextOptions),
                serializer);

            // Act
            await sut.Save <FakeUser>(sourceId, memento, default);

            // Assert
            using (var db = new MementoStoreDbContext(_dbContextOptions))
            {
                Memento actual = await db
                                 .Mementoes
                                 .AsNoTracking()
                                 .Where(m => m.AggregateId == sourceId)
                                 .SingleOrDefaultAsync();

                actual.Should().NotBeNull();
                object restored = serializer.Deserialize(actual.MementoJson);
                restored.Should().BeOfType <FakeUserMemento>();
                restored.ShouldBeEquivalentTo(memento);
            }
        }
Exemple #20
0
        /// <summary>
        /// Deserializes the specified message.
        /// </summary>
        /// <param name="messageType">The type of message.</param>
        /// <param name="revision">The revision of the message.</param>
        /// <param name="message">The message to deserialize.</param>
        /// <returns>A deserialized <see cref="IEvent">event</see>.</returns>
        protected virtual IEvent Deserialize(string messageType, int revision, JObject message)
        {
            Arg.NotNullOrEmpty(messageType, nameof(messageType));
            Arg.NotNull(message, nameof(message));
            Contract.Ensures(Contract.Result <IEvent>() != null);

            return(eventSerializer.Deserialize(messageType, revision, message));
        }
Exemple #21
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_throw_if_type_not_found()
        {
            var serializer = new JsonMessageSerializer();

            //n.b. setting header to non existent assembly
            var headerName = serializer.EventClrQualifiedTypeHeader;
            var headerData = $"{typeof(TestObject2).FullName},dne-assembly";
            var headers    = new Dictionary <string, object> {
                { headerName, headerData }
            };
            var eventData = serializer.Serialize(testObject, headers);
            //confirm type not found
            var deserialized = serializer.Deserialize(eventData);

            Assert.IsType <JObject>(deserialized);
            //request throw on type not found
            serializer.ThrowOnTypeNotFound = true;
            Assert.Throws <InvalidOperationException>(() => serializer.Deserialize(eventData));
        }
        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));
        }
        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));
            }
        }
        public async Task SaveEvents_saves_pending_events_correctly()
        {
            // Arrange
            var userId = Guid.NewGuid();

            var created         = new FakeUserCreated();
            var usernameChanged = new FakeUsernameChanged();
            var events          = new DomainEvent[] { created, usernameChanged };

            events.Raise(userId);

            var serializer = new JsonMessageSerializer();

            var sut = new SqlEventStore(
                () => new FakeEventStoreDbContext(_dbContextOptions),
                serializer);

            string operationId   = Guid.NewGuid().ToString();
            var    correlationId = Guid.NewGuid();
            string contributor   = Guid.NewGuid().ToString();

            // Act
            await sut.SaveEvents <FakeUser>(events, operationId, correlationId, contributor);

            // Asseert
            using (var db = new FakeEventStoreDbContext(_dbContextOptions))
            {
                var pendingEvents = db
                                    .PendingEvents
                                    .Where(e => e.AggregateId == userId)
                                    .OrderBy(e => e.Version)
                                    .ToList();

                foreach (var t in pendingEvents.Zip(events, (pending, source) =>
                                                    new { Pending = pending, Source = source }))
                {
                    var actual = new
                    {
                        t.Pending.Version,
                        t.Pending.CorrelationId,
                        t.Pending.Contributor,
                        Message = serializer.Deserialize(t.Pending.EventJson),
                    };
                    actual.ShouldBeEquivalentTo(new
                    {
                        t.Source.Version,
                        OperationId   = operationId,
                        CorrelationId = correlationId,
                        Contributor   = contributor,
                        Message       = t.Source,
                    },
                                                opts => opts.RespectingRuntimeTypes());
                }
            }
        }
        public void TestMany()
        {
            var messageMapper = new MessageMapper();

            messageMapper.Initialize(new[] { typeof(IAImpl), typeof(IA) });
            var serializer = new JsonMessageSerializer(messageMapper);
            var xml        = @"[{
    $type: ""NServiceBus.Serializers.Json.Tests.IA, NServiceBus.Core.Tests"",
    Data: ""rhNAGU4dr/Qjz6ocAsOs3wk3ZmxHMOg="",
    S: ""kalle"",
    I: 42,
    B: {
        BString: ""BOO"",
        C: {
            $type: ""NServiceBus.Serializers.Json.Tests.C, NServiceBus.Core.Tests"",
            Cstr: ""COO""
        }
    }
}, {
    $type: ""NServiceBus.Serializers.Json.Tests.IA, NServiceBus.Core.Tests"",
    Data: ""AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="",
    S: ""kalle"",
    I: 42,
    B: {
        BString: ""BOO"",
        C: {
            $type: ""NServiceBus.Serializers.Json.Tests.C, NServiceBus.Core.Tests"",
            Cstr: ""COO""
        }
    }
}]";

            using (var stream = new MemoryStream())
            {
                var streamWriter = new StreamWriter(stream);
                streamWriter.Write(xml);
                streamWriter.Flush();
                stream.Position = 0;


                var result = serializer.Deserialize(stream, new[] { typeof(IAImpl) });
                Assert.IsNotEmpty(result);
                Assert.That(result, Has.Length.EqualTo(2));

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

                Assert.AreEqual(23, a.Data.Length);
                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 Deserialize_ShouldThrowWhenNotSuccessful(
        [Frozen] Mock <ISerializer> serializer,
        JsonMessageSerializer sut,
        string data, Type type)
    {
        serializer.Setup(x => x.Deserialize(data, type))
        .Returns(null);

        Assert.Throws <InvalidOperationException>(
            () => sut.Deserialize(data, type));
    }
Exemple #29
0
        public void Deserialize_NotATextMessage_ThrowsInvalidCastException()
        {
            // arrange
            var message = new BytesMessage();

            // act
            var serializer = new JsonMessageSerializer <TestBody>();

            // assert
            Assert.Throws <InvalidCastException>(() => serializer.Deserialize(message));
        }
        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 Deserialize_ShouldDeserialize(
        [Frozen] Mock <ISerializer> serializer,
        JsonMessageSerializer sut,
        string data, Type type, object deserialized)
    {
        serializer.Setup(x => x.Deserialize(data, type))
        .Returns(deserialized);

        var result = sut.Deserialize(data, type);

        Assert.Equal(deserialized, result);
    }
        public void TestMany()
        {
            var xml = @"[{
    $type: ""NServiceBus.Serializers.Json.Tests.IA, NServiceBus.Core.Tests"",
    Data: ""rhNAGU4dr/Qjz6ocAsOs3wk3ZmxHMOg="",
    S: ""kalle"",
    I: 42,
    B: {
        BString: ""BOO"",
        C: {
            $type: ""NServiceBus.Serializers.Json.Tests.C, NServiceBus.Core.Tests"",
            Cstr: ""COO""
        }
    }
}, {
    $type: ""NServiceBus.Serializers.Json.Tests.IA, NServiceBus.Core.Tests"",
    Data: ""AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA="",
    S: ""kalle"",
    I: 42,
    B: {
        BString: ""BOO"",
        C: {
            $type: ""NServiceBus.Serializers.Json.Tests.C, NServiceBus.Core.Tests"",
            Cstr: ""COO""
        }
    }
}]";
            using (var stream = new MemoryStream())
            {
                var streamWriter = new StreamWriter(stream);
                streamWriter.Write(xml);
                streamWriter.Flush();
                stream.Position = 0;

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

                var result = Serializer.Deserialize(stream, new[] { typeof(IAImpl) });
                Assert.IsNotEmpty(result);
                Assert.That(result, Has.Length.EqualTo(2));

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

                Assert.AreEqual(23, a.Data.Length);
                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 send_and_receive_on_conversation_channel() {
			var myQ = Broker.CreateQueue("MyQueue");
			var myMessage = Broker.CreateMessageType("System.String");
			var myContract = Broker.CreateContract("MyContract2", new [] { myMessage }, new[] { myMessage });
			var myService = myQ.CreateService("MyQueue", myContract);

			var c1 = Broker.BeginConversation(myService, myService, myContract);

			var channel = Broker.OpenConversationChannel(c1);
			channel.Send("Hello World");

			var json = new JsonMessageSerializer();
			ServiceBrokerMessageHandler getHelloSendGoodbye = (c, t, b) => {
				Check.That(() => json.Deserialize(b, t).ToString() == "Hello World");
				Broker.OpenConversationChannel(c).Send("Goodbye World!");
			};
			 
			Check.That(() => myQ.TryReceive(getHelloSendGoodbye, TimeSpan.Zero));

			Action<string,object> checkGoodbye = (t, b) => Check.That(() => (string)b == "Goodbye World!"); 
			Check.That(() => channel.TryReceive(checkGoodbye, TimeSpan.Zero));
		}
        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 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 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 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);
            }
        }