private int CreateHeader()
{
string contentType;
if (_message is Stream)
{
_bodyStream = (Stream) _message;
contentType = "stream";
}
else if (_message is byte[])
{
var buffer = (byte[]) _message;
_bodyStream = new MemoryStream(buffer);
_bodyStream.SetLength(buffer.Length);
contentType = "byte[]";
}
else
{
_bodyStream = _internalStream;
_serializer.Serialize(_message, _bodyStream, out contentType);
if (contentType == null)
contentType = _message.GetType().AssemblyQualifiedName;
if (contentType.Length > byte.MaxValue)
throw new InvalidOperationException(
"The AssemblyQualifiedName (type name) may not be larger than 255 characters. Your type: " +
_message.GetType().AssemblyQualifiedName);
}
var sliceOffset = _bufferSlice.Offset;
var sliceBuffer = _bufferSlice.Buffer;
_bodyStream.Position = 0;
_headerSize = FixedHeaderLength + contentType.Length;
BitConverter2.GetBytes((ushort) _headerSize, sliceBuffer, sliceOffset);
_bufferSlice.Buffer[sliceOffset + 2] = Version;
BitConverter2.GetBytes((int) _bodyStream.Length, sliceBuffer, sliceOffset + 2 + 1);
BitConverter2.GetBytes((byte) contentType.Length, sliceBuffer, sliceOffset + 2 + 1 + 4);
Encoding.UTF8.GetBytes(contentType, 0, contentType.Length, sliceBuffer, sliceOffset + 2 + 1 + 4 + 1);
// the header length field is not included in _headerSize as it's a header prefix.
// hence the +2
return _headerSize + 2;
}
}