/// <summary> /// Writes an object to the message's body. First applies the base formatter, then compresses. /// </summary> /// <param name="message">The message to be written to</param> /// <param name="obj">The message to write</param> public void Write(Message message, object obj) { Message clearMessage = new Message(); m_BaseFormatter.Write(clearMessage, obj); message.BodyType = clearMessage.BodyType; // In case the original body length is less than 1 kilobyte - don't compress it long uncompressedBodyLength = clearMessage.BodyStream.Length; if (uncompressedBodyLength <= 1024) { message.BodyStream = clearMessage.BodyStream; message.BodyStream.Position = 0; return; } MemoryStream compressedBodyMemoryStream = new MemoryStream(); using (DeflateStream compressor = new DeflateStream(compressedBodyMemoryStream, CompressionMode.Compress, true)) { MessageHeader messageHeader = new MessageHeader(uncompressedBodyLength); messageHeader.CopyTo(compressedBodyMemoryStream); // Header goes uncompressed! clearMessage.BodyStream.Position = 0; clearMessage.BodyStream.CopyTo(compressor); } long compressedBodyLength = compressedBodyMemoryStream.Length; if (compressedBodyLength < uncompressedBodyLength) { message.BodyStream = compressedBodyMemoryStream; message.BodyStream.Position = 0; } else { message.BodyStream = clearMessage.BodyStream; message.BodyStream.Position = 0; } }