BsonMemberMap.cs 23.9 KB
Newer Older
T
tanghai 已提交
1
/* Copyright 2010-2016 MongoDB Inc.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

using System;
using System.Linq.Expressions;
using System.Reflection;
T
tanghai 已提交
19
#if !ENABLE_IL2CPP
T
tanghai 已提交
20 21
using System.Reflection.Emit;		
#endif
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
using MongoDB.Bson.Serialization.Serializers;

namespace MongoDB.Bson.Serialization
{
    /// <summary>
    /// Represents the mapping between a field or property and a BSON element.
    /// </summary>
    public class BsonMemberMap
    {
        // private fields
        private readonly BsonClassMap _classMap;
        private readonly MemberInfo _memberInfo;
        private readonly Type _memberType;
        private readonly bool _memberTypeIsBsonValue;

        private string _elementName;
        private bool _frozen; // once a class map has been frozen no further changes are allowed
        private int _order;
        private Func<object, object> _getter;
        private Action<object, object> _setter;
T
tanghai 已提交
42
        private volatile IBsonSerializer _serializer;
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
        private IIdGenerator _idGenerator;
        private bool _isRequired;
        private Func<object, bool> _shouldSerializeMethod;
        private bool _ignoreIfDefault;
        private bool _ignoreIfNull;
        private object _defaultValue;
        private Func<object> _defaultValueCreator;
        private bool _defaultValueSpecified;

        // constructors
        /// <summary>
        /// Initializes a new instance of the BsonMemberMap class.
        /// </summary>
        /// <param name="classMap">The class map this member map belongs to.</param>
        /// <param name="memberInfo">The member info.</param>
        public BsonMemberMap(BsonClassMap classMap, MemberInfo memberInfo)
        {
            _classMap = classMap;
            _memberInfo = memberInfo;
            _memberType = BsonClassMap.GetMemberInfoType(memberInfo);
T
tanghai 已提交
63
            _memberTypeIsBsonValue = typeof(BsonValue).GetTypeInfo().IsAssignableFrom(_memberType);
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148

            Reset();
        }

        // public properties
        /// <summary>
        /// Gets the class map that this member map belongs to.
        /// </summary>
        public BsonClassMap ClassMap
        {
            get { return _classMap; }
        }

        /// <summary>
        /// Gets the name of the member.
        /// </summary>
        public string MemberName
        {
            get { return _memberInfo.Name; }
        }

        /// <summary>
        /// Gets the type of the member.
        /// </summary>
        public Type MemberType
        {
            get { return _memberType; }
        }

        /// <summary>
        /// Gets whether the member type is a BsonValue.
        /// </summary>
        public bool MemberTypeIsBsonValue
        {
            get { return _memberTypeIsBsonValue; }
        }

        /// <summary>
        /// Gets the name of the element.
        /// </summary>
        public string ElementName
        {
            get { return _elementName; }
        }

        /// <summary>
        /// Gets the serialization order.
        /// </summary>
        public int Order
        {
            get { return _order; }
        }

        /// <summary>
        /// Gets the member info.
        /// </summary>
        public MemberInfo MemberInfo
        {
            get { return _memberInfo; }
        }

        /// <summary>
        /// Gets the getter function.
        /// </summary>
        public Func<object, object> Getter
        {
            get
            {
                if (_getter == null)
                {
                    _getter = GetGetter();
                }
                return _getter;
            }
        }

        /// <summary>
        /// Gets the setter function.
        /// </summary>
        public Action<object, object> Setter
        {
            get
            {
                if (_setter == null)
                {
T
tanghai 已提交
149
                    if (_memberInfo is FieldInfo)
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
                    {
                        _setter = GetFieldSetter();
                    }
                    else
                    {
                        _setter = GetPropertySetter();
                    }
                }
                return _setter;
            }
        }

        /// <summary>
        /// Gets the Id generator.
        /// </summary>
        public IIdGenerator IdGenerator
        {
            get { return _idGenerator; }
        }

        /// <summary>
        /// Gets whether a default value was specified.
        /// </summary>
        public bool IsDefaultValueSpecified
        {
            get { return _defaultValueSpecified; }
        }

        /// <summary>
        /// Gets whether an element is required for this member when deserialized.
        /// </summary>
        public bool IsRequired
        {
            get { return _isRequired; }
        }

        /// <summary>
        /// Gets the method that will be called to determine whether the member should be serialized.
        /// </summary>
        public Func<object, bool> ShouldSerializeMethod
        {
            get { return _shouldSerializeMethod; }
        }

        /// <summary>
        /// Gets whether default values should be ignored when serialized.
        /// </summary>
        public bool IgnoreIfDefault
        {
            get { return _ignoreIfDefault; }
        }

        /// <summary>
        /// Gets whether null values should be ignored when serialized.
        /// </summary>
        public bool IgnoreIfNull
        {
            get { return _ignoreIfNull; }
        }

        /// <summary>
        /// Gets the default value.
        /// </summary>
        public object DefaultValue
        {
            get { return _defaultValueCreator != null ? _defaultValueCreator() : _defaultValue; }
        }

        /// <summary>
        /// Gets whether the member is readonly.
        /// </summary>
        /// <remarks>
        /// Readonly indicates that the member is written to the database, but not read from the database.
        /// </remarks>
        public bool IsReadOnly
        {
            get
            {
T
tanghai 已提交
228 229 230 231 232 233
                if (_memberInfo is FieldInfo)
                {
                    var field = (FieldInfo)_memberInfo;
                    return field.IsInitOnly || field.IsLiteral;
                }
                else if (_memberInfo is PropertyInfo)
234
                {
T
tanghai 已提交
235 236 237 238 239 240 241 242 243 244
                    var property = (PropertyInfo)_memberInfo;
                    return !property.CanWrite;
                }
                else
                {
                    throw new NotSupportedException(
                       string.Format("Only fields and properties are supported by BsonMemberMap. The member {0} of class {1} is a {2}.",
                       _memberInfo.Name,
                       _memberInfo.DeclaringType.Name,
                       _memberInfo is FieldInfo ? "field" : "property"));
245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272
                }
            }
        }

        // public methods
        /// <summary>
        /// Applies the default value to the member of an object.
        /// </summary>
        /// <param name="obj">The object.</param>
        public void ApplyDefaultValue(object obj)
        {
            if (_defaultValueSpecified)
            {
                this.Setter(obj, DefaultValue);
            }
        }

        /// <summary>
        /// Freezes this instance.
        /// </summary>
        public void Freeze()
        {
            _frozen = true;
        }

        /// <summary>
        /// Gets the serializer.
        /// </summary>
T
tanghai 已提交
273 274
        /// <returns>The serializer.</returns>
        public IBsonSerializer GetSerializer()
275
        {
T
tanghai 已提交
276
            if (_serializer == null)
277 278 279 280
            {
                // return special serializer for BsonValue members that handles the _csharpnull representation
                if (_memberTypeIsBsonValue)
                {
T
tanghai 已提交
281 282 283
                    var wrappedSerializer = BsonSerializer.LookupSerializer(_memberType);
                    var isBsonArraySerializer = wrappedSerializer is IBsonArraySerializer;
                    var isBsonDocumentSerializer = wrappedSerializer is IBsonDocumentSerializer;
284

T
tanghai 已提交
285 286 287 288 289 290
                    Type csharpNullSerializerDefinition;
                    if (isBsonArraySerializer && isBsonDocumentSerializer)
                    {
                        csharpNullSerializerDefinition = typeof(BsonValueCSharpNullArrayAndDocumentSerializer<>);
                    }
                    else if (isBsonArraySerializer)
291
                    {
T
tanghai 已提交
292
                        csharpNullSerializerDefinition = typeof(BsonValueCSharpNullArraySerializer<>);
293
                    }
T
tanghai 已提交
294 295 296 297 298 299 300 301 302 303 304 305
                    else if (isBsonDocumentSerializer)
                    {
                        csharpNullSerializerDefinition = typeof(BsonValueCSharpNullDocumentSerializer<>);
                    }
                    else
                    {
                        csharpNullSerializerDefinition = typeof(BsonValueCSharpNullSerializer<>);
                    }

                    var csharpNullSerializerType = csharpNullSerializerDefinition.MakeGenericType(_memberType);
                    var csharpNullSerializer = (IBsonSerializer)Activator.CreateInstance(csharpNullSerializerType, wrappedSerializer);
                    _serializer = csharpNullSerializer;
306 307 308
                }
                else
                {
T
tanghai 已提交
309
                    _serializer = BsonSerializer.LookupSerializer(_memberType);
310 311
                }
            }
T
tanghai 已提交
312
            return _serializer;
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464
        }

        /// <summary>
        /// Resets the member map back to its initial state.
        /// </summary>
        /// <returns>The member map.</returns>
        public BsonMemberMap Reset()
        {
            if (_frozen) { ThrowFrozenException(); }

            _defaultValue = GetDefaultValue(_memberType);
            _defaultValueCreator = null;
            _defaultValueSpecified = false;
            _elementName = _memberInfo.Name;
            _idGenerator = null;
            _ignoreIfDefault = false;
            _ignoreIfNull = false;
            _isRequired = false;
            _order = int.MaxValue;
            _serializer = null;
            _shouldSerializeMethod = null;

            return this;
        }

        /// <summary>
        /// Sets the default value creator.
        /// </summary>
        /// <param name="defaultValueCreator">The default value creator (note: the supplied delegate must be thread safe).</param>
        /// <returns>The member map.</returns>
        public BsonMemberMap SetDefaultValue(Func<object> defaultValueCreator)
        {
            if (defaultValueCreator == null)
            {
                throw new ArgumentNullException("defaultValueCreator");
            }
            if (_frozen) { ThrowFrozenException(); }
            _defaultValue = defaultValueCreator(); // need an instance to compare against
            _defaultValueCreator = defaultValueCreator;
            _defaultValueSpecified = true;
            return this;
        }

        /// <summary>
        /// Sets the default value.
        /// </summary>
        /// <param name="defaultValue">The default value.</param>
        /// <returns>The member map.</returns>
        public BsonMemberMap SetDefaultValue(object defaultValue)
        {
            if (_frozen) { ThrowFrozenException(); }
            _defaultValue = defaultValue;
            _defaultValueCreator = null;
            _defaultValueSpecified = true;
            return this;
        }

        /// <summary>
        /// Sets the name of the element.
        /// </summary>
        /// <param name="elementName">The name of the element.</param>
        /// <returns>The member map.</returns>
        public BsonMemberMap SetElementName(string elementName)
        {
            if (elementName == null)
            {
                throw new ArgumentNullException("elementName");
            }
            if (elementName.IndexOf('\0') != -1)
            {
                throw new ArgumentException("Element names cannot contain nulls.", "elementName");
            }
            if (_frozen) { ThrowFrozenException(); }

            _elementName = elementName;
            return this;
        }

        /// <summary>
        /// Sets the Id generator.
        /// </summary>
        /// <param name="idGenerator">The Id generator.</param>
        /// <returns>The member map.</returns>
        public BsonMemberMap SetIdGenerator(IIdGenerator idGenerator)
        {
            if (_frozen) { ThrowFrozenException(); }
            _idGenerator = idGenerator;
            return this;
        }

        /// <summary>
        /// Sets whether default values should be ignored when serialized.
        /// </summary>
        /// <param name="ignoreIfDefault">Whether default values should be ignored when serialized.</param>
        /// <returns>The member map.</returns>
        public BsonMemberMap SetIgnoreIfDefault(bool ignoreIfDefault)
        {
            if (_frozen) { ThrowFrozenException(); }
            if (ignoreIfDefault && _ignoreIfNull)
            {
                throw new InvalidOperationException("IgnoreIfDefault and IgnoreIfNull are mutually exclusive. Choose one or the other.");
            }

            _ignoreIfDefault = ignoreIfDefault;
            return this;
        }

        /// <summary>
        /// Sets whether null values should be ignored when serialized.
        /// </summary>
        /// <param name="ignoreIfNull">Wether null values should be ignored when serialized.</param>
        /// <returns>The member map.</returns>
        public BsonMemberMap SetIgnoreIfNull(bool ignoreIfNull)
        {
            if (_frozen) { ThrowFrozenException(); }

            if (ignoreIfNull && _ignoreIfDefault)
            {
                throw new InvalidOperationException("IgnoreIfDefault and IgnoreIfNull are mutually exclusive. Choose one or the other.");
            }
            _ignoreIfNull = ignoreIfNull;
            return this;
        }

        /// <summary>
        /// Sets whether an element is required for this member when deserialized
        /// </summary>
        /// <param name="isRequired">Whether an element is required for this member when deserialized</param>
        /// <returns>The member map.</returns>
        public BsonMemberMap SetIsRequired(bool isRequired)
        {
            if (_frozen) { ThrowFrozenException(); }
            _isRequired = isRequired;
            return this;
        }

        /// <summary>
        /// Sets the serialization order.
        /// </summary>
        /// <param name="order">The serialization order.</param>
        /// <returns>The member map.</returns>
        public BsonMemberMap SetOrder(int order)
        {
            if (_frozen) { ThrowFrozenException(); }
            _order = order;
            return this;
        }

        /// <summary>
        /// Sets the serializer.
        /// </summary>
        /// <param name="serializer">The serializer.</param>
T
tanghai 已提交
465 466 467 468 469
        /// <returns>
        /// The member map.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">serializer</exception>
        /// <exception cref="System.ArgumentException">serializer</exception>
470 471
        public BsonMemberMap SetSerializer(IBsonSerializer serializer)
        {
T
tanghai 已提交
472 473 474 475 476 477 478 479 480 481
            if (serializer == null)
            {
                throw new ArgumentNullException("serializer");
            }
            if (serializer.ValueType != _memberType)
            {
                var message = string.Format("Value type of serializer is {0} and does not match member type {1}.", serializer.ValueType.FullName, _memberType.FullName);
                throw new ArgumentException(message, "serializer");
            }

482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534
            if (_frozen) { ThrowFrozenException(); }
            _serializer = serializer;
            return this;
        }

        /// <summary>
        /// Sets the method that will be called to determine whether the member should be serialized.
        /// </summary>
        /// <param name="shouldSerializeMethod">The method.</param>
        /// <returns>The member map.</returns>
        public BsonMemberMap SetShouldSerializeMethod(Func<object, bool> shouldSerializeMethod)
        {
            if (_frozen) { ThrowFrozenException(); }
            _shouldSerializeMethod = shouldSerializeMethod;
            return this;
        }

        /// <summary>
        /// Determines whether a value should be serialized
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="value">The value.</param>
        /// <returns>True if the value should be serialized.</returns>
        public bool ShouldSerialize(object obj, object value)
        {
            if (_ignoreIfNull)
            {
                if (value == null)
                {
                    return false; // don't serialize null
                }
            }

            if (_ignoreIfDefault)
            {
                if (object.Equals(_defaultValue, value))
                {
                    return false; // don't serialize default value
                }
            }

            if (_shouldSerializeMethod != null && !_shouldSerializeMethod(obj))
            {
                // the _shouldSerializeMethod determined that the member shouldn't be serialized
                return false;
            }

            return true;
        }

        // private methods
        private static object GetDefaultValue(Type type)
        {
T
tanghai 已提交
535 536
            var typeInfo = type.GetTypeInfo();
            if (typeInfo.IsEnum)
537 538 539 540 541 542 543
            {
                return Enum.ToObject(type, 0);
            }

            switch (Type.GetTypeCode(type))
            {
                case TypeCode.Empty:
T
tanghai 已提交
544
#if NET45
545
                case TypeCode.DBNull:
T
tanghai 已提交
546
#endif
547 548 549
                case TypeCode.String:
                    break;
                case TypeCode.Object:
T
tanghai 已提交
550
                    if (typeInfo.IsValueType)
551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
                    {
                        return Activator.CreateInstance(type);
                    }
                    break;
                case TypeCode.Boolean: return false;
                case TypeCode.Char: return '\0';
                case TypeCode.SByte: return (sbyte)0;
                case TypeCode.Byte: return (byte)0;
                case TypeCode.Int16: return (short)0;
                case TypeCode.UInt16: return (ushort)0;
                case TypeCode.Int32: return 0;
                case TypeCode.UInt32: return 0U;
                case TypeCode.Int64: return 0L;
                case TypeCode.UInt64: return 0UL;
                case TypeCode.Single: return 0F;
                case TypeCode.Double: return 0D;
                case TypeCode.Decimal: return 0M;
                case TypeCode.DateTime: return DateTime.MinValue;
            }
            return null;
        }

        private Action<object, object> GetFieldSetter()
        {
            var fieldInfo = (FieldInfo)_memberInfo;

            if (IsReadOnly)
            {
                var message = string.Format(
                    "The field '{0} {1}' of class '{2}' is readonly. To avoid this exception, call IsReadOnly to ensure that setting a value is allowed.",
                    fieldInfo.FieldType.FullName, fieldInfo.Name, fieldInfo.DeclaringType.FullName);
                throw new BsonSerializationException(message);
            }

T
tanghai 已提交
585
#if ENABLE_IL2CPP
586
	        return (obj, value) => { fieldInfo.SetValue(obj, value); };
T
tanghai 已提交
587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
#else
			var sourceType = fieldInfo.DeclaringType;
			var method = new DynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(object), typeof(object) }, true);
			var gen = method.GetILGenerator();
			
			gen.Emit(OpCodes.Ldarg_0);
			gen.Emit(OpCodes.Castclass, sourceType);
			gen.Emit(OpCodes.Ldarg_1);
			gen.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType);
			gen.Emit(OpCodes.Stfld, fieldInfo);
			gen.Emit(OpCodes.Ret);
			
			return (Action<object, object>)method.CreateDelegate(typeof(Action<object, object>));
#endif
		}
602

T
tanghai 已提交
603
		private Func<object, object> GetGetter()
604
        {
T
tanghai 已提交
605
#if ENABLE_IL2CPP
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621
            PropertyInfo propertyInfo = _memberInfo as PropertyInfo;
            if (propertyInfo != null)
            {
                MethodInfo getMethodInfo = propertyInfo.GetGetMethod();
                if (getMethodInfo == null)
                {
                    var message = string.Format(
                        "The property '{0} {1}' of class '{2}' has no 'get' accessor.",
                        propertyInfo.PropertyType.FullName, propertyInfo.Name, propertyInfo.DeclaringType.FullName);
                    throw new BsonSerializationException(message);
                }
                return (obj) => { return getMethodInfo.Invoke(obj, null); };
            }

            FieldInfo fieldInfo = _memberInfo as FieldInfo;
            return (obj) => { return fieldInfo.GetValue(obj); };
T
tanghai 已提交
622
#else
T
tanghai 已提交
623
			var propertyInfo = _memberInfo as PropertyInfo;
624 625
            if (propertyInfo != null)
            {
T
tanghai 已提交
626
                var getMethodInfo = propertyInfo.GetMethod;
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649
                if (getMethodInfo == null)
                {
                    var message = string.Format(
                        "The property '{0} {1}' of class '{2}' has no 'get' accessor.",
                        propertyInfo.PropertyType.FullName, propertyInfo.Name, propertyInfo.DeclaringType.FullName);
                    throw new BsonSerializationException(message);
                }
            }

            // lambdaExpression = (obj) => (object) ((TClass) obj).Member
            var objParameter = Expression.Parameter(typeof(object), "obj");
            var lambdaExpression = Expression.Lambda<Func<object, object>>(
                Expression.Convert(
                    Expression.MakeMemberAccess(
                        Expression.Convert(objParameter, _memberInfo.DeclaringType),
                        _memberInfo
                    ),
                    typeof(object)
                ),
                objParameter
            );

            return lambdaExpression.Compile();
T
tanghai 已提交
650
#endif
651 652
        }

653

654 655
        private Action<object, object> GetPropertySetter()
        {
T
tanghai 已提交
656
#if ENABLE_IL2CPP
657 658 659
            var propertyInfo = (PropertyInfo) _memberInfo;

            return (obj, value) => { propertyInfo.SetValue(obj, value); };
T
tanghai 已提交
660
#else
T
tanghai 已提交
661
			var propertyInfo = (PropertyInfo)_memberInfo;
T
tanghai 已提交
662
            var setMethodInfo = propertyInfo.SetMethod;
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684
            if (IsReadOnly)
            {
                var message = string.Format(
                    "The property '{0} {1}' of class '{2}' has no 'set' accessor. To avoid this exception, call IsReadOnly to ensure that setting a value is allowed.",
                    propertyInfo.PropertyType.FullName, propertyInfo.Name, propertyInfo.DeclaringType.FullName);
                throw new BsonSerializationException(message);
            }

            // lambdaExpression = (obj, value) => ((TClass) obj).SetMethod((TMember) value)
            var objParameter = Expression.Parameter(typeof(object), "obj");
            var valueParameter = Expression.Parameter(typeof(object), "value");
            var lambdaExpression = Expression.Lambda<Action<object, object>>(
                Expression.Call(
                    Expression.Convert(objParameter, _memberInfo.DeclaringType),
                    setMethodInfo,
                    Expression.Convert(valueParameter, _memberType)
                ),
                objParameter,
                valueParameter
            );

            return lambdaExpression.Compile();
T
tanghai 已提交
685
#endif
686 687 688 689 690 691 692 693 694
        }

        private void ThrowFrozenException()
        {
            var message = string.Format("Member map for {0}.{1} has been frozen and no further changes are allowed.", _classMap.ClassType.FullName, _memberInfo.Name);
            throw new InvalidOperationException(message);
        }
    }
}