public static byte[] Marshal(IDictionary<string, object> message)
{
using (MemoryStream memory = new MemoryStream())
{
BinaryWriter writer = new BinaryWriter(memory, Encoding.Unicode);
// Write the version
writer.Write(CurrentMessageFormatVersion);
// Now we just iterate properties and write them out
foreach (KeyValuePair<string, object> property in message)
{
writer.Write(property.Key);
// Null values are treated as empty strings
if (property.Value == null)
{
writer.Write((byte)DataType.EmptyString);
continue;
}
System.Type propType = property.Value.GetType();
if (propType == typeof(int))
{
writer.Write((byte) DataType.Integer);
writer.Write((int)property.Value);
}
else if (propType == typeof(byte))
{
writer.Write((byte)DataType.Byte);
writer.Write((byte)property.Value);
}
else if (propType == typeof(bool))
{
writer.Write((byte)DataType.Boolean);
writer.Write((bool)property.Value);
}
else if(propType == typeof(Enum))
{
writer.Write((byte)DataType.Byte);
writer.Write((byte)property.Value);
}
else
{
// Not one of the former, you're string value it is then!
writer.Write((byte)DataType.String);
writer.Write(property.Value.ToString());
}
}
// Provide our caller a copy in byte[] format
return memory.ToArray();
}
}