public override void Serialize(
BsonWriter bsonWriter,
Type nominalType,
object value,
IBsonSerializationOptions options)
{
if (value == null)
{
throw new ArgumentNullException("value");
}
// could get here with a BsonDocumentWrapper from BsonValueSerializer switch statement
var wrapper = value as BsonDocumentWrapper;
if (wrapper != null)
{
BsonDocumentWrapperSerializer.Instance.Serialize(bsonWriter, nominalType, value, null);
return;
}
var rawBsonDocument = value as RawBsonDocument;
if (rawBsonDocument != null)
{
RawBsonDocumentSerializer.Instance.Serialize(bsonWriter, nominalType, value, options);
return;
}
var bsonDocument = (BsonDocument)value;
var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions;
if (documentSerializationOptions == null)
{
var message = string.Format(
"Serialize method of BsonDocument expected serialization options of type {0}, not {1}.",
BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)),
BsonUtils.GetFriendlyTypeName(options.GetType()));
throw new BsonSerializationException(message);
}
bsonWriter.WriteStartDocument();
BsonElement idElement = null;
if (documentSerializationOptions.SerializeIdFirst && bsonDocument.TryGetElement("_id", out idElement))
{
bsonWriter.WriteName(idElement.Name);
BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), idElement.Value, null);
}
foreach (var element in bsonDocument)
{
// if serializeIdFirst is false then idElement will be null and no elements will be skipped
if (!object.ReferenceEquals(element, idElement))
{
bsonWriter.WriteName(element.Name);
BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), element.Value, null);
}
}
bsonWriter.WriteEndDocument();
}