public void Setup() { var messageMapper = new MessageMapper(); messageMapper.Initialize(new[] { typeof(IA), typeof(A) }); Serializer = new BsonMessageSerializer(messageMapper); }
public void Interfaces_with_only_properties_should_be_mapped() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(InterfaceWithOnlyProperties) }); Assert.NotNull(mapper.GetMappedTypeFor(typeof(InterfaceWithOnlyProperties))); }
public void Serialize_Deserialize_TransportMessage() { var types = new List<Type> { typeof(C1), typeof(C2) }; var mapper = new MessageMapper(); mapper.Initialize(types); var serializer = new XmlMessageSerializer(mapper); serializer.Initialize(types); var transportMessage = new TransportMessage(); transportMessage.Id = Guid.NewGuid().ToString(); transportMessage.IdForCorrelation = Guid.NewGuid().ToString(); transportMessage.ReturnAddress = Guid.NewGuid().ToString(); transportMessage.WindowsIdentityName = string.Empty; transportMessage.TimeSent = DateTime.Now; transportMessage.Headers = new List<HeaderInfo>(); transportMessage.Body = new object[] { new C1() { Data = "o'tool" }, new C2() { Data = "Timmy" } }; var newTransportMessage = Execute(transportMessage, serializer); var messages = newTransportMessage.Body; Assert.AreEqual(2, messages.Count()); Assert.AreEqual(1, messages.Count(x => x is C1)); Assert.AreEqual(1, messages.Count(x => x is C2)); Assert.AreEqual("o'tool", ((C1)messages.First(x => x is C1)).Data); Assert.AreEqual("Timmy", ((C2)messages.First(x => x is C2)).Data); Assert.AreEqual(transportMessage.Id, newTransportMessage.Id); Assert.AreEqual(transportMessage.IdForCorrelation, newTransportMessage.IdForCorrelation); Assert.AreEqual(transportMessage.ReturnAddress, newTransportMessage.ReturnAddress); Assert.AreEqual(transportMessage.TimeSent, newTransportMessage.TimeSent); Assert.AreEqual(transportMessage.Headers, newTransportMessage.Headers); Assert.AreNotSame(transportMessage, newTransportMessage); }
public void Interfaces_with_methods_should_be_ignored() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(InterfaceWithMethods) }); Assert.Null(mapper.GetMappedTypeFor(typeof(InterfaceWithMethods))); }
protected internal sealed override void Setup(FeatureConfigurationContext context) { var mapper = new MessageMapper(); var settings = context.Settings; var messageMetadataRegistry = settings.Get<MessageMetadataRegistry>(); mapper.Initialize(messageMetadataRegistry.GetAllMessages().Select(m => m.MessageType)); var defaultSerializerAndDefinition = settings.GetMainSerializer(); var defaultSerializer = CreateMessageSerializer(defaultSerializerAndDefinition, mapper, settings); var additionalDeserializers = new List<IMessageSerializer>(); foreach (var definitionAndSettings in context.Settings.GetAdditionalSerializers()) { additionalDeserializers.Add(CreateMessageSerializer(definitionAndSettings, mapper, settings)); } var resolver = new MessageDeserializerResolver(defaultSerializer, additionalDeserializers); var logicalMessageFactory = new LogicalMessageFactory(messageMetadataRegistry, mapper); context.Pipeline.Register(new DeserializeLogicalMessagesConnector(resolver, logicalMessageFactory, messageMetadataRegistry), "Deserializes the physical message body into logical messages"); context.Pipeline.Register(new SerializeMessageConnector(defaultSerializer, messageMetadataRegistry), "Converts a logical message into a physical message"); context.Container.ConfigureComponent(_ => mapper, DependencyLifecycle.SingleInstance); context.Container.ConfigureComponent(_ => messageMetadataRegistry, DependencyLifecycle.SingleInstance); context.Container.ConfigureComponent(_ => logicalMessageFactory, DependencyLifecycle.SingleInstance); LogFoundMessages(messageMetadataRegistry.GetAllMessages().ToList()); }
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); } }
public void Should_handle_concrete_message_with_interface_property() { var messageMapper = new MessageMapper(); messageMapper.Initialize(new[] { typeof(MessageWithInterfaceProperty) }); var serializer = new JsonMessageSerializer(messageMapper); var message = new MessageWithInterfaceProperty { InterfaceProperty = new InterfacePropertyImplementation { SomeProperty = "test" } }; using (var stream = new MemoryStream()) { serializer.Serialize(message, stream); stream.Position = 0; var result = (MessageWithInterfaceProperty) serializer.Deserialize(stream, new[] { typeof(MessageWithInterfaceProperty) })[0]; Assert.AreEqual(message.InterfaceProperty.SomeProperty, result.InterfaceProperty.SomeProperty); } }
public void Should_fail_for_non_public_interface_message() { var mapper = new MessageMapper(); var ex = Assert.Throws <Exception>(() => mapper.Initialize(new[] { typeof(IPrivateInterfaceMessage) })); StringAssert.Contains($"Cannot generate a concrete implementation for '{typeof(IPrivateInterfaceMessage).FullName}' because it is not public. Ensure that all interfaces used as messages are public.", ex.Message); }
public void Should_fail_for_interface_message_with_illegal_interface_property() { var mapper = new MessageMapper(); var ex = Assert.Throws <Exception>(() => mapper.Initialize(new[] { typeof(InterfaceMessageWithIllegalInterfaceProperty) })); StringAssert.Contains($"Cannot generate a concrete implementation for '{typeof(IIllegalProperty).FullName}' because it contains methods. Ensure that all interfaces used as messages do not contain methods.", ex.Message); }
public void Should_create_instance_of_concrete_type_with_illegal_interface_property() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(ConcreteMessageWithIllegalInterfaceProperty) }); mapper.CreateInstance <ConcreteMessageWithIllegalInterfaceProperty>(); }
public void Interfaces_generic_with_methods_should_not_be_mapped() { var mapper = new MessageMapper(); var genericInterfaceType = typeof(InterfaceGenericWithMethods <>); mapper.Initialize(new[] { genericInterfaceType }); Assert.Null(mapper.GetMappedTypeFor(genericInterfaceType)); }
public void Should_map_when_deriving_from_another_interface_with_the_same_property_name_but_different_type() { var mapper = new MessageMapper(); var genericInterfaceType = typeof(InterfaceWithGenericProperty <IBar>); mapper.Initialize(new[] { genericInterfaceType }); Assert.NotNull(mapper.GetMappedTypeFor(genericInterfaceType)); }
public void Generated_type_should_preserve_namespace_to_make_it_easier_for_users_to_define_custom_conventions() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(InterfaceToGenerate) }); Assert.AreEqual(typeof(InterfaceToGenerate).Namespace, mapper.CreateInstance(typeof(InterfaceToGenerate)).GetType().Namespace); }
public void Class_abstract_generic_with_only_properties_generic_should_not_be_mapped() { var mapper = new MessageMapper(); var genericClassType = typeof(GenericAbstractCommand <>); mapper.Initialize(new[] { genericClassType }); Assert.Null(mapper.GetMappedTypeFor(genericClassType)); }
public static T CreateMessage <T>(Action <T> a2) where T : IMessage { IMessageMapper mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(T) }); return(mapper.CreateInstance(a2)); }
public JsonMessageSerializerTest() { messageMapper = new MessageMapper(); messageMapper.Initialize(new[] { typeof(IA), typeof(A) }); }
public void Setup() { var types = new List<Type> { typeof(Sample_Message) }; var mapper = new MessageMapper(); mapper.Initialize(types); serializer = new XmlMessageSerializer(mapper); ((XmlMessageSerializer)serializer).Initialize(types); }
public void Interfaces_with_methods_are_not_supported() { var mapper = new MessageMapper(); Assert.Throws<Exception>(() => mapper.Initialize(new[] { typeof(InterfaceWithMethods) })); }
public void Accept_Attributes_with_no_default_ctor_as_long_as_the_parameter_in_constructor_has_the_same_name_as_the_property() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(InterfaceWithCustomAttributeThatHasNoDefaultConstructor) }); var instance = mapper.CreateInstance(typeof (InterfaceWithCustomAttributeThatHasNoDefaultConstructor)); var attributes = instance.GetType().GetProperty("SomeProperty").GetCustomAttributes(typeof(CustomAttributeWithNoDefaultConstructor),true); var attr = (CustomAttributeWithNoDefaultConstructor)attributes[0]; Assert.AreEqual(attr.Name, "Blah"); }
private static void ConfigureMessageMapper(Configure config) { var messageTypes = Configure.TypesToScan.Where(t => typeof(IMessage).IsAssignableFrom(t)).ToList(); var messageMapper = new MessageMapper(); messageMapper.Initialize(messageTypes); config.Configurer.RegisterSingleton<IMessageMapper>(messageMapper); }
public void Interfaces_with_methods_are_not_supported() { var mapper = new MessageMapper(); Assert.Throws <Exception>(() => mapper.Initialize(new[] { typeof(IInterfaceWithMethods) })); }
public JsonSerializerFacade(params Type[] objectTypes) { this.objectTypes = objectTypes; mapper = new MessageMapper(); var settings = new SettingsHolder(); serializer = new JsonSerializer().Configure(settings)(mapper); mapper.Initialize(objectTypes); }
public void Interface_should_be_created() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(Interface) }); var result = mapper.CreateInstance<Interface>(null); Assert.IsNotNull(result); }
public void Attributes_on_properties_should_be_mapped() { var mapper = new MessageMapper(); mapper.Initialize(new[]{typeof(InterfaceWithPropertiesAndAttributes)}); Assert.IsTrue(PropertyContainsAttribute("SomeProperty",typeof(SomeAttribute),mapper.CreateInstance(typeof(InterfaceWithPropertiesAndAttributes)))); // Doesn't affect properties without attributes Assert.IsFalse(PropertyContainsAttribute("SomeOtherProperty", typeof(SomeAttribute), mapper.CreateInstance(typeof(InterfaceWithPropertiesAndAttributes)))); }
protected internal sealed override void Setup(FeatureConfigurationContext context) { var mapper = new MessageMapper(); var settings = context.Settings; var messageMetadataRegistry = settings.Get <MessageMetadataRegistry>(); mapper.Initialize(messageMetadataRegistry.GetAllMessages().Select(m => m.MessageType)); var defaultSerializerAndDefinition = settings.GetMainSerializer(); var defaultSerializer = CreateMessageSerializer(defaultSerializerAndDefinition, mapper, settings); var additionalDeserializerDefinitions = context.Settings.GetAdditionalSerializers(); var additionalDeserializers = new List <IMessageSerializer>(); var additionalDeserializerDiagnostics = new List <object>(); foreach (var definitionAndSettings in additionalDeserializerDefinitions) { var deserializer = CreateMessageSerializer(definitionAndSettings, mapper, settings); additionalDeserializers.Add(deserializer); var deserializerType = definitionAndSettings.Item1.GetType(); additionalDeserializerDiagnostics.Add(new { Type = deserializerType.FullName, Version = FileVersionRetriever.GetFileVersion(deserializerType), deserializer.ContentType }); } var resolver = new MessageDeserializerResolver(defaultSerializer, additionalDeserializers); var logicalMessageFactory = new LogicalMessageFactory(messageMetadataRegistry, mapper); context.Pipeline.Register(new DeserializeLogicalMessagesConnector(resolver, logicalMessageFactory, messageMetadataRegistry, mapper), "Deserializes the physical message body into logical messages"); context.Pipeline.Register(new SerializeMessageConnector(defaultSerializer, messageMetadataRegistry), "Converts a logical message into a physical message"); context.Container.ConfigureComponent(_ => mapper, DependencyLifecycle.SingleInstance); context.Container.ConfigureComponent(_ => messageMetadataRegistry, DependencyLifecycle.SingleInstance); context.Container.ConfigureComponent(_ => logicalMessageFactory, DependencyLifecycle.SingleInstance); LogFoundMessages(messageMetadataRegistry.GetAllMessages().ToList()); context.Settings.AddStartupDiagnosticsSection("Serialization", new { DefaultSerializer = new { Type = defaultSerializerAndDefinition.Item1.GetType().FullName, Version = FileVersionRetriever.GetFileVersion(defaultSerializerAndDefinition.Item1.GetType()), defaultSerializer.ContentType }, AdditionalDeserializers = additionalDeserializerDiagnostics }); }
public void Interface_should_be_created() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(IInterface) }); var result = mapper.CreateInstance <IInterface>(null); Assert.IsNotNull(result); }
private static void ConfigureMessageMapper(Configure config) { var messageTypes = Configure.TypesToScan.Where(t => t.IsMessageType()).ToList(); var messageMapper = new MessageMapper(); messageMapper.Initialize(messageTypes); config.Configurer.RegisterSingleton <IMessageMapper>(messageMapper); }
public void Serialize_Deserialize_Multiple_Namespaces() { var types = new List<Type> { typeof(C1), typeof(C2) }; var mapper = new MessageMapper(); mapper.Initialize(types); var serializer = new XmlMessageSerializer(mapper); serializer.Initialize(types); Time(new IMessage[] { new C1() { Data = "o'tool" }, new C2() { Data = "Timmy" } }, serializer); }
public void Attributes_on_properties_should_be_mapped() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(IInterfaceWithPropertiesAndAttributes) }); Assert.IsTrue(PropertyContainsAttribute("SomeProperty", typeof(SomeAttribute), mapper.CreateInstance(typeof(IInterfaceWithPropertiesAndAttributes)))); // Doesn't affect properties without attributes Assert.IsFalse(PropertyContainsAttribute("SomeOtherProperty", typeof(SomeAttribute), mapper.CreateInstance(typeof(IInterfaceWithPropertiesAndAttributes)))); }
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 Accept_Attributes_with_no_default_ctor_while_ctor_parameters_are_different_than_properties_of_custom_attribute() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(IInterfaceWithCustomAttributeThatHasNoDefaultConstructorAndNoMatchingParameters) }); var instance = mapper.CreateInstance(typeof(IInterfaceWithCustomAttributeThatHasNoDefaultConstructorAndNoMatchingParameters)); var attributes = instance.GetType().GetProperty("SomeProperty").GetCustomAttributes(typeof(CustomAttributeWithNoDefaultConstructorAndNoMatchingParameters), true); var attr = (CustomAttributeWithNoDefaultConstructorAndNoMatchingParameters)attributes[0]; Assert.AreEqual(attr.Name, "Blah"); }
public JsonSerializerFacade(params Type[] objectTypes) { this.objectTypes = objectTypes; mapper = new MessageMapper(); mapper.Initialize(objectTypes); var settings = new SettingsHolder(); #pragma warning disable CS0618 // Type or member is obsolete serializer = new NewtonsoftSerializer().Configure(settings)(mapper); #pragma warning restore CS0618 // Type or member is obsolete }
public static XmlMessageSerializer Create(params Type[] types) { var mapper = new MessageMapper(); mapper.Initialize(types); var serializer = new XmlMessageSerializer(mapper, new Conventions()); serializer.Initialize(types); return(serializer); }
public void Class_implementing_returnMyself_inheriting_from_iEnumerable_returnMyself_implementation_should_be_mapped() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(DerivedReturnMyselfCollectionImplementingIReturnMyself) }); Assert.NotNull(mapper.GetMappedTypeFor(typeof(DerivedReturnMyselfCollectionImplementingIReturnMyself))); }
public void Class_implementing_iEnumerable_returnMyself_should_be_mapped() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(ClassImplementingIEnumerable <ReturnMyself>) }); Assert.NotNull(mapper.GetMappedTypeFor(typeof(ClassImplementingIEnumerable <ReturnMyself>))); }
public void Setup() { var types = new List <Type> { typeof(Sample_Message) }; var mapper = new MessageMapper(); mapper.Initialize(types); serializer = new XmlMessageSerializer(mapper); ((XmlMessageSerializer)serializer).Initialize(types); }
private IStartableMessageBus Build() { var messageTypes = MessageTypeConventions.ScanAssembliesForMessageTypes(assembliesToScan); var messageMapper = new MessageMapper(); messageMapper.SetMessageTypeConventions(this.MessageTypeConventions); messageMapper.Initialize(messageTypes); var allMessageTypes = messageTypes.Concat(messageMapper.DynamicTypes); MessageSerializer = new XmlMessageSerializer(messageMapper); (MessageSerializer as XmlMessageSerializer).Initialize(messageTypes); this.MessageHandlers.AddAssembliesToScan(assembliesToScan); this.MessageHandlers.Init(); if (executeTheseHandlersFirst.Any()) this.MessageHandlers.ExecuteTheseHandlersFirst(executeTheseHandlersFirst); if (executeTheseHandlersLast.Any()) this.MessageHandlers.ExecuteTheseHandlersLast(executeTheseHandlersLast); // Get endpoint mapping foreach (MessageEndpointMapping mapping in this.MessageEndpointMappingCollection) { try { var messageType = Type.GetType(mapping.Messages, false); if (messageType != null && MessageTypeConventions.IsMessageType(messageType)) { typesToEndpoints[messageType] = mapping.Endpoint.Trim(); continue; } } catch (Exception ex) { Logger.Error("Problem loading message type: " + mapping.Messages, ex); } try { var a = Assembly.Load(mapping.Messages); foreach (var t in a.GetTypes().Where(t => MessageTypeConventions.IsMessageType(t))) typesToEndpoints[t] = mapping.Endpoint.Trim(); } catch (Exception ex) { throw new ArgumentException("Problem loading message assembly: " + mapping.Messages, ex); } } var transport = TransportBuilder.Build(); var messageDispatcher = new MessageDispatcher(ServiceLocator, this.MessageHandlers); var messageBus = new UnicastMessageBus(messageMapper, transport, messageDispatcher); messageBus.MapMessageTypesToAddress(typesToEndpoints); var performanceCounters = new PerformanceCounters(); messageBus.MessageReceived += performanceCounters.OnMessageReceived; messageBus.MessageSent += performanceCounters.OnMessageSent; messageBus.MessageFailed += performanceCounters.OnMessageFailure; messageBus.MessageHandled += performanceCounters.OnMessageHandled; return messageBus; }
public void Accept_Attributes_with_no_default_ctor_as_long_as_the_parameter_in_constructor_has_the_same_name_as_the_property() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(IInterfaceWithCustomAttributeThatHasNoDefaultConstructor) }); var instance = mapper.CreateInstance(typeof(IInterfaceWithCustomAttributeThatHasNoDefaultConstructor)); var attributes = instance.GetType().GetProperty("SomeProperty").GetCustomAttributes(typeof(CustomAttributeWithNoDefaultConstructor), true); var attr = (CustomAttributeWithNoDefaultConstructor)attributes[0]; Assert.AreEqual(attr.Name, "Blah"); }
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(); } } } }
public void TestInterfaces() { var output = new MemoryStream(); var messageMapper = new MessageMapper(); messageMapper.Initialize(new[] { typeof(IA), typeof(IAImpl) }); 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); var serializer = new JsonMessageSerializer(messageMapper); 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 Initialize_ShouldBeThreadsafe() { var mapper = new MessageMapper(); Parallel.For(0, 10, i => { mapper.Initialize(new[] { typeof(SampleMessageClass), typeof(ISampleMessageInterface), typeof(ClassImplementingIEnumerable <>) }); }); }
public static IMessageSerializer Create <T>() { var types = new List <Type> { typeof(T) }; var mapper = new MessageMapper(); mapper.Initialize(types); var serializer = new XmlMessageSerializer(mapper); serializer.Initialize(types); return(serializer); }
public void Deserialize_message_without_concrete_implementation() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(ISuperMessageWithoutConcreteImpl) }); using (var stream = new MemoryStream()) { Serializer.SkipArrayWrappingForSingleMessages = true; var msg = mapper.CreateInstance<ISuperMessageWithoutConcreteImpl>(); msg.SomeProperty = "test"; Serializer.Serialize(new object[] { msg }, stream); stream.Position = 0; var result = (ISuperMessageWithoutConcreteImpl)Serializer.Deserialize(stream, new[] { typeof(ISuperMessageWithoutConcreteImpl) })[0]; Assert.AreEqual("test", result.SomeProperty); } }
/// <summary> /// Use XML serialization that supports interface-based messages. /// </summary> /// <param name="config"></param> /// <returns></returns> public static Configure XmlSerializer(this Configure config) { if (!Configure.BuilderIsConfigured()) { SetXmlSerializerAsDefault.UseXmlSerializer = true; return config; } var messageTypes = Configure.TypesToScan.Where(t => t.IsMessageType()).ToList(); var mapper = new MessageMapper(); mapper.Initialize(messageTypes); config.Configurer.RegisterSingleton<IMessageMapper>(mapper); config.Configurer.RegisterSingleton<IMessageCreator>(mapper);//todo - Modify the builders to auto register all types var serializer = new XmlMessageSerializer(mapper); serializer.Initialize(messageTypes); config.Configurer.RegisterSingleton<IMessageSerializer>(serializer); return config; }
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 messageMapper = new MessageMapper(); messageMapper.Initialize(new[] { typeof(IA), typeof(IAImpl) }); 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); var serializer = new JsonMessageSerializer(messageMapper); 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 Serialize_message_without_concrete_implementation() { var mapper = new MessageMapper(); mapper.Initialize(new []{ typeof(ISuperMessageWithoutConcreteImpl)}); using (var stream = new MemoryStream()) { Serializer.SkipArrayWrappingForSingleMessages = true; Serializer.Serialize(new object[] { mapper.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 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 Accept_attributes_with_value_attribute() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(IMyEventWithAttributeWithBoolProperty) }); var instance = mapper.CreateInstance(typeof(IMyEventWithAttributeWithBoolProperty)); var attributes = instance.GetType().GetProperty("EventId").GetCustomAttributes(typeof(CustomAttributeWithValueProperties), true); var attr = attributes[0] as CustomAttributeWithValueProperties; Assert.AreEqual(attr != null && attr.FlagIsSet, true); if (attr != null) Assert.AreEqual(attr.MyAge, 21); }
protected JsonMessageSerializerTestBase() { MessageMapper = new MessageMapper(); MessageMapper.Initialize(new[] { typeof(IA), typeof(A) }); }
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 Deserialize_message_without_concrete_implementation() { var messageMapper = new MessageMapper(); messageMapper.Initialize(new[] { typeof(ISuperMessageWithoutConcreteImpl) }); var 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 Accept_Attributes_with_no_default_ctor_while_ctor_parameters_are_different_than_properties_of_custom_attribute() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(InterfaceWithCustomAttributeThatHasNoDefaultConstructorAndNoMatchingParameters) }); var instance = mapper.CreateInstance(typeof(InterfaceWithCustomAttributeThatHasNoDefaultConstructorAndNoMatchingParameters)); var attributes = instance.GetType().GetProperty("SomeProperty").GetCustomAttributes(typeof(CustomAttributeWithNoDefaultConstructorAndNoMatchingParameters), true); var attr = (CustomAttributeWithNoDefaultConstructorAndNoMatchingParameters)attributes[0]; Assert.AreEqual(attr.Name, "Blah"); }
public void Should_handle_types_correctly() { 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" } } }; new Random().NextBytes(obj.Data); var output = new MemoryStream(); var messageMapper = new MessageMapper(); messageMapper.Initialize(new[] { typeof(IA), typeof(A) }); var 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("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 Serialize_message_without_concrete_implementation() { var messageMapper = new MessageMapper(); messageMapper.Initialize(new[] { typeof(ISuperMessageWithoutConcreteImpl) }); var 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); } }
protected JsonMessageSerializerTestBase(params Type[] messageTypes) { MessageMapper = new MessageMapper(); MessageMapper.Initialize(new[] { typeof(IA), typeof(A) }.Union(messageTypes)); }