/// <summary> /// Encodes the specified message header and body. /// </summary> /// <typeparam name="T">The type of the message.</typeparam> /// <param name="body">The message body.</param> /// <param name="header">The message header.</param> /// <param name="compression">The compression type.</param> /// <returns>The encoded byte array containing the message data.</returns> public static byte[] Encode <T>(this T body, IMessageHeader header, string compression) where T : ISpecificRecord { using (var stream = new MemoryStream()) { // create avro binary encoder to write to memory stream var headerEncoder = new BinaryEncoder(stream); var bodyEncoder = headerEncoder; Stream gzip = null; try { // compress message body if compression has been negotiated if (header.CanCompressMessageBody()) { if (GzipEncoding.Equals(compression, StringComparison.InvariantCultureIgnoreCase)) { // add Compressed flag to message flags before writing header header.SetBodyCompressed(); gzip = new GZipStream(stream, CompressionMode.Compress, true); bodyEncoder = new BinaryEncoder(gzip); } } // serialize header var headerWriter = new SpecificWriter <IMessageHeader>(header.Schema); headerWriter.Write(header, headerEncoder); // serialize body var bodyWriter = new SpecificWriter <T>(body.Schema); bodyWriter.Write(body, bodyEncoder); } finally { gzip?.Dispose(); } return(stream.ToArray()); } }