public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var method = (MethodInfo)value; bsonWriter.WriteStartDocument(); bsonWriter.WriteName("Type"); bsonWriter.WriteString(method.DeclaringType.AssemblyQualifiedName); bsonWriter.WriteName("Method"); bsonWriter.WriteString(GetMethodSignature(method)); bsonWriter.WriteEndDocument(); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { IDictionary<string, object> obj = value as IDictionary<string, object>; if (obj == null) { bsonWriter.WriteNull(); return; } bsonWriter.WriteStartDocument(); foreach (var member in obj) { bsonWriter.WriteName(member.Key); object memberValue = member.Value; if (memberValue == null) { bsonWriter.WriteNull(); } else { nominalType = memberValue.GetType(); var serializer = BsonSerializer.LookupSerializer(nominalType); serializer.Serialize(bsonWriter, nominalType, memberValue, options); } } bsonWriter.WriteEndDocument(); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); return; } var metaObject = ((IDynamicMetaObjectProvider)value).GetMetaObject(Expression.Constant(value)); var memberNames = metaObject.GetDynamicMemberNames().ToList(); if (memberNames.Count == 0) { bsonWriter.WriteNull(); return; } bsonWriter.WriteStartDocument(); foreach (var memberName in memberNames) { bsonWriter.WriteName(memberName); var memberValue = BinderHelper.GetMemberValue(value, memberName); if (memberValue == null) bsonWriter.WriteNull(); else { var memberType = memberValue.GetType(); var serializer = BsonSerializer.LookupSerializer(memberType); serializer.Serialize(bsonWriter, memberType, memberValue, options); } } bsonWriter.WriteEndDocument(); }
protected void WriteNullableDouble(BsonWriter writer,string name,double? value) { writer.WriteName(name); if ( value != null ) { writer.WriteDouble(value.Value); } else { writer.WriteNull(); } }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options ) { var dictionary = (DynamicDictionary)value; bsonWriter.WriteStartDocument(); bsonWriter.WriteString( "_t", "DynamicDictionary" ); if( dictionary != null ) { foreach( var entry in dictionary ) { bsonWriter.WriteName( entry.Key.Replace( '.', '\x03' ) ); BsonSerializer.Serialize( bsonWriter, typeof( object ), entry.Value ); } } bsonWriter.WriteEndDocument(); }
private void SerializeExtraElements(BsonWriter bsonWriter, object obj, BsonMemberMap extraElementsMemberMap) { var extraElements = extraElementsMemberMap.Getter(obj); if (extraElements != null) { if (extraElementsMemberMap.MemberType == typeof(BsonDocument)) { var bsonDocument = (BsonDocument)extraElements; foreach (var element in bsonDocument) { bsonWriter.WriteName(element.Name); BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), element.Value, null); } } else { var dictionary = (IDictionary<string, object>)extraElements; foreach (var key in dictionary.Keys) { bsonWriter.WriteName(key); var value = dictionary[key]; if (value == null) { bsonWriter.WriteNull(); } else { var bsonValue = BsonTypeMapper.MapToBsonValue(dictionary[key]); BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), bsonValue, null); } } } } }
private void SerializeMember(BsonWriter bsonWriter, object obj, BsonMemberMap memberMap) { var value = memberMap.Getter(obj); if (!memberMap.ShouldSerialize(obj, value)) { return; // don't serialize member } bsonWriter.WriteName(memberMap.ElementName); var nominalType = memberMap.MemberType; if (value == null && nominalType.IsInterface) { bsonWriter.WriteNull(); } else if (value == null && memberMap.MemberTypeIsBsonValue) { bsonWriter.WriteStartDocument(); bsonWriter.WriteBoolean("_csharpnull", true); bsonWriter.WriteEndDocument(); } else { var actualType = (value == null) ? nominalType : value.GetType(); var serializer = memberMap.GetSerializer(actualType); serializer.Serialize(bsonWriter, nominalType, value, memberMap.SerializationOptions); } }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, bool serializeIdFirst ) { if (value == null) { bsonWriter.WriteNull(); } else { bsonWriter.WriteStartArray(); int index = 0; foreach (var element in (IEnumerable) value) { bsonWriter.WriteName(index.ToString()); BsonSerializer.Serialize(bsonWriter, typeof(object), element); index++; } bsonWriter.WriteEndArray(); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { // Nullable types are weird because they get boxed as their underlying value type // we can best handle that by switching the nominalType to the underlying value type // (so VerifyNominalType doesn't fail and we don't get an unnecessary discriminator) if (nominalType.IsGenericType && nominalType.GetGenericTypeDefinition() == typeof(Nullable<>)) { nominalType = nominalType.GetGenericArguments()[0]; } VerifyNominalType(nominalType); var actualType = (value == null) ? nominalType : value.GetType(); if (actualType != _classMap.ClassType) { var message = string.Format("BsonClassMapSerializer.Serialize for type {0} was called with actualType {1}.", BsonUtils.GetFriendlyTypeName(_classMap.ClassType), BsonUtils.GetFriendlyTypeName(actualType)); throw new BsonSerializationException(message); } var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions; if (documentSerializationOptions == null) { var message = string.Format( "Serializer BsonClassMapSerializer expected serialization options of type {0}, not {1}.", BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)), BsonUtils.GetFriendlyTypeName(options.GetType())); throw new BsonSerializationException(message); } bsonWriter.WriteStartDocument(); BsonMemberMap idMemberMap = null; if (documentSerializationOptions.SerializeIdFirst) { idMemberMap = _classMap.IdMemberMap; if (idMemberMap != null) { SerializeMember(bsonWriter, value, idMemberMap); } } if (actualType != nominalType || _classMap.DiscriminatorIsRequired || _classMap.HasRootClass) { // never write out a discriminator for an anonymous class if (!_classMap.IsAnonymous) { var discriminatorConvention = _classMap.GetDiscriminatorConvention(); var discriminator = discriminatorConvention.GetDiscriminator(nominalType, actualType); if (discriminator != null) { bsonWriter.WriteName(discriminatorConvention.ElementName); BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), discriminator, null); } } } var allMemberMaps = _classMap.AllMemberMaps; var extraElementsMemberMapIndex = _classMap.ExtraElementsMemberMapIndex; for (var memberMapIndex = 0; memberMapIndex < allMemberMaps.Count; ++memberMapIndex) { var memberMap = allMemberMaps[memberMapIndex]; // note: if serializeIdFirst is false then idMemberMap will be null (so no property will be skipped) if (memberMap != idMemberMap) { if (memberMapIndex != extraElementsMemberMapIndex) { SerializeMember(bsonWriter, value, memberMap); } else { SerializeExtraElements(bsonWriter, value, memberMap); } } } bsonWriter.WriteEndDocument(); } }
private void SerializeMember(BsonWriter bsonWriter, object obj, BsonMemberMap memberMap) { var value = memberMap.Getter(obj); if (!memberMap.ShouldSerialize(obj, value)) { return; // don't serialize member } bsonWriter.WriteName(memberMap.ElementName); var nominalType = memberMap.MemberType; var actualType = (value == null) ? nominalType : value.GetType(); var serializer = memberMap.GetSerializer(actualType); serializer.Serialize(bsonWriter, nominalType, value, memberMap.SerializationOptions); }
protected override void OnSerialized(BsonWriter bsonWriter, object value, IBsonSerializationOptions options) { if (_migrations.Any()) { bsonWriter.WriteName(VERSION_ELEMENT_NAME); var currentVersion = _versionDetectionStrategy.GetCurrentVersion(); _versionSerializer.Serialize(bsonWriter, typeof(Version), currentVersion, null); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options ) { if (value == null) { bsonWriter.WriteNull(); } else { var dictionary = (IDictionary) value; var representationOptions = options as RepresentationSerializationOptions; BsonType representation; if (representationOptions == null) { representation = BsonType.Document; foreach (object key in dictionary.Keys) { var name = key as string; // check for null and type string at the same time if (name == null || name.StartsWith("$") || name.Contains(".")) { representation = BsonType.Array; break; } } } else { representation = representationOptions.Representation; } switch (representation) { case BsonType.Document: bsonWriter.WriteStartDocument(); foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteName((string) entry.Key); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value); } bsonWriter.WriteEndDocument(); break; case BsonType.Array: bsonWriter.WriteStartArray(); foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteStartArray(); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Key); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value); bsonWriter.WriteEndArray(); } bsonWriter.WriteEndArray(); break; default: var message = string.Format("'{0}' is not a valid representation for type IDictionary.", representation); throw new BsonSerializationException(message); } } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> 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 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(); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var dictionary = (IDictionary)value; if (nominalType == typeof(object)) { var actualType = value.GetType(); bsonWriter.WriteStartDocument(); bsonWriter.WriteString("_t", BsonClassMap.GetTypeNameDiscriminator(actualType)); bsonWriter.WriteName("_v"); Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType bsonWriter.WriteEndDocument(); return; } var dictionaryOptions = options as DictionarySerializationOptions; if (dictionaryOptions == null) { // support RepresentationSerializationOptions for backward compatibility var representationOptions = options as RepresentationSerializationOptions; if (representationOptions != null) { switch (representationOptions.Representation) { case BsonType.Array: dictionaryOptions = DictionarySerializationOptions.ArrayOfArrays; break; case BsonType.Document: dictionaryOptions = DictionarySerializationOptions.Document; break; default: var message = string.Format("BsonType {0} is not a valid representation for a Dictionary.", representationOptions.Representation); throw new BsonSerializationException(message); } } if (dictionaryOptions == null) { dictionaryOptions = DictionarySerializationOptions.Defaults; } } var representation = dictionaryOptions.Representation; if (representation == DictionaryRepresentation.Dynamic) { representation = DictionaryRepresentation.Document; foreach (object key in dictionary.Keys) { var name = key as string; // check for null and type string at the same time if (name == null || name.StartsWith("$") || name.Contains(".")) { representation = DictionaryRepresentation.ArrayOfArrays; break; } } } switch (representation) { case DictionaryRepresentation.Document: bsonWriter.WriteStartDocument(); foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteName((string)entry.Key); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value); } bsonWriter.WriteEndDocument(); break; case DictionaryRepresentation.ArrayOfArrays: bsonWriter.WriteStartArray(); foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteStartArray(); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Key); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value); bsonWriter.WriteEndArray(); } bsonWriter.WriteEndArray(); break; case DictionaryRepresentation.ArrayOfDocuments: bsonWriter.WriteStartArray(); foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteStartDocument(); bsonWriter.WriteName("k"); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Key); bsonWriter.WriteName("v"); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value); bsonWriter.WriteEndDocument(); } bsonWriter.WriteEndArray(); break; default: var message = string.Format("'{0}' is not a valid representation for type IDictionary.", representation); throw new BsonSerializationException(message); } } }
void IBsonSerializable.Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options) { bsonWriter.WriteStartDocument(); bsonWriter.WriteString("$ref", _collectionName); bsonWriter.WriteName("$id"); _id.WriteTo(bsonWriter); if (_databaseName != null) { bsonWriter.WriteString("$db", _databaseName); } bsonWriter.WriteEndDocument(); }
private void SerializeMember( BsonWriter bsonWriter, object obj, BsonMemberMap memberMap ) { var value = memberMap.Getter(obj); if (value == null && memberMap.IgnoreIfNull) { return; // don't serialize null value } if (memberMap.HasDefaultValue && !memberMap.SerializeDefaultValue && object.Equals(value, memberMap.DefaultValue)) { return; // don't serialize default value } if (!memberMap.ShouldSerializeMethod(obj)) { return; // the ShouldSerializeMethod determined that the member shouldn't be serialized } bsonWriter.WriteName(memberMap.ElementName); var nominalType = memberMap.MemberType; var actualType = (value == null) ? nominalType : value.GetType(); var serializer = memberMap.GetSerializer(actualType); serializer.Serialize(bsonWriter, nominalType, value, memberMap.SerializationOptions); }
private void SerializeMember( BsonWriter bsonWriter, object obj, BsonMemberMap memberMap ) { var value = memberMap.Getter(obj); if (value == null && memberMap.IgnoreIfNull) { return; // don't serialize null value } if (memberMap.HasDefaultValue && !memberMap.SerializeDefaultValue && value.Equals(memberMap.DefaultValue)) { return; // don't serialize default value } var nominalType = memberMap.MemberType; var actualType = (value == null) ? nominalType : value.GetType(); var serializer = memberMap.GetSerializerForActualType(actualType); var elementName = memberMap.ElementName; bsonWriter.WriteName(elementName); serializer.Serialize(bsonWriter, nominalType, value, memberMap.SerializationOptions); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { if (nominalType == typeof(object)) { var actualType = value.GetType(); bsonWriter.WriteStartDocument(); bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType)); bsonWriter.WriteName("_v"); Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType bsonWriter.WriteEndDocument(); return; } var dictionary = (IDictionary)value; var dictionarySerializationOptions = EnsureSerializationOptions(options); var representation = dictionarySerializationOptions.Representation; var itemSerializationOptions = dictionarySerializationOptions.ItemSerializationOptions; if (representation == DictionaryRepresentation.Dynamic) { representation = DictionaryRepresentation.Document; foreach (object key in dictionary.Keys) { var name = key as string; // check for null and type string at the same time if (name == null || name[0] == '$' || name.IndexOf('.') != -1) { representation = DictionaryRepresentation.ArrayOfArrays; break; } } } switch (representation) { case DictionaryRepresentation.Document: bsonWriter.WriteStartDocument(); foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteName((string)entry.Key); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value, itemSerializationOptions); } bsonWriter.WriteEndDocument(); break; case DictionaryRepresentation.ArrayOfArrays: bsonWriter.WriteStartArray(); foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteStartArray(); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Key, null); // no serialization options for key BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value, itemSerializationOptions); bsonWriter.WriteEndArray(); } bsonWriter.WriteEndArray(); break; case DictionaryRepresentation.ArrayOfDocuments: bsonWriter.WriteStartArray(); foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteStartDocument(); bsonWriter.WriteName("k"); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Key, null); // no serialization options for key bsonWriter.WriteName("v"); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value, itemSerializationOptions); bsonWriter.WriteEndDocument(); } bsonWriter.WriteEndArray(); break; default: var message = string.Format("'{0}' is not a valid IDictionary representation.", representation); throw new BsonSerializationException(message); } } }
//private KeyValuePair<string, string> DeserializeNameValue(BsonReader bsonReader) //{ // string key = null; // string value = null; // var bsonType = bsonReader.GetCurrentBsonType(); // if (bsonType == BsonType.Array) // { // // [["toto1", "tata1"], ["toto2", "tata2"]] // bsonReader.ReadStartArray(); // //bsonReader.ReadBsonType(); // //var keyType = keyDiscriminatorConvention.GetActualType(bsonReader, typeof(TKey)); // //var keySerializer = GetKeySerializer(keyType); // //key = (TKey)keySerializer.Deserialize(bsonReader, typeof(TKey), keyType, keyValuePairSerializationOptions.KeySerializationOptions); // //bsonReader.ReadBsonType(); // //var valueType = valueDiscriminatorConvention.GetActualType(bsonReader, typeof(TValue)); // //var valueSerializer = GetValueSerializer(valueType); // //value = (TValue)valueSerializer.Deserialize(bsonReader, typeof(TValue), valueType, keyValuePairSerializationOptions.ValueSerializationOptions); // key = bsonReader.ReadString(); // value = bsonReader.ReadString(); // bsonReader.ReadEndArray(); // } // else if (bsonType == BsonType.Document) // { // // [{ "k" : "toto1", "v" : "tata1" }, { "k" : "toto2", "v" : "tata2" }] // bsonReader.ReadStartDocument(); // var bsonTrie = new BsonTrie<bool>(); // bsonTrie.Add("k", true); // is key // bsonTrie.Add("v", false); // bool keyFound = false, valueFound = false; // bool elementFound; // bool elementIsKey; // while (bsonReader.ReadBsonType(bsonTrie, out elementFound, out elementIsKey) != BsonType.EndOfDocument) // { // var name = bsonReader.ReadName(); // if (elementFound) // { // if (elementIsKey) // { // //var keyType = keyDiscriminatorConvention.GetActualType(bsonReader, typeof(TKey)); // //var keySerializer = GetValueSerializer(keyType); // //key = (TKey)keySerializer.Deserialize(bsonReader, typeof(TKey), keyType, keyValuePairSerializationOptions.KeySerializationOptions); // key = bsonReader.ReadString(); // keyFound = true; // } // else // { // //var valueType = valueDiscriminatorConvention.GetActualType(bsonReader, typeof(TValue)); // //var valueSerializer = GetValueSerializer(valueType); // //value = (TValue)valueSerializer.Deserialize(bsonReader, typeof(TValue), valueType, keyValuePairSerializationOptions.ValueSerializationOptions); // value = bsonReader.ReadString(); // valueFound = true; // } // } // else // { // var message = string.Format("Element '{0}' is not valid for KeyValuePairs (expecting 'k' or 'v').", name); // throw new BsonSerializationException(message); // } // } // bsonReader.ReadEndDocument(); // if (!keyFound) // { // //throw new FileFormatException("KeyValuePair item was missing the 'k' element."); // throw new PBException("KeyValuePair item was missing the 'k' element."); // } // if (!valueFound) // { // //throw new FileFormatException("KeyValuePair item was missing the 'v' element."); // throw new PBException("KeyValuePair item was missing the 'v' element."); // } // } // else // { // //var message = string.Format("Cannot deserialize '{0}' from BsonType {1}.", BsonUtils.GetFriendlyTypeName(typeof(KeyValuePair<string, string>)), bsonType); // //throw new FileFormatException(message); // throw new PBException("Cannot deserialize '{0}' from BsonType {1}.", BsonUtils.GetFriendlyTypeName(typeof(KeyValuePair<string, string>)), bsonType); // } // return new KeyValuePair<string, string>(key, value); //} /// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (_trace) pb.Trace.WriteLine("NameValueCollectionSerializer.Serialize()"); if (value == null) { bsonWriter.WriteNull(); } else { // dont know why nominalType can be an object if (nominalType == typeof(object)) { var actualType = value.GetType(); bsonWriter.WriteStartDocument(); bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType)); bsonWriter.WriteName("_v"); Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType bsonWriter.WriteEndDocument(); return; } // json Dictionary // { "toto1" : "tata1", "toto2" : "tata2" } //var dictionary = (IDictionary)value; NameValueCollection nameValueCollection = (NameValueCollection)value; var dictionarySerializationOptions = EnsureSerializationOptions(options); var dictionaryRepresentation = dictionarySerializationOptions.Representation; var keyValuePairSerializationOptions = dictionarySerializationOptions.KeyValuePairSerializationOptions; if (dictionaryRepresentation == DictionaryRepresentation.Dynamic) { // if some keys contain '$', '.' or '\0' serialize as ArrayOfArrays otherwise serialize as Document dictionaryRepresentation = DictionaryRepresentation.Document; foreach (string key in nameValueCollection.Keys) { //var name = key as string; // key might not be a string if (string.IsNullOrEmpty(key) || key[0] == '$' || key.IndexOf('.') != -1 || key.IndexOf('\0') != -1) { dictionaryRepresentation = DictionaryRepresentation.ArrayOfArrays; break; } } } switch (dictionaryRepresentation) { case DictionaryRepresentation.Document: bsonWriter.WriteStartDocument(); //foreach (DictionaryEntry dictionaryEntry in dictionary) //{ // bsonWriter.WriteName((string)dictionaryEntry.Key); // BsonSerializer.Serialize(bsonWriter, typeof(object), dictionaryEntry.Value, keyValuePairSerializationOptions.ValueSerializationOptions); //} for (int i = 0; i < nameValueCollection.Count; i++) { bsonWriter.WriteString(nameValueCollection.GetKey(i), nameValueCollection.Get(i)); } bsonWriter.WriteEndDocument(); break; case DictionaryRepresentation.ArrayOfArrays: case DictionaryRepresentation.ArrayOfDocuments: // override KeyValuePair representation if necessary var keyValuePairRepresentation = (dictionaryRepresentation == DictionaryRepresentation.ArrayOfArrays) ? BsonType.Array : BsonType.Document; if (keyValuePairSerializationOptions.Representation != keyValuePairRepresentation) { keyValuePairSerializationOptions = new KeyValuePairSerializationOptions(keyValuePairRepresentation, keyValuePairSerializationOptions.KeySerializationOptions, keyValuePairSerializationOptions.ValueSerializationOptions); } bsonWriter.WriteStartArray(); //foreach (DictionaryEntry dictionaryEntry in dictionary) for (int i = 0; i < nameValueCollection.Count; i++) { //var keyValuePair = new KeyValuePair<object, object>(dictionaryEntry.Key, dictionaryEntry.Value); var keyValuePair = new KeyValuePair<string, string>(nameValueCollection.GetKey(i), nameValueCollection.Get(i)); //_keyValuePairSerializer.Serialize(bsonWriter, typeof(KeyValuePair<object, object>), keyValuePair, keyValuePairSerializationOptions); _keyValuePairSerializer.Serialize(bsonWriter, typeof(KeyValuePair<string, string>), keyValuePair, keyValuePairSerializationOptions); } bsonWriter.WriteEndArray(); //bsonWriter.WriteStartArray(); //for (int i = 0; i < nameValueCollection.Count; i++) //{ // bsonWriter.WriteStartArray(); // bsonWriter.WriteString(nameValueCollection.GetKey(i), nameValueCollection.Get(i)); // bsonWriter.WriteEndArray(); //} //bsonWriter.WriteEndArray(); break; //case DictionaryRepresentation.ArrayOfDocuments: // bsonWriter.WriteStartArray(); // for (int i = 0; i < nameValueCollection.Count; i++) // { // bsonWriter.WriteStartDocument(); // bsonWriter.WriteString(nameValueCollection.GetKey(i), nameValueCollection.Get(i)); // bsonWriter.WriteEndDocument(); // } // bsonWriter.WriteEndArray(); // break; default: var message = string.Format("'{0}' is not a valid IDictionary representation.", dictionaryRepresentation); throw new BsonSerializationException(message); } } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var profileInfo = (SystemProfileInfo)value; bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("ts", BsonUtils.ToMillisecondsSinceEpoch(profileInfo.Timestamp)); if (profileInfo.Info != null) { bsonWriter.WriteString("info", profileInfo.Info); } if (profileInfo.Op != null) { bsonWriter.WriteString("op", profileInfo.Op); } if (profileInfo.Namespace != null) { bsonWriter.WriteString("ns", profileInfo.Namespace); } if (profileInfo.Command != null) { bsonWriter.WriteName("command"); profileInfo.Command.WriteTo(bsonWriter); } if (profileInfo.Query != null) { bsonWriter.WriteName("query"); profileInfo.Query.WriteTo(bsonWriter); } if (profileInfo.UpdateObject != null) { bsonWriter.WriteName("updateobj"); profileInfo.UpdateObject.WriteTo(bsonWriter); } if (profileInfo.CursorId != 0) { bsonWriter.WriteInt64("cursorid", profileInfo.CursorId); } if (profileInfo.NumberToReturn != 0) { bsonWriter.WriteInt32("ntoreturn", profileInfo.NumberToReturn); } if (profileInfo.NumberToSkip != 0) { bsonWriter.WriteInt32("ntoskip", profileInfo.NumberToSkip); } if (profileInfo.Exhaust) { bsonWriter.WriteBoolean("exhaust", profileInfo.Exhaust); } if (profileInfo.NumberScanned != 0) { bsonWriter.WriteInt32("nscanned", profileInfo.NumberScanned); } if (profileInfo.IdHack) { bsonWriter.WriteBoolean("idhack", profileInfo.IdHack); } if (profileInfo.ScanAndOrder) { bsonWriter.WriteBoolean("scanAndOrder", profileInfo.ScanAndOrder); } if (profileInfo.Moved) { bsonWriter.WriteBoolean("moved", profileInfo.Moved); } if (profileInfo.FastMod) { bsonWriter.WriteBoolean("fastmod", profileInfo.FastMod); } if (profileInfo.FastModInsert) { bsonWriter.WriteBoolean("fastmodinsert", profileInfo.FastModInsert); } if (profileInfo.Upsert) { bsonWriter.WriteBoolean("upsert", profileInfo.Upsert); } if (profileInfo.KeyUpdates != 0) { bsonWriter.WriteInt32("keyUpdates", profileInfo.KeyUpdates); } if (profileInfo.Exception != null) { bsonWriter.WriteString("exception", profileInfo.Exception); } if (profileInfo.ExceptionCode != 0) { bsonWriter.WriteInt32("exceptionCode", profileInfo.ExceptionCode); } if (profileInfo.NumberReturned != 0) { bsonWriter.WriteInt32("nreturned", profileInfo.NumberReturned); } if (profileInfo.ResponseLength != 0) { bsonWriter.WriteInt32("responseLength", profileInfo.ResponseLength); } bsonWriter.WriteDouble("millis", profileInfo.Duration.TotalMilliseconds); if (profileInfo.Client != null) { bsonWriter.WriteString("client", profileInfo.Client); } if (profileInfo.User != null) { bsonWriter.WriteString("user", profileInfo.User); } if (profileInfo.Error != null) { bsonWriter.WriteString("err", profileInfo.Error); } if (profileInfo.Abbreviated != null) { bsonWriter.WriteString("abbreviated", profileInfo.Abbreviated); } bsonWriter.WriteEndDocument(); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { if (nominalType == typeof(object)) { var actualType = value.GetType(); bsonWriter.WriteStartDocument(); bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType)); bsonWriter.WriteName("_v"); Serialize(bsonWriter, actualType, value, options); bsonWriter.WriteEndDocument(); return; } var items = ((Stack)value).ToArray(); // convert to array to allow efficient access in reverse order var arraySerializationOptions = EnsureSerializationOptions<ArraySerializationOptions>(options); var itemSerializationOptions = arraySerializationOptions.ItemSerializationOptions; // serialize first pushed item first (reverse of enumeration order) bsonWriter.WriteStartArray(); for (var i = items.Length - 1; i >= 0; i--) { BsonSerializer.Serialize(bsonWriter, typeof(object), items[i], itemSerializationOptions); } bsonWriter.WriteEndArray(); } }
void IBsonSerializable.Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options) { bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("ts", BsonUtils.ToMillisecondsSinceEpoch(_timestamp)); if (_info != null) { bsonWriter.WriteString("info", _info); } if (_op != null) { bsonWriter.WriteString("op", _op); } if (_namespace != null) { bsonWriter.WriteString("ns", _namespace); } if (_command != null) { bsonWriter.WriteName("command"); _command.WriteTo(bsonWriter); } if (_query != null) { bsonWriter.WriteName("query"); _query.WriteTo(bsonWriter); } if (_updateObject != null) { bsonWriter.WriteName("updateobj"); _updateObject.WriteTo(bsonWriter); } if (_cursorId != 0) { bsonWriter.WriteInt64("cursorid", _cursorId); } if (_numberToReturn != 0) { bsonWriter.WriteInt32("ntoreturn", _numberToReturn); } if (_numberToSkip != 0) { bsonWriter.WriteInt32("ntoskip", _numberToSkip); } if (_exhaust) { bsonWriter.WriteBoolean("exhaust", _exhaust); } if (_numberScanned != 0) { bsonWriter.WriteInt32("nscanned", _numberScanned); } if (_idHack) { bsonWriter.WriteBoolean("idhack", _idHack); } if (_scanAndOrder) { bsonWriter.WriteBoolean("scanAndOrder", _scanAndOrder); } if (_moved) { bsonWriter.WriteBoolean("moved", _moved); } if (_fastMod) { bsonWriter.WriteBoolean("fastmod", _fastMod); } if (_fastModInsert) { bsonWriter.WriteBoolean("fastmodinsert", _fastModInsert); } if (_upsert) { bsonWriter.WriteBoolean("upsert", _upsert); } if (_keyUpdates != 0) { bsonWriter.WriteInt32("keyUpdates", _keyUpdates); } if (_exception != null) { bsonWriter.WriteString("exception", _exception); } if (_exceptionCode != 0) { bsonWriter.WriteInt32("exceptionCode", _exceptionCode); } if (_numberReturned != 0) { bsonWriter.WriteInt32("nreturned", _numberReturned); } if (_responseLength != 0) { bsonWriter.WriteInt32("responseLength", _responseLength); } bsonWriter.WriteDouble("millis", _duration.TotalMilliseconds); if (_client != null) { bsonWriter.WriteString("client", _client); } if (_user != null) { bsonWriter.WriteString("user", _user); } if (_error != null) { bsonWriter.WriteString("err", _error); } if (_abbreviated != null) { bsonWriter.WriteString("abbreviated", _abbreviated); } bsonWriter.WriteEndDocument(); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { // Nullable types are weird because they get boxed as their underlying value type // we can best handle that by switching the nominalType to the underlying value type // (so VerifyNominalType doesn't fail and we don't get an unnecessary discriminator) if (nominalType.IsGenericType && nominalType.GetGenericTypeDefinition() == typeof(Nullable<>)) { nominalType = nominalType.GetGenericArguments()[0]; } VerifyNominalType(nominalType); var actualType = (value == null) ? nominalType : value.GetType(); var classMap = BsonClassMap.LookupClassMap(actualType); bsonWriter.WriteStartDocument(); var documentOptions = (options == null) ? DocumentSerializationOptions.Defaults : (DocumentSerializationOptions)options; BsonMemberMap idMemberMap = null; if (documentOptions.SerializeIdFirst) { idMemberMap = classMap.IdMemberMap; if (idMemberMap != null) { SerializeMember(bsonWriter, value, idMemberMap); } } if (actualType != nominalType || classMap.DiscriminatorIsRequired || classMap.HasRootClass) { // never write out a discriminator for an anonymous class if (!classMap.IsAnonymous) { var discriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(nominalType); var discriminator = discriminatorConvention.GetDiscriminator(nominalType, actualType); if (discriminator != null) { bsonWriter.WriteName(discriminatorConvention.ElementName); discriminator.WriteTo(bsonWriter); } } } foreach (var memberMap in classMap.MemberMaps) { // note: if serializeIdFirst is false then idMemberMap will be null (so no property will be skipped) if (memberMap != idMemberMap) { if (memberMap == classMap.ExtraElementsMemberMap) { SerializeExtraElements(bsonWriter, value, memberMap); } else { SerializeMember(bsonWriter, value, memberMap); } } } bsonWriter.WriteEndDocument(); } }
protected void WritePolygon(BsonWriter writer,string name,Polygon value) { writer.WriteName(name); WritePolygon(writer,value); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var actualType = value.GetType(); var discriminator = GetDiscriminator(nominalType, actualType); if (discriminator != null) { bsonWriter.WriteStartDocument(); bsonWriter.WriteString("_t", discriminator); bsonWriter.WriteName("_v"); Serialize(bsonWriter, actualType, value, options); bsonWriter.WriteEndDocument(); return; } var arraySerializationOptions = EnsureSerializationOptions<ArraySerializationOptions>(options); var itemSerializationOptions = arraySerializationOptions.ItemSerializationOptions; Type lastItemType = null; IBsonSerializer lastItemSerializer = null; bsonWriter.WriteStartArray(); foreach (var item in EnumerateItemsInSerializationOrder(value)) { var itemType = (item == null) ? typeof(object) : item.GetType(); IBsonSerializer itemSerializer; if (itemType == lastItemType) { itemSerializer = lastItemSerializer; } else { itemSerializer = BsonSerializer.LookupSerializer(itemType); lastItemType = itemType; lastItemSerializer = itemSerializer; } itemSerializer.Serialize(bsonWriter, typeof(object), item, itemSerializationOptions); } bsonWriter.WriteEndArray(); } }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options ) { if (value == null) { bsonWriter.WriteNull(); } else { var dictionary = (IDictionary) value; if (dictionary.Keys.Cast<object>().All(o => o.GetType() == typeof(string))) { bsonWriter.WriteStartDocument(); int index = 0; foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteName((string) entry.Key); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value); index++; } bsonWriter.WriteEndDocument(); } else { bsonWriter.WriteStartArray(); foreach (DictionaryEntry entry in dictionary) { bsonWriter.WriteStartArray(); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Key); BsonSerializer.Serialize(bsonWriter, typeof(object), entry.Value); bsonWriter.WriteEndArray(); } bsonWriter.WriteEndArray(); } } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { if (nominalType == typeof(object)) { var actualType = value.GetType(); bsonWriter.WriteStartDocument(); bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType)); bsonWriter.WriteName("_v"); Serialize(bsonWriter, actualType, value, options); // recursive call replacing nominalType with actualType bsonWriter.WriteEndDocument(); return; } var dictionary = (IDictionary)value; var dictionarySerializationOptions = EnsureSerializationOptions(options); var dictionaryRepresentation = dictionarySerializationOptions.Representation; var keyValuePairSerializationOptions = dictionarySerializationOptions.KeyValuePairSerializationOptions; if (dictionaryRepresentation == DictionaryRepresentation.Dynamic) { dictionaryRepresentation = DictionaryRepresentation.Document; foreach (object key in dictionary.Keys) { var name = key as string; // key might not be a string if (name == null || (name.Length > 0 && name[0] == '$') || name.IndexOf('.') != -1) { dictionaryRepresentation = DictionaryRepresentation.ArrayOfArrays; break; } } } switch (dictionaryRepresentation) { case DictionaryRepresentation.Document: bsonWriter.WriteStartDocument(); foreach (DictionaryEntry dictionaryEntry in dictionary) { bsonWriter.WriteName((string)dictionaryEntry.Key); BsonSerializer.Serialize(bsonWriter, typeof(object), dictionaryEntry.Value, keyValuePairSerializationOptions.ValueSerializationOptions); } bsonWriter.WriteEndDocument(); break; case DictionaryRepresentation.ArrayOfArrays: case DictionaryRepresentation.ArrayOfDocuments: // override KeyValuePair representation if necessary var keyValuePairRepresentation = (dictionaryRepresentation == DictionaryRepresentation.ArrayOfArrays) ? BsonType.Array : BsonType.Document; if (keyValuePairSerializationOptions.Representation != keyValuePairRepresentation) { keyValuePairSerializationOptions = new KeyValuePairSerializationOptions( keyValuePairRepresentation, keyValuePairSerializationOptions.KeySerializationOptions, keyValuePairSerializationOptions.ValueSerializationOptions); } bsonWriter.WriteStartArray(); foreach (DictionaryEntry dictionaryEntry in dictionary) { var keyValuePair = new KeyValuePair<object, object>(dictionaryEntry.Key, dictionaryEntry.Value); _keyValuePairSerializer.Serialize( bsonWriter, typeof(KeyValuePair<object, object>), keyValuePair, keyValuePairSerializationOptions); } bsonWriter.WriteEndArray(); break; default: var message = string.Format("'{0}' is not a valid IDictionary representation.", dictionaryRepresentation); throw new BsonSerializationException(message); } } }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, bool serializeIdFirst ) { if (value == null) { bsonWriter.WriteNull(); } else { bsonWriter.WriteStartArray(); var outputOrder = new ArrayList((Stack) value); // serialize first pushed item first (reverse of enumerator order) outputOrder.Reverse(); int index = 0; foreach (var element in outputOrder) { bsonWriter.WriteName(index.ToString()); BsonSerializer.Serialize(bsonWriter, typeof(object), element); index++; } bsonWriter.WriteEndArray(); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { if (nominalType == typeof(object)) { var actualType = value.GetType(); bsonWriter.WriteStartDocument(); bsonWriter.WriteString("_t", TypeNameDiscriminator.GetDiscriminator(actualType)); bsonWriter.WriteName("_v"); Serialize(bsonWriter, actualType, value, options); bsonWriter.WriteEndDocument(); return; } var items = (Queue)value; var arraySerializationOptions = EnsureSerializationOptions<ArraySerializationOptions>(options); var itemSerializationOptions = arraySerializationOptions.ItemSerializationOptions; bsonWriter.WriteStartArray(); foreach (var item in items) { BsonSerializer.Serialize(bsonWriter, typeof(object), item, itemSerializationOptions); } bsonWriter.WriteEndArray(); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var dbRef = (MongoDBRef)value; bsonWriter.WriteStartDocument(); bsonWriter.WriteString("$ref", dbRef.CollectionName); bsonWriter.WriteName("$id"); dbRef.Id.WriteTo(bsonWriter); if (dbRef.DatabaseName != null) { bsonWriter.WriteString("$db", dbRef.DatabaseName); } bsonWriter.WriteEndDocument(); } }