public static IDictionary<string, object> Demarshal(byte[] data)
{
// Cannot be empty
if (data.Length == 0)
throw new InvalidDataException(string.Format("Empty message provided, invalid format."));
using (BinaryReader br = new BinaryReader(new MemoryStream(data, false), Encoding.Unicode))
{
// For now we support only the one message version
byte messageFormatVersion = br.ReadByte();
if (messageFormatVersion != CurrentMessageFormatVersion)
throw new InvalidDataException(string.Format("Message format: {0} is not support (library version: {1})", messageFormatVersion, CurrentMessageFormatVersion));
// Create a dict for the message contents
Dictionary<string, object> messageDict = new Dictionary<string, object>();
while (br.BaseStream.Position < br.BaseStream.Length)
{
string propertyName = br.ReadString();
DataType propertyType = (DataType)br.ReadByte();
switch (propertyType)
{
case DataType.Boolean:
messageDict.Add(propertyName, br.ReadBoolean());
break;
case DataType.Byte:
messageDict.Add(propertyName, br.ReadByte());
break;
case DataType.Integer:
messageDict.Add(propertyName, br.ReadInt32());
break;
case DataType.String:
messageDict.Add(propertyName, br.ReadString());
break;
case DataType.EmptyString:
messageDict.Add(propertyName, (string) null);
break;
default:
throw new InvalidDataException(string.Format("Message includes unknown data type: {0} for property: {1}", propertyType, propertyName));
}
}
return messageDict;
}
}