List <Type> GetFullTypes(IEnumerable <object> messages) { var types = new List <Type>(); foreach (var m in messages) { var messageType = m.GetType(); var s = MessageMapper.GetMappedTypeFor(messageType); if (types.Contains(s)) { continue; } types.Add(s); foreach (var t in GetParentTypes(messageType) .Where(MessageConventionExtensions.IsMessageType) .Where(t => !types.Contains(t))) { types.Add(t); } } return(types); }
private string GetDestinationForMessageType(Type messageType) { string destination = null; if (staticRoutes.TryGetValue(messageType, out destination)) { return(destination); } if (!messageType.IsInterface) { var interfaces = messageType.GetInterfaces(); foreach (var _interface in interfaces) { if (staticRoutes.TryGetValue(_interface, out destination)) { return(destination); } } var t = MessageMapper.GetMappedTypeFor(messageType); if (t != null && t != messageType) { return(GetDestinationForMessageType(t)); } } return(destination); }
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 Interfaces_with_methods_should_be_ignored() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(InterfaceWithMethods) }); Assert.Null(mapper.GetMappedTypeFor(typeof(InterfaceWithMethods))); }
private HashSet <string> GetAddressesForMessageType(Type messageType) { HashSet <string> addresses = null; if (staticRoutes.TryGetValue(messageType, out addresses)) { return(addresses); } if (!messageType.IsInterface) { var interfaces = messageType.GetInterfaces(); foreach (var _interface in interfaces) { if (staticRoutes.TryGetValue(_interface, out addresses)) { return(addresses); } } var t = MessageMapper.GetMappedTypeFor(messageType); if (t != null && t != messageType) { return(GetAddressesForMessageType(t)); } } return(addresses); }
public void Interfaces_with_inheritance_and_property_overload_should_be_mapped() { var mapper = new MessageMapper(); var genericInterfaceType = typeof(InterfaceWithGenericProperty <ISpecific>); mapper.Initialize(new[] { genericInterfaceType }); Assert.NotNull(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 Class_abstract_with_only_properties_should_be_mapped() { var mapper = new MessageMapper(); var abstractClassType = typeof(SimpleAbstractClass); mapper.Initialize(new[] { abstractClassType }); Assert.NotNull(mapper.GetMappedTypeFor(abstractClassType)); }
public void Class_abstract_with_methods_should_not_be_mapped() { var mapper = new MessageMapper(); var abstractClassType = typeof(SimpleAbstractClassWithMethods); mapper.Initialize(new[] { abstractClassType }); Assert.Null(mapper.GetMappedTypeFor(abstractClassType)); }
public void Should_map_structs() { var mapper = new MessageMapper(); var mappedType = mapper.GetMappedTypeFor(typeof(SampleMessageStruct)); Assert.AreEqual(typeof(SampleMessageStruct), mappedType); }
public void Class_concrete_generic_with_only_properties_generic_should_be_mapped() { var mapper = new MessageMapper(); var abstractClassType = typeof(GenericCommand <Data>); mapper.Initialize(new[] { abstractClassType }); Assert.NotNull(mapper.GetMappedTypeFor(abstractClassType)); }
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 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 void Interfaces_with_only_properties_should_be_mapped() { var mapper = new MessageMapper(); mapper.Initialize(new[] { typeof(IInterfaceWithOnlyProperties) }); Assert.NotNull(mapper.GetMappedTypeFor(typeof(IInterfaceWithOnlyProperties))); }
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 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))); }
string SerializeEnclosedMessageTypes(IEnumerable <object> messages) { var types = messages.Select(m => MessageMapper.GetMappedTypeFor(m.GetType())).ToList(); var interfaces = types.SelectMany(t => t.GetInterfaces()) .Where(MessageConventionExtensions.IsMessageType); var distinctTypes = types.Distinct(); var interfacesOrderedByHierarchy = interfaces.Distinct().OrderByDescending(i => i.GetInterfaces().Count()); // Interfaces with less interfaces are lower in the hierarchy. return(string.Join(";", distinctTypes.Concat(interfacesOrderedByHierarchy).Select(t => t.AssemblyQualifiedName))); }
public List <LogicalMessage> CreateMultiple(IEnumerable <object> messages) { if (messages == null) { return(new List <LogicalMessage>()); } return(messages.Select(m => { var messageType = MessageMapper.GetMappedTypeFor(m.GetType()); var headers = GetMessageHeaders(m); return new LogicalMessage(MessageMetadataRegistry.GetMessageDefinition(messageType), m, headers, this); }).ToList()); }
public void Invoke(BehaviorContext context, Action next) { var logicalMessages = new LogicalMessages(); context.Set(logicalMessages); if (SkipDeserialization || UnicastBus.SkipDeserialization) { return; } var transportMessage = context.TransportMessage; object[] rawMessages; try { rawMessages = Extract(transportMessage); } catch (Exception exception) { throw new SerializationException(string.Format("An error occurred while attempting to extract logical messages from transport message {0}", transportMessage), exception); } if (!transportMessage.IsControlMessage() && !rawMessages.Any()) { log.Warn("Received an empty message - ignoring."); return; } foreach (var rawMessage in rawMessages) { var messageType = MessageMapper.GetMappedTypeFor(rawMessage.GetType()); logicalMessages.Add(new LogicalMessage(messageType, rawMessage)); } next(); }
/// <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); }
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)); }
/// <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 LogicalMessage Create(Type messageType, object message, Dictionary <string, string> headers) { var realMessageType = MessageMapper.GetMappedTypeFor(messageType); return(new LogicalMessage(MessageMetadataRegistry.GetMessageDefinition(realMessageType), message, headers, this)); }
Type GetMessageType(object message) { var messageType = message.GetType(); return(MessageMapper.GetMappedTypeFor(messageType)); }