public override object Deserialize(
BsonReader bsonReader,
Type nominalType,
Type actualType,
IBsonSerializationOptions options)
{
VerifyTypes(nominalType, actualType, typeof(Guid));
var bsonType = bsonReader.GetCurrentBsonType();
string message;
switch (bsonType)
{
case BsonType.Binary:
var binaryData = bsonReader.ReadBinaryData();
var bytes = binaryData.Bytes;
var subType = binaryData.SubType;
var guidRepresentation = binaryData.GuidRepresentation;
if (bytes.Length != 16)
{
message = string.Format("Expected length to be 16, not {0}.", bytes.Length);
throw new Exception(message);
}
if (subType != BsonBinarySubType.UuidStandard && subType != BsonBinarySubType.UuidLegacy)
{
message = string.Format("Expected binary sub type to be UuidStandard or UuidLegacy, not {0}.", subType);
throw new Exception(message);
}
if (guidRepresentation == GuidRepresentation.Unspecified)
{
throw new BsonSerializationException("GuidSerializer cannot deserialize a Guid when GuidRepresentation is Unspecified.");
}
return GuidConverter.FromBytes(bytes, guidRepresentation);
case BsonType.String:
return new Guid(bsonReader.ReadString());
default:
message = string.Format("Cannot deserialize Guid from BsonType {0}.", bsonType);
throw new Exception(message);
}
}