Represents the mapping between a field or property and a BSON element.
Beispiel #1
0
 public void Apply(BsonMemberMap memberMap)
 {
     if (memberMap.MemberType == typeof(Guid))
     {
         memberMap.SetDefaultValue(Guid.Empty);
     }
 }
        /// <summary>
        /// Applies the specified member map convention.
        /// </summary>
        /// <param name="memberMap">The member map convention.</param>
        public void Apply(BsonMemberMap memberMap)
        {
            Func<Type, IBsonSerializer> converter = t =>
                {
                    if (t == typeof(DateTime))
                        return new DateTimeSerializer(DateTimeKind.Local);
                    else if (t == typeof(DateTime?))
                        return new NullableSerializer<DateTime>(new DateTimeSerializer(DateTimeKind.Local));
                    return null;
                };

            IBsonSerializer serializer = null;
            switch (memberMap.MemberInfo.MemberType)
            {
                case MemberTypes.Property:
                    PropertyInfo propertyInfo = (PropertyInfo)memberMap.MemberInfo;
                    serializer = converter(propertyInfo.PropertyType);
                    break;
                case MemberTypes.Field:
                    FieldInfo fieldInfo = (FieldInfo)memberMap.MemberInfo;
                    serializer = converter(fieldInfo.FieldType);
                    break;
                default:
                    break;
            }

            if (serializer != null)
                memberMap.SetSerializer(serializer);
        }
 /// <summary>
 /// Initializes an instance of the MongoFieldExpression class.
 /// </summary>
 /// <param name="expression">The expression that references the field.</param>
 /// <param name="name">The name of the referenced field.</param>
 /// <param name="memberMap">The BsonMemberMap of the referenced field.</param>
 public MongoFieldExpression(Expression expression, string name, BsonMemberMap memberMap)
     : base(MongoExpressionType.Field, expression.Type)
 {
     _expression = expression;
     _name = name;
     _memberMap = memberMap;
 }
 /// <summary>
 /// Changes the decimal representation if the member is a decimal
 /// </summary>
 /// <param name="memberMap"></param>
 public void Apply(BsonMemberMap memberMap)
 {
     if (memberMap.MemberType == typeof(string) && memberMap.ClassMap.IdMemberMap == memberMap)
     {
         memberMap.SetSerializer(new StringSerializer(BsonType.ObjectId));
     }
 }
 public FieldExpression(Expression expression, Alias alias, string name, BsonMemberMap memberMap)
     : base(MongoExpressionType.Field, expression.Type)
 {
     Alias = alias;
     Expression = expression;
     Name = name;
     MemberMap = memberMap;
 }
 public void Apply(BsonMemberMap memberMap)
 {
     if (memberMap.MemberType.IsEnum)
     {
         var serializer = memberMap.GetSerializer();
         var camelCaseValueSerializer = new CamelCaseValueSerializer(serializer);
         memberMap.SetSerializer(camelCaseValueSerializer);
     }
 }
        internal BsonValue GetValue(BsonMemberMap memberMap, Expression expression)
        {
            _memberMap = memberMap;
            Visit(expression);
            if (_value == null)
                throw new NotSupportedException("No value result.");

            return _value;
        }
 protected override void DeserializeExtraElement(BsonReader bsonReader, object obj, string elementName, BsonMemberMap extraElementsMemberMap)
 {
     if (elementName == VERSION_ELEMENT_NAME)
     {
         var extraElements = EnsureExtraElements(obj, extraElementsMemberMap);
         extraElements[VERSION_ELEMENT_NAME] = _versionSerializer.Deserialize(bsonReader, typeof (Version), null);
     }
     else
     {
         base.DeserializeExtraElement(bsonReader, obj, elementName, extraElementsMemberMap);
     }
 }
        private object SerializeValue(object value, BsonMemberMap memberMap)
        {
            const string tmpField = "tmp";

            var type = value.GetType();
            var serializer = memberMap.GetSerializer(type);

            var document = new BsonDocument();
            using (var writer = BsonWriter.Create(document))
            {
                // serialize the value inside a document using the provided serializer
                writer.WriteStartDocument();
                writer.WriteName(tmpField);
                serializer.Serialize(writer, type, value, memberMap.SerializationOptions);
                writer.WriteEndDocument();
            }

            // extract the serialized value from the document
            return document[tmpField];
        }
 // public methods
 /// <summary>
 /// Applies a modification to the member map.
 /// </summary>
 /// <param name="memberMap">The member map.</param>
 public virtual void Apply(BsonMemberMap memberMap)
 {
     var memberSerializer = memberMap.GetSerializer(memberMap.MemberType);
     var memberSerializationOptions = memberMap.SerializationOptions;
     if (memberSerializationOptions == null)
     {
         var memberDefaultSerializationOptions = memberSerializer.GetDefaultSerializationOptions();
         if (memberDefaultSerializationOptions == null)
         {
             var message = string.Format(
                 "A serialization options attribute of type {0} cannot be used when the serializer is of type {1}.",
                 BsonUtils.GetFriendlyTypeName(this.GetType()),
                 BsonUtils.GetFriendlyTypeName(memberSerializer.GetType()));
             throw new NotSupportedException(message);
         }
         memberSerializationOptions = memberDefaultSerializationOptions.Clone();
         memberMap.SetSerializationOptions(memberSerializationOptions);
     }
     memberSerializationOptions.ApplyAttribute(memberSerializer, this);
 }
        private void DeserializeExtraElementMember(
            BsonDeserializationContext context,
            object obj,
            string elementName,
            BsonMemberMap extraElementsMemberMap)
        {
            var bsonReader = context.Reader;

            if (extraElementsMemberMap.MemberType == typeof(BsonDocument))
            {
                var extraElements = (BsonDocument)extraElementsMemberMap.Getter(obj);
                if (extraElements == null)
                {
                    extraElements = new BsonDocument();
                    extraElementsMemberMap.Setter(obj, extraElements);
                }

                var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
                extraElements[elementName] = bsonValue;
            }
            else
            {
                var extraElements = (IDictionary <string, object>)extraElementsMemberMap.Getter(obj);
                if (extraElements == null)
                {
                    if (extraElementsMemberMap.MemberType == typeof(IDictionary <string, object>))
                    {
                        extraElements = new Dictionary <string, object>();
                    }
                    else
                    {
                        extraElements = (IDictionary <string, object>)Activator.CreateInstance(extraElementsMemberMap.MemberType);
                    }
                    extraElementsMemberMap.Setter(obj, extraElements);
                }

                var bsonValue = BsonValueSerializer.Instance.Deserialize(context);
                extraElements[elementName] = BsonTypeMapper.MapToDotNetValue(bsonValue);
            }
        }
 /// <summary>
 /// Applies the specified member map convention.
 /// </summary>
 /// <param name="memberMap">The member map convention.</param>
 public void Apply(BsonMemberMap memberMap)
 {
     IBsonSerializationOptions options = null;
     switch (memberMap.MemberInfo.MemberType)
     {
         case MemberTypes.Property:
             PropertyInfo propertyInfo = (PropertyInfo)memberMap.MemberInfo;
             if (propertyInfo.PropertyType == typeof(DateTime) ||
                 propertyInfo.PropertyType == typeof(DateTime?))
                 options = new DateTimeSerializationOptions(DateTimeKind.Local);
             break;
         case MemberTypes.Field:
             FieldInfo fieldInfo = (FieldInfo)memberMap.MemberInfo;
             if (fieldInfo.FieldType == typeof(DateTime) ||
                 fieldInfo.FieldType == typeof(DateTime?))
                 options = new DateTimeSerializationOptions(DateTimeKind.Local);
             break;
         default:
             break;
     }
     memberMap.SetSerializationOptions(options);
 }
Beispiel #13
0
        private void DeserializeMember(BsonReader bsonReader, object obj, BsonMemberMap memberMap)
        {
            try
            {
                object value;

                var nominalType = memberMap.MemberType;
                var bsonType    = bsonReader.GetCurrentBsonType();
                if (bsonType == BsonType.Null && nominalType.IsInterface)
                {
                    bsonReader.ReadNull();
                    value = null;
                }
                else
                {
                    Type actualType;
                    if (bsonType == BsonType.Null)
                    {
                        actualType = nominalType;
                    }
                    else
                    {
                        var discriminatorConvention = memberMap.GetDiscriminatorConvention();
                        actualType = discriminatorConvention.GetActualType(bsonReader, nominalType); // returns nominalType if no discriminator found
                    }
                    var serializer = memberMap.GetSerializer(actualType);
                    value = serializer.Deserialize(bsonReader, nominalType, actualType, memberMap.SerializationOptions);
                }

                memberMap.Setter(obj, value);
            }
            catch (Exception ex)
            {
                var message = string.Format(
                    "An error occurred while deserializing the {0} {1} of class {2}: {3}", // terminating period provided by nested message
                    memberMap.MemberName, (memberMap.MemberInfo.MemberType == MemberTypes.Field) ? "field" : "property", obj.GetType().FullName, ex.Message);
                throw new FileFormatException(message, ex);
            }
        }
Beispiel #14
0
        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
            {
                var actualType = (value == null) ? nominalType : value.GetType();
                var serializer = memberMap.GetSerializer(actualType);
                serializer.Serialize(bsonWriter, nominalType, value, memberMap.SerializationOptions);
            }
        }
Beispiel #15
0
        private void DeserializeMember(
            BsonReader bsonReader,
            object obj,
            BsonMemberMap memberMap
            )
        {
            var  nominalType = memberMap.MemberType;
            Type actualType;

            if (bsonReader.CurrentBsonType == BsonType.Null)
            {
                actualType = nominalType;
            }
            else
            {
                var discriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(nominalType);
                actualType = discriminatorConvention.GetActualType(bsonReader, nominalType); // returns nominalType if no discriminator found
            }
            var serializer = memberMap.GetSerializer(actualType);
            var value      = serializer.Deserialize(bsonReader, nominalType, actualType, memberMap.SerializationOptions);

            memberMap.Setter(obj, value);
        }
Beispiel #16
0
        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
            }

            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);
        }
Beispiel #17
0
        /// <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();
            }
        }
Beispiel #18
0
            public FindResult Find(Expression expression)
            {
                if (expression.NodeType == ExpressionType.Parameter)
                    return null;

                _fieldParts = new Stack<string>();
                _isBlocked = false;
                _bsonMemberMap = null;
                Visit(expression);
                var fieldName = string.Join(".", _fieldParts.ToArray());

                if (_isBlocked)
                    return null;

                return new FindResult { FieldName = fieldName, MemberMap = _bsonMemberMap };
            }
        // private methods
        private void DeserializeExtraElement(BsonReader bsonReader, object obj, string elementName, BsonMemberMap extraElementsMemberMap)
        {
            var extraElements = (BsonDocument)extraElementsMemberMap.Getter(obj);

            if (extraElements == null)
            {
                extraElements = new BsonDocument();
                extraElementsMemberMap.Setter(obj, extraElements);
            }
            var value = BsonValue.ReadFrom(bsonReader);

            extraElements[elementName] = value;
        }
        private void SerializeExtraElements(BsonSerializationContext context, object obj, BsonMemberMap extraElementsMemberMap)
        {
            var bsonWriter = context.Writer;

            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(context, element.Value);
                    }
                }
                else
                {
                    var dictionary = (IDictionary <string, object>)extraElements;
                    foreach (var key in dictionary.Keys)
                    {
                        bsonWriter.WriteName(key);
                        var value     = dictionary[key];
                        var bsonValue = BsonTypeMapper.MapToBsonValue(value);
                        BsonValueSerializer.Instance.Serialize(context, bsonValue);
                    }
                }
            }
        }
Beispiel #21
0
        /// <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();
            }
        }
 private void SerializeExtraElements(BsonWriter bsonWriter, object obj, BsonMemberMap extraElementsMemberMap)
 {
     var extraElements = (BsonDocument)extraElementsMemberMap.Getter(obj);
     if (extraElements != null)
     {
         foreach (var element in extraElements)
         {
             element.WriteTo(bsonWriter);
         }
     }
 }
 // private methods
 private void DeserializeExtraElement(
     BsonReader bsonReader,
     object obj,
     string elementName,
     BsonMemberMap extraElementsMemberMap)
 {
     if (extraElementsMemberMap.MemberType == typeof(BsonDocument))
     {
         var extraElements = (BsonDocument)extraElementsMemberMap.Getter(obj);
         if (extraElements == null)
         {
             extraElements = new BsonDocument();
             extraElementsMemberMap.Setter(obj, extraElements);
         }
         var bsonValue = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
         extraElements[elementName] = bsonValue;
     }
     else
     {
         var extraElements = (IDictionary<string, object>)extraElementsMemberMap.Getter(obj);
         if (extraElements == null)
         {
             if (extraElementsMemberMap.MemberType == typeof(IDictionary<string, object>))
             {
                 extraElements = new Dictionary<string, object>();
             }
             else
             {
                 extraElements = (IDictionary<string, object>)Activator.CreateInstance(extraElementsMemberMap.MemberType);
             }
             extraElementsMemberMap.Setter(obj, extraElements);
         }
         var bsonValue = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
         extraElements[elementName] = BsonTypeMapper.MapToDotNetValue(bsonValue);
     }
 }
        private object DeserializeMemberValue(BsonReader bsonReader, BsonMemberMap memberMap)
        {
            try
            {
                var nominalType = memberMap.MemberType;

                var bsonType = bsonReader.GetCurrentBsonType();
                if (bsonType == BsonType.Null && nominalType.IsInterface)
                {
                    bsonReader.ReadNull();
                    return null;
                }

                Type actualType;
                if (bsonType == BsonType.Null)
                {
                    actualType = nominalType;
                }
                else
                {
                    var discriminatorConvention = memberMap.GetDiscriminatorConvention();
                    actualType = discriminatorConvention.GetActualType(bsonReader, nominalType); // returns nominalType if no discriminator found
                }

                var serializer = memberMap.GetSerializer(actualType);
                return serializer.Deserialize(bsonReader, nominalType, actualType, memberMap.SerializationOptions);
            }
            catch (Exception ex)
            {
                var message = string.Format(
                    "An error occurred while deserializing the {0} {1} of class {2}: {3}", // terminating period provided by nested message
                    memberMap.MemberName, (memberMap.MemberInfo.MemberType == MemberTypes.Field) ? "field" : "property", memberMap.ClassMap.ClassType.FullName, ex.Message);
                throw new Exception(message, ex);
            }
        }
		private static bool IsReferencesManyRelation(BsonMemberMap memberMap)
		{
			return ReflectionUtility.IsListOfRawGeneric(typeof(Document<>), memberMap.MemberType);
		}
		private static void ValidateVirtualRelation(BsonMemberMap memberMap)
		{
			if (!((PropertyInfo)memberMap.MemberInfo).GetGetMethod().IsVirtual)
				throw new Exception("Relational association properties must be declared as virtual, to support lazy loading");
		}
        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 DeserializeMember(
     BsonReader bsonReader,
     object obj,
     BsonMemberMap memberMap
 ) {
     var nominalType = memberMap.MemberType;
     Type actualType;
     if (bsonReader.CurrentBsonType == BsonType.Null) {
         actualType = nominalType;
     } else {
         var discriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(nominalType);
         actualType = discriminatorConvention.GetActualType(bsonReader, nominalType); // returns nominalType if no discriminator found
     }
     var serializer = memberMap.GetSerializer(actualType);
     var value = serializer.Deserialize(bsonReader, nominalType, actualType, memberMap.SerializationOptions);
     memberMap.Setter(obj, value);
 }
 private static IDictionary<string, object> EnsureExtraElements(object obj, BsonMemberMap extraElementsMemberMap)
 {
     // TODO: make this method protected non-static and pull up?
     var extraElements = (IDictionary<string, object>) extraElementsMemberMap.Getter(obj);
     if (extraElements == null)
     {
         if (extraElementsMemberMap.MemberType == typeof (IDictionary<string, object>))
         {
             extraElements = new Dictionary<string, object>();
         }
         else
         {
             extraElements = (IDictionary<string, object>) Activator.CreateInstance(extraElementsMemberMap.MemberType);
         }
         extraElementsMemberMap.Setter(obj, extraElements);
     }
     return extraElements;
 }
 // private methods
 private void DeserializeExtraElement(
     BsonReader bsonReader,
     object obj,
     string elementName,
     BsonMemberMap extraElementsMemberMap)
 {
     var extraElements = (BsonDocument)extraElementsMemberMap.Getter(obj);
     if (extraElements == null)
     {
         extraElements = new BsonDocument();
         extraElementsMemberMap.Setter(obj, extraElements);
     }
     var value = BsonValue.ReadFrom(bsonReader);
     extraElements[elementName] = value;
 }
 private void DeserializeMember(BsonReader bsonReader, object obj, BsonMemberMap memberMap)
 {
     try
     {
         var nominalType = memberMap.MemberType;
         Type actualType;
         if (bsonReader.CurrentBsonType == BsonType.Null)
         {
             actualType = nominalType;
         }
         else
         {
             var discriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(nominalType);
             actualType = discriminatorConvention.GetActualType(bsonReader, nominalType); // returns nominalType if no discriminator found
         }
         var serializer = memberMap.GetSerializer(actualType);
         var value = serializer.Deserialize(bsonReader, nominalType, actualType, memberMap.SerializationOptions);
         memberMap.Setter(obj, value);
     }
     catch (Exception ex)
     {
         var message = string.Format(
             "An error occurred while deserializing the {0} {1} of class {2}: {3}", // terminating period provided by nested message
             memberMap.MemberName, (memberMap.MemberInfo.MemberType == MemberTypes.Field) ? "field" : "property", obj.GetType().FullName, ex.Message);
         throw new FileFormatException(message, ex);
     }
 }
        private void DeserializeMember(BsonReader bsonReader, object obj, BsonMemberMap memberMap)
        {
            try
            {
                var nominalType = memberMap.MemberType;
                object value = null;

                var bsonType = bsonReader.GetCurrentBsonType();
                if (bsonType == BsonType.Null && nominalType.IsInterface)
                {
                    bsonReader.ReadNull();
                    goto setvalue;
                }
                else if (memberMap.MemberTypeIsBsonValue)
                {
                    if (bsonType == BsonType.Document && IsCSharpNullRepresentation(bsonReader))
                    {
                        // if IsCSharpNullRepresentation returns true it will have consumed the document representing C# null
                        goto setvalue;
                    }

                    // handle BSON null for backward compatibility with existing data (new data would have _csharpnull)
                    if (bsonType == BsonType.Null && (nominalType != typeof(BsonValue) && nominalType != typeof(BsonNull)))
                    {
                        bsonReader.ReadNull();
                        goto setvalue;
                    }
                }

                Type actualType;
                if (bsonType == BsonType.Null)
                {
                    actualType = nominalType;
                }
                else
                {
                    var discriminatorConvention = memberMap.GetDiscriminatorConvention();
                    actualType = discriminatorConvention.GetActualType(bsonReader, nominalType); // returns nominalType if no discriminator found
                }
                var serializer = memberMap.GetSerializer(actualType);
                value = serializer.Deserialize(bsonReader, nominalType, actualType, memberMap.SerializationOptions);

                setvalue:
                memberMap.Setter(obj, value);
            }
            catch (Exception ex)
            {
                var message = string.Format(
                    "An error occurred while deserializing the {0} {1} of class {2}: {3}", // terminating period provided by nested message
                    memberMap.MemberName, (memberMap.MemberInfo.MemberType == MemberTypes.Field) ? "field" : "property", obj.GetType().FullName, ex.Message);
                throw new FileFormatException(message, ex);
            }
        }
        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);
        }
 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);
                 }
             }
         }
     }
 }
 public void Apply(BsonMemberMap memberMap)
 {
     IsRun = true;
     RunCount++;
     RunTicks = _stopwatch.ElapsedTicks;
 }
        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);
            }
        }
		private void SerializeMember(BsonWriter bsonWriter, object obj, BsonMemberMap memberMap)
		{
			object objA = memberMap.Getter(obj);
			if (objA == null && memberMap.IgnoreIfNull || (memberMap.HasDefaultValue && !memberMap.SerializeDefaultValue && object.Equals(objA, memberMap.DefaultValue) || !memberMap.ShouldSerializeMethod(obj)))
				return;
			bsonWriter.WriteName(memberMap.ElementName);
			Type memberType = memberMap.MemberType;
			Type actualType = objA == null ? memberType : objA.GetType();
			if (IsRelation(memberMap))
				ValidateVirtualRelation(memberMap);
			memberMap.GetSerializer(actualType).Serialize(bsonWriter, memberType, objA, memberMap.SerializationOptions);
		}
Beispiel #38
0
            protected override Expression VisitMemberAccess(MemberExpression m)
            {
                var declaringType = m.Member.DeclaringType;
                if (!TypeHelper.IsNativeToMongo(declaringType) && !IsCollection(declaringType))
                {
                    Expression e;
                    if (_determiner.IsGroupingKey(m))
                    {
                        _fieldParts.Push(m.Member.Name);
                        Visit(m.Expression);
                        return m;
                    }
                    else if (_memberMap.TryGetValue(m.Member, out e) && e is FieldExpression)
                    {
                        var field = (FieldExpression)e;
                        _fieldParts.Push(field.Name);

                        if (_bsonMemberMap == null)
                            _bsonMemberMap = field.MemberMap;

                        Visit(m.Expression);
                        return m;
                    }
                    else if(e == null)
                    {
                        var classMap = BsonClassMap.LookupClassMap(declaringType);
                        var propMap = classMap.GetMemberMap(m.Member.Name);
                        if (propMap != null)
                        {
                            _fieldParts.Push(propMap.ElementName);

                            if (_bsonMemberMap == null)
                                _bsonMemberMap = propMap;
                        }
                        else
                            _fieldParts.Push(m.Member.Name);

                        Visit(m.Expression);
                        return m;
                    }
                }

                _isBlocked = true;
                return m;
            }
        private void SerializeNormalMember(BsonSerializationContext context, object obj, BsonMemberMap memberMap)
        {
            var bsonWriter = context.Writer;

            var value = memberMap.Getter(obj);

            if (!memberMap.ShouldSerialize(obj, value))
            {
                return; // don't serialize member
            }

            bsonWriter.WriteName(memberMap.ElementName);
            memberMap.GetSerializer().Serialize(context, value);
        }
		public void Apply(BsonMemberMap memberMap)
		{
			if (memberMap.MemberName.StartsWith("_"))
				memberMap.SetShouldSerializeMethod(o => false);
		}