/// <summary> /// Private caller, used for recurrence /// </summary> /// <param name="messageData">Stream where data is stored</param> /// <param name="dataClass">Poco data class implementation</param> /// <returns>Implementation of a POCO data class with it's properties filled if there's not a version mismatch</returns> private static object PrivDeserialize(Stream messageData, object dataClass) { var properties = BaseSerializer.GetCachedProperties(dataClass.GetType()); //We use the FastMember as it's faster than reflection var accessor = BaseSerializer.GetCachedTypeAccessor(dataClass.GetType()); try { foreach (var prop in properties) { var value = GetValue(messageData, prop.PropertyType); if (prop.CanWrite) //Property with a setter { accessor[dataClass, prop.Name] = value; } else { if (!prop.CanWrite && !Equals(value, accessor[dataClass, prop.Name])) { throw new Exception("Property without a setter where it's value mismatch"); } } } } catch (Exception e) { throw new Exception($"Cannot deserialize this message with the bytes provided: {e}"); } return(dataClass); }
/// <summary> /// Private accessor for recurrence /// </summary> /// <param name="data">Message data implementation</param> /// <param name="messageData">Stream to write the bytes to</param> /// <param name="recursive">True if you call this from recursively and want to keep the stream open</param> /// <returns>Serialized array of bytes</returns> private static byte[] PrivSerialize(object data, Stream messageData, bool recursive = false) { if (!recursive) { messageData = new MemoryStream(); } var properties = BaseSerializer.GetCachedProperties(data.GetType()); //We use the FastMember as it's faster than reflection var accessor = BaseSerializer.GetCachedTypeAccessor(data.GetType()); //First write the version! if (!recursive) { WriteValue(messageData, typeof(string), accessor[data, "Version"]); } //Then write the other properties... foreach (var prop in properties) { WriteValue(messageData, prop.PropertyType, accessor[data, prop.Name]); } var array = ((MemoryStream)messageData).ToArray(); if (!recursive) { messageData.Dispose(); } return(array); }