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);
        }
Ejemplo n.º 2
0
        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 Should_handle_interface_message_with_interface_property()
        {
            var messageMapper = new MessageMapper();
            messageMapper.Initialize(new[]
            {
                typeof(IMessageWithInterfaceProperty)
            });
            var serializer = new JsonMessageSerializer(messageMapper);

            IMessageWithInterfaceProperty message = new InterfaceMessageWithInterfacePropertyImplementation
            {
                InterfaceProperty = new InterfacePropertyImplementation
                {
                    SomeProperty = "test"
                }
            };

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

                stream.Position = 0;

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

                Assert.AreEqual(message.InterfaceProperty.SomeProperty, result.InterfaceProperty.SomeProperty);
            }
        }
Ejemplo n.º 4
0
        public void Interfaces_with_methods_should_be_ignored()
        {
            var mapper = new MessageMapper();
            mapper.Initialize(new[] { typeof(InterfaceWithMethods) });

            Assert.Null(mapper.GetMappedTypeFor(typeof(InterfaceWithMethods)));
        }
        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 Setup()
        {
            var messageMapper = new MessageMapper();
              messageMapper.Initialize(new[] { typeof(IA), typeof(A) });

              Serializer = new BsonMessageSerializer(messageMapper);
        }
Ejemplo n.º 7
0
        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 Interfaces_with_methods_are_not_supported()
 {
     var mapper = new MessageMapper();
     Assert.Throws<Exception>(() => mapper.Initialize(new[]
     {
         typeof(InterfaceWithMethods)
     }));
 }
 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);
 }
Ejemplo n.º 10
0
        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);
        }
Ejemplo n.º 11
0
 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");
 }
Ejemplo n.º 12
0
        public void Interface_should_be_created()
        {
            var mapper = new MessageMapper();
            mapper.Initialize(new[] { typeof(Interface) });

            var result = mapper.CreateInstance<Interface>(null);

            Assert.IsNotNull(result);
        }
Ejemplo n.º 13
0
 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))));
 }
Ejemplo n.º 14
0
        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);
        }
Ejemplo n.º 15
0
        public void Using_xml_message_serialization()
        {
            IMessageMapper mapper = new MessageMapper();
            var serializer = new MessageSerializer
                                 {
                                     MessageMapper = mapper,
                                     MessageTypes = new List<Type>(new[] { typeof(TestMessage) })
                                 };

            ExecuteAndVerify(serializer);
        }
Ejemplo n.º 16
0
        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;
        }
Ejemplo n.º 17
0
        public void Configuration(IAppBuilder app)
        {
            var actorSystem = ActorSystem.Create("TestSystem");
            actorSystem.ActorOf<EchoActor>("echo");

            //register message types
            var mapper = new MessageMapper()
                                .Add<Echo>();

            ServiceLocator.Register<ActorSystem>(actorSystem);
            ServiceLocator.Register<MessageMapper>(mapper);

            app.MapSignalR();
        }
        private static JsonMessageSerializer CreateSerializer()
        {
            var mapper = new MessageMapper();
            var ser = new JsonMessageSerializer(mapper);

            //ser.JsonSerializerSettings.ContractResolver = new DefaultContractResolver
            //{
            //    DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance
            //};

            //ser.JsonSerializerSettings.MissingMemberHandling = MissingMemberHandling.Error;
            //ser.JsonSerializerSettings.TypeNameHandling = TypeNameHandling.All;

            return ser;
        }
Ejemplo n.º 19
0
        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;
        }
        //
        // Fetch all messages from a user to a user
        //
        public ReadResponseMessage fetchMessagesFromUserToUser(String fromUser, String toUser)
        {
            List <Message>      messages = new List <Message>();
            ReadResponseMessage response;

            try
            {
                List <BsonDocument> documents = col.Find(m => m["from"] == fromUser && m["to"] == toUser).ToList();
                foreach (var doc in documents)
                {
                    Message message = MessageMapper.toMessage(doc);
                    messages.Add(message);
                }
                response = new ReadResponseMessage(Status.STATUS.SUCCESS, messages, null);
            }
            catch (MongoWriteException err)
            {
                response = new ReadResponseMessage(Status.STATUS.ERROR, messages, err);
            }


            return(response);
        }
Ejemplo n.º 22
0
        public void SerializeInvalidCharacters()
        {
            IMessageMapper mapper     = new MessageMapper();
            var            serializer = SerializerFactory.Create <MessageWithInvalidCharacter>();
            var            msg        = mapper.CreateInstance <MessageWithInvalidCharacter>();

            var sb = new StringBuilder();

            sb.Append("Hello");
            sb.Append((char)0x1C);
            sb.Append("John");
            msg.Special = sb.ToString();

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(new[] { msg }, stream);
                stream.Position = 0;

                var msgArray = serializer.Deserialize(stream);
                var m        = msgArray[0] as MessageWithInvalidCharacter;
                Assert.AreEqual(sb.ToString(), m.Special);
            }
        }
Ejemplo n.º 23
0
        public void Deserialize_message_with_interface_without_wrapping()
        {
            var messageMapper = new MessageMapper();
            var serializer    = new JsonMessageSerializer(messageMapper);

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(new SuperMessage
                {
                    SomeProperty = "John"
                }, stream);

                stream.Position = 0;

                var result = (SuperMessage)serializer.Deserialize(stream, new[]
                {
                    typeof(SuperMessage),
                    typeof(IMyEvent)
                })[0];

                Assert.AreEqual("John", result.SomeProperty);
            }
        }
Ejemplo n.º 24
0
        public async Task MessageBoardService_GetAsync_Returns_Two_Messages()
        {
            // Arrange
            var options = new DbContextOptionsBuilder <MessageBoardDbContext>()
                          .UseInMemoryDatabase("MessageBoardDB")
                          .Options;

            using (var dbContext = new MessageBoardDbContext(options))
            {
                // Clear existing messages
                dbContext.Messages.RemoveRange(dbContext.Messages);
                await dbContext.SaveChangesAsync();

                // Initialize new messages
                dbContext.Messages.Add(new MessageDb {
                    User = "******", Content = "Hello Tom.", Created = DateTime.Now.AddMinutes(5)
                });
                dbContext.Messages.Add(new MessageDb {
                    User = "******", Content = "Hi, Rick.", Created = DateTime.Now.AddMinutes(5)
                });
                await dbContext.SaveChangesAsync();
            };

            var mapper = new MessageMapper();

            using (var dbContext = new MessageBoardDbContext(options))
            {
                var service = new MessageBoardService(mapper, dbContext);

                // Act
                var result = await service.GetAsync();

                // Assert
                Assert.Equal(2, result.Messages.Count());
            };
        }
Ejemplo n.º 25
0
        public void SerializeClosedGenericListsInSameNamespace()
        {
            IMessageMapper mapper     = new MessageMapper();
            var            serializer = SerializerFactory.Create <MessageWithClosedList>();
            var            msg        = mapper.CreateInstance <MessageWithClosedList>();

            msg.Items = new ItemList
            {
                new MessageWithListItem
                {
                    Data = "Hello"
                }
            };

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(msg, stream);
                stream.Position = 0;

                var msgArray = serializer.Deserialize(stream);
                var m        = (MessageWithClosedList)msgArray[0];
                Assert.AreEqual("Hello", m.Items.First().Data);
            }
        }
Ejemplo n.º 26
0
        public void SerializeClosedGenericListsInAlternateNamespaceMultipleIListImplementations()
        {
            IMessageMapper mapper     = new MessageMapper();
            var            serializer = SerializerFactory.Create <MessageWithClosedListInAlternateNamespaceMultipleIListImplementations>();
            var            msg        = mapper.CreateInstance <MessageWithClosedListInAlternateNamespaceMultipleIListImplementations>();

            msg.Items = new AlternateItemListMultipleIListImplementations
            {
                new MessageWithListItemAlternate
                {
                    Data = "Hello"
                }
            };

            using (var stream = new MemoryStream())
            {
                serializer.Serialize(msg, stream);
                stream.Position = 0;

                var msgArray = serializer.Deserialize(stream);
                var m        = (MessageWithClosedListInAlternateNamespaceMultipleIListImplementations)msgArray[0];
                Assert.AreEqual("Hello", m.Items.First <MessageWithListItemAlternate>().Data);
            }
        }
Ejemplo n.º 27
0
        public void Deserialize_message_with_concrete_implementation_and_interface()
        {
            var map    = new[] { typeof(SuperMessageWithConcreteImpl), typeof(ISuperMessageWithConcreteImpl) };
            var mapper = new MessageMapper();

            mapper.Initialize(map);

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

                Serializer.Serialize(new object[] { msg }, stream);

                stream.Position = 0;

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

                Assert.IsInstanceOf <SuperMessageWithConcreteImpl>(result);
                Assert.AreEqual("test", result.SomeProperty);
            }
        }
        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 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();

            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(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]);
        }
Ejemplo n.º 30
0
 public ProductService(IProductRepository productRepository, ICatalogueService catalogueService)
 {
     _productRepository = productRepository;
     _catalogueService  = catalogueService;
     _messageMapper     = new MessageMapper();
 }
        private object GetObjectOfTypeFromNode(Type t, XmlNode node)
        {
            if (t.IsSimpleType())
            {
                return(GetPropertyValue(t, node));
            }

            if (t == typeof(WireEncryptedString))
            {
                if (EncryptionService != null)
                {
                    var encrypted = GetObjectOfTypeFromNode(typeof(EncryptedValue), node) as EncryptedValue;
                    var s         = EncryptionService.Decrypt(encrypted);

                    return(new WireEncryptedString {
                        Value = s
                    });
                }

                foreach (XmlNode n in node.ChildNodes)
                {
                    if (n.Name.ToLower() == "encryptedbase64value")
                    {
                        var wes = new WireEncryptedString();
                        wes.Value = GetPropertyValue(typeof(String), n) as string;

                        return(wes);
                    }
                }
            }

            if (typeof(IEnumerable).IsAssignableFrom(t))
            {
                return(GetPropertyValue(t, node));
            }

            object result = MessageMapper.CreateInstance(t);

            foreach (XmlNode n in node.ChildNodes)
            {
                Type type = null;
                if (n.Name.Contains(":"))
                {
                    type = Type.GetType("System." + n.Name.Substring(0, n.Name.IndexOf(":")), false, true);
                }

                var prop = GetProperty(t, n.Name);
                if (prop != null)
                {
                    var val = GetPropertyValue(type ?? prop.PropertyType, n);
                    if (val != null)
                    {
                        propertyInfoToLateBoundPropertySet[prop].Invoke(result, val);
                        continue;
                    }
                }

                var field = GetField(t, n.Name);
                if (field != null)
                {
                    object val = GetPropertyValue(type ?? field.FieldType, n);
                    if (val != null)
                    {
                        fieldInfoToLateBoundFieldSet[field].Invoke(result, val);
                        continue;
                    }
                }
            }

            return(result);
        }
        /// <summary>
        /// Deserializes the given stream to an array of messages which are returned.
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public IMessage[] Deserialize(Stream stream)
        {
            prefixesToNamespaces = new Dictionary <string, string>();
            messageBaseTypes     = new List <Type>();
            var result = new List <IMessage>();

            var doc = new XmlDocument();

            doc.Load(XmlReader.Create(stream, new XmlReaderSettings {
                CheckCharacters = false
            }));

            if (doc.DocumentElement == null)
            {
                return(result.ToArray());
            }

            foreach (XmlAttribute attr in doc.DocumentElement.Attributes)
            {
                if (attr.Name == "xmlns")
                {
                    defaultNameSpace = attr.Value.Substring(attr.Value.LastIndexOf("/") + 1);
                }
                else
                {
                    if (attr.Name.Contains("xmlns:"))
                    {
                        int    colonIndex = attr.Name.LastIndexOf(":");
                        string prefix     = attr.Name.Substring(colonIndex + 1);

                        if (prefix.Contains(BASETYPE))
                        {
                            Type baseType = MessageMapper.GetMappedTypeFor(attr.Value);
                            if (baseType != null)
                            {
                                messageBaseTypes.Add(baseType);
                            }
                        }
                        else
                        {
                            prefixesToNamespaces[prefix] = attr.Value;
                        }
                    }
                }
            }

            if (doc.DocumentElement.Name.ToLower() != "messages")
            {
                object m = Process(doc.DocumentElement, null);

                if (m == null)
                {
                    throw new SerializationException("Could not deserialize message.");
                }

                result.Add(m as IMessage);
            }
            else
            {
                foreach (XmlNode node in doc.DocumentElement.ChildNodes)
                {
                    object m = Process(node, null);

                    result.Add(m as IMessage);
                }
            }

            defaultNameSpace = null;

            return(result.ToArray());
        }
        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);
        }
Ejemplo n.º 34
0
 public ClusterService(IClusterRepository clusterRepository)
 {
     _clusterRepository = clusterRepository;
     _messageMapper     = new MessageMapper();
 }
Ejemplo n.º 35
0
        public void Should_throw_for_non_registered_message()
        {
            var action = new Func <string>(() => MessageMapper.GetQueueName(typeof(NotRegisteredMessage)));

            action.Invoking(m => m.Invoke()).Should().Throw <MessageMappingMissingException>();
        }
        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 DeserializeLogicalMessagesConnector(MessageDeserializerResolver deserializerResolver, LogicalMessageFactory logicalMessageFactory, MessageMetadataRegistry messageMetadataRegistry, MessageMapper mapper)
 {
     this.deserializerResolver    = deserializerResolver;
     this.logicalMessageFactory   = logicalMessageFactory;
     this.messageMetadataRegistry = messageMetadataRegistry;
     this.mapper = mapper;
 }
Ejemplo n.º 38
0
        public async Task <IStartableEndpoint> Initialize()
        {
            RegisterCriticalErrorHandler();

            var concreteTypes = settings.GetAvailableTypes()
                                .Where(IsConcrete)
                                .ToList();

            var featureActivator = BuildFeatureActivator(concreteTypes);

            ConfigRunBeforeIsFinalized(concreteTypes);

            var transportInfrastructure = InitializeTransportComponent();

            var receiveConfiguration = BuildReceiveConfiguration(transportInfrastructure);

            var routing = InitializeRouting(transportInfrastructure, receiveConfiguration);

            var messageMapper = new MessageMapper();

            settings.Set <IMessageMapper>(messageMapper);

            pipelineComponent.AddRootContextItem <IMessageMapper>(messageMapper);

            var featureStats = featureActivator.SetupFeatures(container, pipelineComponent.PipelineSettings, routing, receiveConfiguration);

            settings.AddStartupDiagnosticsSection("Features", featureStats);

            pipelineComponent.Initialize(builder, container);

            container.ConfigureComponent(b => settings.Get <Notifications>(), DependencyLifecycle.SingleInstance);

            var eventAggregator = new EventAggregator(settings.Get <NotificationSubscriptions>());

            pipelineComponent.AddRootContextItem <IEventAggregator>(eventAggregator);

            var queueBindings = settings.Get <QueueBindings>();

            var receiveComponent = CreateReceiveComponent(receiveConfiguration, transportInfrastructure, pipelineComponent, queueBindings, eventAggregator);

            var shouldRunInstallers = settings.GetOrDefault <bool>("Installers.Enable");

            if (shouldRunInstallers)
            {
                var username = GetInstallationUserName();

                if (settings.CreateQueues())
                {
                    await receiveComponent.CreateQueuesIfNecessary(queueBindings, username).ConfigureAwait(false);
                }

                await RunInstallers(concreteTypes, username).ConfigureAwait(false);
            }

            settings.AddStartupDiagnosticsSection("Endpoint",
                                                  new
            {
                Name               = settings.EndpointName(),
                SendOnly           = settings.Get <bool>("Endpoint.SendOnly"),
                NServiceBusVersion = GitFlowVersion.MajorMinorPatch
            }
                                                  );

            var messageSession = new MessageSession(pipelineComponent.CreateRootContext(builder));

            return(new StartableEndpoint(settings, builder, featureActivator, transportInfrastructure, receiveComponent, criticalError, messageSession));
        }
Ejemplo n.º 39
0
#pragma warning disable CS1591 // 缺少对公共可见类型或成员“LeactosController.LeactosController(IMessageService, IUserService, MessageMapper, EmailHelper)”的 XML 注释
        public LeactosController(IMessageService messageService, IUserService userService, MessageMapper mapperToMessageDTO, EmailHelper sendEmail)
#pragma warning restore CS1591 // 缺少对公共可见类型或成员“LeactosController.LeactosController(IMessageService, IUserService, MessageMapper, EmailHelper)”的 XML 注释
        {
            this.messageService     = messageService;
            this.userService        = userService;
            this.mapperToMessageDTO = mapperToMessageDTO;
            this.sendEmail          = sendEmail;
        }
Ejemplo n.º 40
0
 public CategoryService(ICategoryRepository categoryRepository)
 {
     _categoryRepository = categoryRepository;
     _messageMapper      = new MessageMapper();
 }
 protected JsonMessageSerializerTestBase(params Type[] messageTypes)
 {
     MessageMapper = new MessageMapper();
     MessageMapper.Initialize(new[] { typeof(IA), typeof(A) }.Union(messageTypes));
 }
Ejemplo n.º 42
0
        void Initialize()
        {
            var pipelineSettings = settings.Get <PipelineSettings>();

            hostingConfiguration.Container.RegisterSingleton <ReadOnlySettings>(settings);

            featureComponent = new FeatureComponent(settings);

            // This needs to happen here to make sure that features enabled state is present in settings so both
            // IWantToRunBeforeConfigurationIsFinalized implementations and transports can check access it
            featureComponent.RegisterFeatureEnabledStatusInSettings(hostingConfiguration);

            ConfigRunBeforeIsFinalized(hostingConfiguration);

            var transportConfiguration = TransportComponent.PrepareConfiguration(settings.Get <TransportComponent.Settings>());

            var receiveConfiguration = BuildReceiveConfiguration(transportConfiguration);

            var routingComponent = RoutingComponent.Initialize(
                settings.Get <RoutingComponent.Configuration>(),
                transportConfiguration,
                receiveConfiguration,
                settings.Get <Conventions>(),
                pipelineSettings);

            var messageMapper = new MessageMapper();

            settings.Set <IMessageMapper>(messageMapper);

            recoverabilityComponent = new RecoverabilityComponent(settings);

            var featureConfigurationContext = new FeatureConfigurationContext(settings, hostingConfiguration.Container, pipelineSettings, routingComponent, receiveConfiguration);

            featureComponent.Initalize(featureConfigurationContext);

            hostingConfiguration.CreateHostInformationForV7BackwardsCompatibility();

            recoverabilityComponent.Initialize(receiveConfiguration, hostingConfiguration);

            sendComponent = SendComponent.Initialize(pipelineSettings, hostingConfiguration, routingComponent, messageMapper);

            pipelineComponent = PipelineComponent.Initialize(pipelineSettings, hostingConfiguration);

            hostingConfiguration.Container.ConfigureComponent(b => settings.Get <Notifications>(), DependencyLifecycle.SingleInstance);

            receiveComponent = ReceiveComponent.Initialize(
                settings.Get <ReceiveComponent.Configuration>(),
                receiveConfiguration,
                transportConfiguration,
                pipelineComponent,
                settings.ErrorQueueAddress(),
                hostingConfiguration,
                pipelineSettings);

            installationComponent = InstallationComponent.Initialize(settings.Get <InstallationComponent.Configuration>(),
                                                                     hostingConfiguration);

            // The settings can only be locked after initializing the feature component since it uses the settings to store & share feature state.
            // As well as all the other components have been initialized
            settings.PreventChanges();

            transportComponent = TransportComponent.Initialize(transportConfiguration, hostingConfiguration);

            settings.AddStartupDiagnosticsSection("Endpoint",
                                                  new
            {
                Name               = settings.EndpointName(),
                SendOnly           = settings.Get <bool>("Endpoint.SendOnly"),
                NServiceBusVersion = GitVersionInformation.MajorMinorPatch
            }
                                                  );
        }
Ejemplo n.º 43
0
        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 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);
            }
        }
Ejemplo n.º 45
0
        public void TestInterfaces()
        {
            var mapper     = new MessageMapper();
            var serializer = SerializerFactory.Create <ISecondSerializableMessage>(mapper);


            var o = mapper.CreateInstance <ISecondSerializableMessage>();

            o.Id      = Guid.NewGuid();
            o.Age     = 10;
            o.Address = Guid.NewGuid().ToString();
            o.Int     = 7;
            o.Name    = "udi";
            o.Uri     = new Uri("http://www.UdiDahan.com/");
            o.Risk    = new Risk
            {
                Percent  = 0.15D,
                Annum    = true,
                Accuracy = 0.314M
            };
            o.Some         = SomeEnum.B;
            o.Start        = DateTime.Now;
            o.Duration     = TimeSpan.Parse("-01:15:27.123");
            o.Offset       = DateTimeOffset.Now;
            o.Lookup       = new MyDictionary();
            o.Lookup["1"]  = "1";
            o.Foos         = new Dictionary <string, List <Foo> >();
            o.Foos["foo1"] = new List <Foo>(new[]
            {
                new Foo
                {
                    Name  = "1",
                    Title = "1"
                },
                new Foo
                {
                    Name  = "2",
                    Title = "2"
                }
            });
            o.Data = new byte[]
            {
                1,
                2,
                3,
                4,
                5,
                4,
                3,
                2,
                1
            };
            o.SomeStrings = new List <string>
            {
                "a",
                "b",
                "c"
            };

            o.ArrayFoos = new[]
            {
                new Foo
                {
                    Name  = "FooArray1",
                    Title = "Mr."
                },
                new Foo
                {
                    Name  = "FooAray2",
                    Title = "Mrs"
                }
            };
            o.Bars = new[]
            {
                new Bar
                {
                    Name   = "Bar1",
                    Length = 1
                },
                new Bar
                {
                    Name   = "BAr2",
                    Length = 5
                }
            };
            o.NaturalNumbers = new HashSet <int>(new[]
            {
                0,
                1,
                2,
                3,
                4,
                5,
                6,
                7,
                8,
                9
            });
            o.Developers = new HashSet <string>(new[]
            {
                "Udi Dahan",
                "Andreas Ohlund",
                "Matt Burton",
                "Jonathan Oliver et al"
            });

            o.Parent         = mapper.CreateInstance <IFirstSerializableMessage>();
            o.Parent.Name    = "udi";
            o.Parent.Age     = 10;
            o.Parent.Address = Guid.NewGuid().ToString();
            o.Parent.Int     = 7;
            o.Parent.Name    = "-1";
            o.Parent.Risk    = new Risk
            {
                Percent  = 0.15D,
                Annum    = true,
                Accuracy = 0.314M
            };

            o.Names = new List <IFirstSerializableMessage>();
            for (var i = 0; i < number; i++)
            {
                var firstMessage = mapper.CreateInstance <IFirstSerializableMessage>();
                o.Names.Add(firstMessage);
                firstMessage.Age     = 10;
                firstMessage.Address = Guid.NewGuid().ToString();
                firstMessage.Int     = 7;
                firstMessage.Name    = i.ToString();
                firstMessage.Risk    = new Risk
                {
                    Percent  = 0.15D,
                    Annum    = true,
                    Accuracy = 0.314M
                };
            }

            o.MoreNames = o.Names.ToArray();

            Time(o, serializer);
        }
Ejemplo n.º 46
0
        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_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);
            }
        }
Ejemplo n.º 48
0
 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");
 }
Ejemplo n.º 49
0
        public void Queue_Manager_Test()
        {
            var clientManager = new PooledRedisClientManager();

            clientManager.GetClient().FlushDb();
            var manager       = new QueueManager(new JsonSerializer(), clientManager, new QueueKeyNameProvider(false));
            var messageMapper = new MessageMapper();

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

            var nsbSerializer = new JsonMessageSerializer(messageMapper);

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

            var transportMessage = new TransportMessage()
            {
                Id            = Guid.NewGuid().ToString("N"),
                MessageIntent = MessageIntentEnum.Send,
                Headers       = new Dictionary <string, string>()
            };

            transportMessage.Headers["NServiceBus.FailedQ"] = "original";

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

            var errorAddress = Address.Parse("error");

            manager.SendMessageToQueue(transportMessage, errorAddress);

            var messageCount = manager.GetMessageCount(errorAddress);

            var messages = manager.GetAllMessages(errorAddress);

            Assert.IsTrue(messages.Count == 1);
            Assert.IsTrue(messages[0].Id == transportMessage.Id);

            Assert.IsTrue(messageCount == 1);

            var queues = manager.GetAllQueues();

            Assert.IsTrue(queues.Count == 1);

            manager.ReturnAllMessagesToSourceQueue(errorAddress);

            var queues2 = manager.GetAllQueues();

            Assert.IsTrue(queues2.Count(o => o.Queue == "original") > 0);

            manager.DeleteQueue(Address.Parse("original"));

            var queues3 = manager.GetAllQueues();

            Assert.IsTrue(queues3.Count == 0);
        }
        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);
            }
        }
        private object Process(XmlNode node, object parent)
        {
            string name     = node.Name;
            string typeName = defaultNameSpace + "." + name;

            if (name.Contains(":"))
            {
                int colonIndex = node.Name.IndexOf(":");
                name = name.Substring(colonIndex + 1);
                string prefix = node.Name.Substring(0, colonIndex);
                string ns     = prefixesToNamespaces[prefix];

                typeName = ns.Substring(nameSpace.LastIndexOf("/") + 1) + "." + name;
            }

            if (name.Contains("NServiceBus."))
            {
                typeName = name;
            }

            if (parent != null)
            {
                if (parent is IEnumerable)
                {
                    if (parent.GetType().IsArray)
                    {
                        return(GetObjectOfTypeFromNode(parent.GetType().GetElementType(), node));
                    }

                    var args = parent.GetType().GetGenericArguments();
                    if (args.Length == 1)
                    {
                        return(GetObjectOfTypeFromNode(args[0], node));
                    }
                }

                PropertyInfo prop = parent.GetType().GetProperty(name);
                if (prop != null)
                {
                    return(GetObjectOfTypeFromNode(prop.PropertyType, node));
                }
            }

            Type t = MessageMapper.GetMappedTypeFor(typeName);

            if (t == null)
            {
                logger.Debug("Could not load " + typeName + ". Trying base types...");
                foreach (Type baseType in messageBaseTypes)
                {
                    try
                    {
                        logger.Debug("Trying to deserialize message to " + baseType.FullName);
                        return(GetObjectOfTypeFromNode(baseType, node));
                    }
                    // ReSharper disable EmptyGeneralCatchClause
                    catch { } // intentionally swallow exception
                }
                // ReSharper restore EmptyGeneralCatchClause

                throw new TypeLoadException("Could not handle type '" + typeName + "'.");
            }

            return(GetObjectOfTypeFromNode(t, node));
        }
Ejemplo n.º 52
0
        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);
        }
        /// <summary>
        /// Serializes the given messages to the given stream.
        /// </summary>
        /// <param name="messages"></param>
        /// <param name="stream"></param>
        public void Serialize(IMessage[] messages, Stream stream)
        {
            namespacesToPrefix = new Dictionary <string, string>();
            namespacesToAdd    = new List <Type>();

            var namespaces = GetNamespaces(messages, MessageMapper);

            for (int i = 0; i < namespaces.Count; i++)
            {
                string prefix = "q" + i;
                if (i == 0)
                {
                    prefix = "";
                }

                if (namespaces[i] != null)
                {
                    namespacesToPrefix[namespaces[i]] = prefix;
                }
            }

            var messageBuilder = new StringBuilder();

            foreach (var m in messages)
            {
                var t = MessageMapper.GetMappedTypeFor(m.GetType());

                WriteObject(t.Name, t, m, messageBuilder);
            }

            var builder = new StringBuilder();

            List <string> baseTypes = GetBaseTypes(messages, MessageMapper);

            builder.AppendLine("<?xml version=\"1.0\" ?>");

            builder.Append("<Messages xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"");

            for (int i = 0; i < namespaces.Count; i++)
            {
                string prefix = "q" + i;
                if (i == 0)
                {
                    prefix = "";
                }

                builder.AppendFormat(" xmlns{0}=\"{1}/{2}\"", (prefix != "" ? ":" + prefix : prefix), nameSpace, namespaces[i]);
            }

            foreach (var type in namespacesToAdd)
            {
                builder.AppendFormat(" xmlns:{0}=\"{1}\"", type.Name.ToLower(), type.Name);
            }

            for (int i = 0; i < baseTypes.Count; i++)
            {
                string prefix = BASETYPE;
                if (i != 0)
                {
                    prefix += i;
                }

                builder.AppendFormat(" xmlns:{0}=\"{1}\"", prefix, baseTypes[i]);
            }

            builder.Append(">\n");

            builder.Append(messageBuilder.ToString());

            builder.AppendLine("</Messages>");

            byte[] buffer = Encoding.UTF8.GetBytes(builder.ToString());
            stream.Write(buffer, 0, buffer.Length);
        }
Ejemplo n.º 54
0
 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);
 }
Ejemplo n.º 55
0
 public CatalogueService(IProductRepository productRepository) //Constracter
 {
     _productRepository = productRepository;
     _messageMapper     = new MessageMapper();
 }
Ejemplo n.º 56
0
 protected JsonMessageSerializerTestBase()
 {
     MessageMapper = new MessageMapper();
     MessageMapper.Initialize(new[] { typeof(IA), typeof(A) });
 }
Ejemplo n.º 57
0
        protected void ReceiveMessage <T>(T message, IDictionary <string, string> headers = null, MessageMapper mapper = null)
        {
            RegisterMessageType <T>();
            var messageToReceive = Helpers.Serialize(message, mapper: mapper);

            if (headers != null)
            {
                foreach (var header in headers)
                {
                    messageToReceive.Headers[header.Key] = header.Value;
                }
            }

            ReceiveMessage(messageToReceive);
        }
        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);
            }
        }
Ejemplo n.º 59
0
        void Initialize()
        {
            containerComponent.ContainerConfiguration.RegisterSingleton <ReadOnlySettings>(settings);

            RegisterCriticalErrorHandler();

            var concreteTypes = settings.GetAvailableTypes()
                                .Where(IsConcrete)
                                .ToList();

            featureComponent = new FeatureComponent(settings);

            // This needs to happen here to make sure that features enabled state is present in settings so both
            // IWantToRunBeforeConfigurationIsFinalized implementations and transports can check access it
            featureComponent.RegisterFeatureEnabledStatusInSettings(concreteTypes);

            ConfigRunBeforeIsFinalized(concreteTypes);

            transportInfrastructure = InitializeTransportComponent();

            var receiveConfiguration = BuildReceiveConfiguration(transportInfrastructure);

            var routingComponent = new RoutingComponent(settings);

            routingComponent.Initialize(transportInfrastructure, pipelineComponent, receiveConfiguration);

            var messageMapper = new MessageMapper();

            settings.Set <IMessageMapper>(messageMapper);

            pipelineComponent.AddRootContextItem <IMessageMapper>(messageMapper);

            recoverabilityComponent = new RecoverabilityComponent(settings);

            var featureConfigurationContext = new FeatureConfigurationContext(settings, containerComponent.ContainerConfiguration, pipelineComponent.PipelineSettings, routingComponent, receiveConfiguration);

            featureComponent.Initalize(containerComponent, featureConfigurationContext);
            //The settings can only be locked after initializing the feature component since it uses the settings to store & share feature state.
            settings.PreventChanges();

            recoverabilityComponent.Initialize(receiveConfiguration);

            pipelineComponent.Initialize(containerComponent);
            containerComponent.ContainerConfiguration.ConfigureComponent(b => settings.Get <Notifications>(), DependencyLifecycle.SingleInstance);

            var eventAggregator = new EventAggregator(settings.Get <NotificationSubscriptions>());

            pipelineComponent.AddRootContextItem <IEventAggregator>(eventAggregator);

            var shouldRunInstallers = settings.GetOrDefault <bool>("Installers.Enable");

            if (shouldRunInstallers)
            {
                RegisterInstallers(concreteTypes);
            }

            settings.AddStartupDiagnosticsSection("Endpoint",
                                                  new
            {
                Name               = settings.EndpointName(),
                SendOnly           = settings.Get <bool>("Endpoint.SendOnly"),
                NServiceBusVersion = GitVersionInformation.MajorMinorPatch
            }
                                                  );

            queueBindings    = settings.Get <QueueBindings>();
            receiveComponent = CreateReceiveComponent(receiveConfiguration, transportInfrastructure, pipelineComponent, queueBindings, eventAggregator);
        }
Ejemplo n.º 60
0
 public SmartMeterService(ISmartMeterRepository smartmeterRepository)
 {
     _smartmeterRepository = smartmeterRepository;
     _messageMapper        = new MessageMapper();
 }