/// <summary> /// Serializes the message to a pooled <see cref="MemoryStream"/>. Be sure to /// add the stream returned back to the <see cref="MemoryStreamPool"/> when you've /// finished with it. /// </summary> /// <param name="ignoreTypeCode">Optionally ignore unspecified message types (used for unit testing).</param> /// <returns>A <see cref="MemoryStream"/> holding the serialized message.</returns> public MemoryStream SerializeAsStream(bool ignoreTypeCode = false) { if (!ignoreTypeCode && Type == InternalMessageTypes.Unspecified) { throw new ArgumentException($"Message type [{this.GetType().FullName}] has not initialized its [{nameof(Type)}] property.", nameof(ProxyMessage)); } var output = MemoryStreamPool.Alloc(); try { using (var writer = new BinaryWriter(output, Encoding.UTF8, leaveOpen: true)) { writer.Write((int)Type); // Write the properties. writer.Write(Properties.Count); foreach (var property in Properties) { WriteString(writer, property.Key); WriteString(writer, property.Value); } // Write the attachments. writer.Write(Attachments.Count); foreach (var attachment in Attachments) { if (attachment == null) { writer.Write(-1); } else { writer.Write(attachment.Length); writer.Write(attachment); } } } // Rewind the stream. output.Position = 0; } catch { MemoryStreamPool.Free(output); throw; } return(output); }
/// <summary> /// <para> /// Serializes the message to bytes. /// </para> /// <note> /// This method is intended for testing purposes. Use <see cref="SerializeAsStream(bool)"/> /// for production since that method will perform better by not needing to allocate a /// byte array with the message contents for every call. /// </note> /// </summary> /// <param name="ignoreTypeCode">Optionally ignore unspecified message types (used for unit testing).</param> /// <returns>The serialized byte array.</returns> public byte[] SerializeAsBytes(bool ignoreTypeCode = false) { if (!ignoreTypeCode && Type == InternalMessageTypes.Unspecified) { throw new ArgumentException($"Message type [{this.GetType().FullName}] has not initialized its [{nameof(Type)}] property.", nameof(ProxyMessage)); } var output = SerializeAsStream(ignoreTypeCode); try { return(output.ToArray()); } finally { MemoryStreamPool.Free(output); } }