/// <summary>
/// Serializes a value.
/// </summary>
/// <param name="context">The serialization context.</param>
/// <param name="args">The serialization args.</param>
/// <param name="value">The object.</param>
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value)
{
var bsonWriter = context.Writer;
if (value == null)
{
bsonWriter.WriteNull();
}
else
{
var actualType = value.GetType();
if (actualType == typeof(object))
{
bsonWriter.WriteStartDocument();
bsonWriter.WriteEndDocument();
}
else
{
// certain types can be written directly as BSON value
// if we're not at the top level document, or if we're using the JsonWriter
if (bsonWriter.State == BsonWriterState.Value || bsonWriter is JsonWriter)
{
switch (Type.GetTypeCode(actualType))
{
case TypeCode.Boolean:
bsonWriter.WriteBoolean((bool)value);
return;
case TypeCode.DateTime:
// TODO: is this right? will lose precision after round trip
var bsonDateTime = new BsonDateTime(BsonUtils.ToUniversalTime((DateTime)value));
bsonWriter.WriteDateTime(bsonDateTime.MillisecondsSinceEpoch);
return;
case TypeCode.Double:
bsonWriter.WriteDouble((double)value);
return;
case TypeCode.Int16:
// TODO: is this right? will change type to Int32 after round trip
bsonWriter.WriteInt32((short)value);
return;
case TypeCode.Int32:
bsonWriter.WriteInt32((int)value);
return;
case TypeCode.Int64:
bsonWriter.WriteInt64((long)value);
return;
case TypeCode.Object:
if (actualType == typeof(Decimal128))
{
var decimal128 = (Decimal128)value;
bsonWriter.WriteDecimal128(decimal128);
return;
}
if (actualType == typeof(Guid))
{
var guid = (Guid)value;
#pragma warning disable 618
if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2 && _guidRepresentation == GuidRepresentation.Unspecified)
{
var guidRepresentation = bsonWriter.Settings.GuidRepresentation;
var binaryData = new BsonBinaryData(guid, guidRepresentation);
bsonWriter.WriteBinaryData(binaryData);
}
else
{
_guidSerializer.Serialize(context, args, guid);
}
#pragma warning restore 618
return;
}
if (actualType == typeof(ObjectId))
{
bsonWriter.WriteObjectId((ObjectId)value);
return;
}
break;
case TypeCode.String:
bsonWriter.WriteString((string)value);
return;
}
}
SerializeDiscriminatedValue(context, args, value, actualType);
}
}
}