BsonMemberMap.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692
  1. /* Copyright 2010-2014 MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Linq.Expressions;
  17. using System.Reflection;
  18. using System.Reflection.Emit;
  19. using MongoDB.Bson.Serialization.Conventions;
  20. using MongoDB.Bson.Serialization.Options;
  21. using MongoDB.Bson.Serialization.Serializers;
  22. namespace MongoDB.Bson.Serialization
  23. {
  24. /// <summary>
  25. /// Represents the mapping between a field or property and a BSON element.
  26. /// </summary>
  27. public class BsonMemberMap
  28. {
  29. // private fields
  30. private readonly BsonClassMap _classMap;
  31. private readonly MemberInfo _memberInfo;
  32. private readonly Type _memberType;
  33. private readonly bool _memberTypeIsBsonValue;
  34. private string _elementName;
  35. private bool _frozen; // once a class map has been frozen no further changes are allowed
  36. private int _order;
  37. private Func<object, object> _getter;
  38. private Action<object, object> _setter;
  39. private IBsonSerializationOptions _serializationOptions;
  40. private IBsonSerializer _serializer;
  41. private volatile IDiscriminatorConvention _cachedDiscriminatorConvention;
  42. private volatile IBsonSerializer _cachedSerializer;
  43. private IIdGenerator _idGenerator;
  44. private bool _isRequired;
  45. private Func<object, bool> _shouldSerializeMethod;
  46. private bool _ignoreIfDefault;
  47. private bool _ignoreIfNull;
  48. private object _defaultValue;
  49. private Func<object> _defaultValueCreator;
  50. private bool _defaultValueSpecified;
  51. // constructors
  52. /// <summary>
  53. /// Initializes a new instance of the BsonMemberMap class.
  54. /// </summary>
  55. /// <param name="classMap">The class map this member map belongs to.</param>
  56. /// <param name="memberInfo">The member info.</param>
  57. public BsonMemberMap(BsonClassMap classMap, MemberInfo memberInfo)
  58. {
  59. _classMap = classMap;
  60. _memberInfo = memberInfo;
  61. _memberType = BsonClassMap.GetMemberInfoType(memberInfo);
  62. _memberTypeIsBsonValue = typeof(BsonValue).IsAssignableFrom(_memberType);
  63. Reset();
  64. }
  65. // public properties
  66. /// <summary>
  67. /// Gets the class map that this member map belongs to.
  68. /// </summary>
  69. public BsonClassMap ClassMap
  70. {
  71. get { return _classMap; }
  72. }
  73. /// <summary>
  74. /// Gets the name of the member.
  75. /// </summary>
  76. public string MemberName
  77. {
  78. get { return _memberInfo.Name; }
  79. }
  80. /// <summary>
  81. /// Gets the type of the member.
  82. /// </summary>
  83. public Type MemberType
  84. {
  85. get { return _memberType; }
  86. }
  87. /// <summary>
  88. /// Gets whether the member type is a BsonValue.
  89. /// </summary>
  90. public bool MemberTypeIsBsonValue
  91. {
  92. get { return _memberTypeIsBsonValue; }
  93. }
  94. /// <summary>
  95. /// Gets the name of the element.
  96. /// </summary>
  97. public string ElementName
  98. {
  99. get { return _elementName; }
  100. }
  101. /// <summary>
  102. /// Gets the serialization order.
  103. /// </summary>
  104. public int Order
  105. {
  106. get { return _order; }
  107. }
  108. /// <summary>
  109. /// Gets the member info.
  110. /// </summary>
  111. public MemberInfo MemberInfo
  112. {
  113. get { return _memberInfo; }
  114. }
  115. /// <summary>
  116. /// Gets the getter function.
  117. /// </summary>
  118. public Func<object, object> Getter
  119. {
  120. get
  121. {
  122. if (_getter == null)
  123. {
  124. _getter = GetGetter();
  125. }
  126. return _getter;
  127. }
  128. }
  129. /// <summary>
  130. /// Gets the serialization options.
  131. /// </summary>
  132. public IBsonSerializationOptions SerializationOptions
  133. {
  134. get { return _serializationOptions; }
  135. }
  136. /// <summary>
  137. /// Gets the setter function.
  138. /// </summary>
  139. public Action<object, object> Setter
  140. {
  141. get
  142. {
  143. if (_setter == null)
  144. {
  145. if (_memberInfo.MemberType == MemberTypes.Field)
  146. {
  147. _setter = GetFieldSetter();
  148. }
  149. else
  150. {
  151. _setter = GetPropertySetter();
  152. }
  153. }
  154. return _setter;
  155. }
  156. }
  157. /// <summary>
  158. /// Gets the Id generator.
  159. /// </summary>
  160. public IIdGenerator IdGenerator
  161. {
  162. get { return _idGenerator; }
  163. }
  164. /// <summary>
  165. /// Gets whether a default value was specified.
  166. /// </summary>
  167. public bool IsDefaultValueSpecified
  168. {
  169. get { return _defaultValueSpecified; }
  170. }
  171. /// <summary>
  172. /// Gets whether an element is required for this member when deserialized.
  173. /// </summary>
  174. public bool IsRequired
  175. {
  176. get { return _isRequired; }
  177. }
  178. /// <summary>
  179. /// Gets the method that will be called to determine whether the member should be serialized.
  180. /// </summary>
  181. public Func<object, bool> ShouldSerializeMethod
  182. {
  183. get { return _shouldSerializeMethod; }
  184. }
  185. /// <summary>
  186. /// Gets whether default values should be ignored when serialized.
  187. /// </summary>
  188. public bool IgnoreIfDefault
  189. {
  190. get { return _ignoreIfDefault; }
  191. }
  192. /// <summary>
  193. /// Gets whether null values should be ignored when serialized.
  194. /// </summary>
  195. public bool IgnoreIfNull
  196. {
  197. get { return _ignoreIfNull; }
  198. }
  199. /// <summary>
  200. /// Gets the default value.
  201. /// </summary>
  202. public object DefaultValue
  203. {
  204. get { return _defaultValueCreator != null ? _defaultValueCreator() : _defaultValue; }
  205. }
  206. /// <summary>
  207. /// Gets whether the member is readonly.
  208. /// </summary>
  209. /// <remarks>
  210. /// Readonly indicates that the member is written to the database, but not read from the database.
  211. /// </remarks>
  212. public bool IsReadOnly
  213. {
  214. get
  215. {
  216. switch(_memberInfo.MemberType)
  217. {
  218. case MemberTypes.Field:
  219. var field = (FieldInfo)_memberInfo;
  220. return field.IsInitOnly || field.IsLiteral;
  221. case MemberTypes.Property:
  222. var property = (PropertyInfo)_memberInfo;
  223. return !property.CanWrite;
  224. default:
  225. throw new NotSupportedException(
  226. string.Format("Only fields and properties are supported by BsonMemberMap. The member {0} of class {1} is a {2}.",
  227. _memberInfo.Name,
  228. _memberInfo.DeclaringType.Name,
  229. _memberInfo.MemberType));
  230. }
  231. }
  232. }
  233. // public methods
  234. /// <summary>
  235. /// Applies the default value to the member of an object.
  236. /// </summary>
  237. /// <param name="obj">The object.</param>
  238. public void ApplyDefaultValue(object obj)
  239. {
  240. if (_defaultValueSpecified)
  241. {
  242. this.Setter(obj, DefaultValue);
  243. }
  244. }
  245. /// <summary>
  246. /// Freezes this instance.
  247. /// </summary>
  248. public void Freeze()
  249. {
  250. _frozen = true;
  251. }
  252. /// <summary>
  253. /// Gets the serializer.
  254. /// </summary>
  255. /// <param name="actualType">The actual type of the member's value.</param>
  256. /// <returns>The member map.</returns>
  257. public IBsonSerializer GetSerializer(Type actualType)
  258. {
  259. // if a custom serializer is configured always return it
  260. if (_serializer != null)
  261. {
  262. return _serializer;
  263. }
  264. else
  265. {
  266. // return special serializer for BsonValue members that handles the _csharpnull representation
  267. if (_memberTypeIsBsonValue)
  268. {
  269. return BsonValueCSharpNullSerializer.Instance;
  270. }
  271. // return a cached serializer when possible
  272. if (actualType == _memberType)
  273. {
  274. var serializer = _cachedSerializer;
  275. if (serializer == null)
  276. {
  277. // it's possible but harmless for multiple threads to do the initial lookup at the same time
  278. serializer = BsonSerializer.LookupSerializer(_memberType);
  279. _cachedSerializer = serializer;
  280. }
  281. return serializer;
  282. }
  283. else
  284. {
  285. return BsonSerializer.LookupSerializer(actualType);
  286. }
  287. }
  288. }
  289. /// <summary>
  290. /// Resets the member map back to its initial state.
  291. /// </summary>
  292. /// <returns>The member map.</returns>
  293. public BsonMemberMap Reset()
  294. {
  295. if (_frozen) { ThrowFrozenException(); }
  296. _defaultValue = GetDefaultValue(_memberType);
  297. _defaultValueCreator = null;
  298. _defaultValueSpecified = false;
  299. _elementName = _memberInfo.Name;
  300. _idGenerator = null;
  301. _ignoreIfDefault = false;
  302. _ignoreIfNull = false;
  303. _isRequired = false;
  304. _order = int.MaxValue;
  305. _serializationOptions = null;
  306. _serializer = null;
  307. _shouldSerializeMethod = null;
  308. return this;
  309. }
  310. /// <summary>
  311. /// Sets the default value creator.
  312. /// </summary>
  313. /// <param name="defaultValueCreator">The default value creator (note: the supplied delegate must be thread safe).</param>
  314. /// <returns>The member map.</returns>
  315. public BsonMemberMap SetDefaultValue(Func<object> defaultValueCreator)
  316. {
  317. if (defaultValueCreator == null)
  318. {
  319. throw new ArgumentNullException("defaultValueCreator");
  320. }
  321. if (_frozen) { ThrowFrozenException(); }
  322. _defaultValue = defaultValueCreator(); // need an instance to compare against
  323. _defaultValueCreator = defaultValueCreator;
  324. _defaultValueSpecified = true;
  325. return this;
  326. }
  327. /// <summary>
  328. /// Sets the default value.
  329. /// </summary>
  330. /// <param name="defaultValue">The default value.</param>
  331. /// <returns>The member map.</returns>
  332. public BsonMemberMap SetDefaultValue(object defaultValue)
  333. {
  334. if (_frozen) { ThrowFrozenException(); }
  335. _defaultValue = defaultValue;
  336. _defaultValueCreator = null;
  337. _defaultValueSpecified = true;
  338. return this;
  339. }
  340. /// <summary>
  341. /// Sets the name of the element.
  342. /// </summary>
  343. /// <param name="elementName">The name of the element.</param>
  344. /// <returns>The member map.</returns>
  345. public BsonMemberMap SetElementName(string elementName)
  346. {
  347. if (elementName == null)
  348. {
  349. throw new ArgumentNullException("elementName");
  350. }
  351. if (elementName.IndexOf('\0') != -1)
  352. {
  353. throw new ArgumentException("Element names cannot contain nulls.", "elementName");
  354. }
  355. if (_frozen) { ThrowFrozenException(); }
  356. _elementName = elementName;
  357. return this;
  358. }
  359. /// <summary>
  360. /// Sets the Id generator.
  361. /// </summary>
  362. /// <param name="idGenerator">The Id generator.</param>
  363. /// <returns>The member map.</returns>
  364. public BsonMemberMap SetIdGenerator(IIdGenerator idGenerator)
  365. {
  366. if (_frozen) { ThrowFrozenException(); }
  367. _idGenerator = idGenerator;
  368. return this;
  369. }
  370. /// <summary>
  371. /// Sets whether default values should be ignored when serialized.
  372. /// </summary>
  373. /// <param name="ignoreIfDefault">Whether default values should be ignored when serialized.</param>
  374. /// <returns>The member map.</returns>
  375. public BsonMemberMap SetIgnoreIfDefault(bool ignoreIfDefault)
  376. {
  377. if (_frozen) { ThrowFrozenException(); }
  378. if (ignoreIfDefault && _ignoreIfNull)
  379. {
  380. throw new InvalidOperationException("IgnoreIfDefault and IgnoreIfNull are mutually exclusive. Choose one or the other.");
  381. }
  382. _ignoreIfDefault = ignoreIfDefault;
  383. return this;
  384. }
  385. /// <summary>
  386. /// Sets whether null values should be ignored when serialized.
  387. /// </summary>
  388. /// <param name="ignoreIfNull">Wether null values should be ignored when serialized.</param>
  389. /// <returns>The member map.</returns>
  390. public BsonMemberMap SetIgnoreIfNull(bool ignoreIfNull)
  391. {
  392. if (_frozen) { ThrowFrozenException(); }
  393. if (ignoreIfNull && _ignoreIfDefault)
  394. {
  395. throw new InvalidOperationException("IgnoreIfDefault and IgnoreIfNull are mutually exclusive. Choose one or the other.");
  396. }
  397. _ignoreIfNull = ignoreIfNull;
  398. return this;
  399. }
  400. /// <summary>
  401. /// Sets whether an element is required for this member when deserialized
  402. /// </summary>
  403. /// <param name="isRequired">Whether an element is required for this member when deserialized</param>
  404. /// <returns>The member map.</returns>
  405. public BsonMemberMap SetIsRequired(bool isRequired)
  406. {
  407. if (_frozen) { ThrowFrozenException(); }
  408. _isRequired = isRequired;
  409. return this;
  410. }
  411. /// <summary>
  412. /// Sets the serialization order.
  413. /// </summary>
  414. /// <param name="order">The serialization order.</param>
  415. /// <returns>The member map.</returns>
  416. public BsonMemberMap SetOrder(int order)
  417. {
  418. if (_frozen) { ThrowFrozenException(); }
  419. _order = order;
  420. return this;
  421. }
  422. /// <summary>
  423. /// Sets the external representation.
  424. /// </summary>
  425. /// <param name="representation">The external representation.</param>
  426. /// <returns>The member map.</returns>
  427. public BsonMemberMap SetRepresentation(BsonType representation)
  428. {
  429. if (_frozen) { ThrowFrozenException(); }
  430. _serializationOptions = new RepresentationSerializationOptions(representation);
  431. return this;
  432. }
  433. /// <summary>
  434. /// Sets the serialization options.
  435. /// </summary>
  436. /// <param name="serializationOptions">The serialization options.</param>
  437. /// <returns>The member map.</returns>
  438. public BsonMemberMap SetSerializationOptions(IBsonSerializationOptions serializationOptions)
  439. {
  440. if (_frozen) { ThrowFrozenException(); }
  441. _serializationOptions = serializationOptions;
  442. return this;
  443. }
  444. /// <summary>
  445. /// Sets the serializer.
  446. /// </summary>
  447. /// <param name="serializer">The serializer.</param>
  448. /// <returns>The member map.</returns>
  449. public BsonMemberMap SetSerializer(IBsonSerializer serializer)
  450. {
  451. if (_frozen) { ThrowFrozenException(); }
  452. _serializer = serializer;
  453. return this;
  454. }
  455. /// <summary>
  456. /// Sets the method that will be called to determine whether the member should be serialized.
  457. /// </summary>
  458. /// <param name="shouldSerializeMethod">The method.</param>
  459. /// <returns>The member map.</returns>
  460. public BsonMemberMap SetShouldSerializeMethod(Func<object, bool> shouldSerializeMethod)
  461. {
  462. if (_frozen) { ThrowFrozenException(); }
  463. _shouldSerializeMethod = shouldSerializeMethod;
  464. return this;
  465. }
  466. /// <summary>
  467. /// Determines whether a value should be serialized
  468. /// </summary>
  469. /// <param name="obj">The object.</param>
  470. /// <param name="value">The value.</param>
  471. /// <returns>True if the value should be serialized.</returns>
  472. public bool ShouldSerialize(object obj, object value)
  473. {
  474. if (_ignoreIfNull)
  475. {
  476. if (value == null)
  477. {
  478. return false; // don't serialize null
  479. }
  480. }
  481. if (_ignoreIfDefault)
  482. {
  483. if (object.Equals(_defaultValue, value))
  484. {
  485. return false; // don't serialize default value
  486. }
  487. }
  488. if (_shouldSerializeMethod != null && !_shouldSerializeMethod(obj))
  489. {
  490. // the _shouldSerializeMethod determined that the member shouldn't be serialized
  491. return false;
  492. }
  493. return true;
  494. }
  495. // internal methods
  496. /// <summary>
  497. /// Gets the discriminator convention for the member type.
  498. /// </summary>
  499. /// <returns>The discriminator convention for the member type.</returns>
  500. internal IDiscriminatorConvention GetDiscriminatorConvention()
  501. {
  502. // return a cached discriminator convention when possible
  503. var discriminatorConvention = _cachedDiscriminatorConvention;
  504. if (discriminatorConvention == null)
  505. {
  506. // it's possible but harmless for multiple threads to do the initial lookup at the same time
  507. discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(_memberType);
  508. _cachedDiscriminatorConvention = discriminatorConvention;
  509. }
  510. return discriminatorConvention;
  511. }
  512. // private methods
  513. private static object GetDefaultValue(Type type)
  514. {
  515. if (type.IsEnum)
  516. {
  517. return Enum.ToObject(type, 0);
  518. }
  519. switch (Type.GetTypeCode(type))
  520. {
  521. case TypeCode.Empty:
  522. case TypeCode.DBNull:
  523. case TypeCode.String:
  524. break;
  525. case TypeCode.Object:
  526. if (type.IsValueType)
  527. {
  528. return Activator.CreateInstance(type);
  529. }
  530. break;
  531. case TypeCode.Boolean: return false;
  532. case TypeCode.Char: return '\0';
  533. case TypeCode.SByte: return (sbyte)0;
  534. case TypeCode.Byte: return (byte)0;
  535. case TypeCode.Int16: return (short)0;
  536. case TypeCode.UInt16: return (ushort)0;
  537. case TypeCode.Int32: return 0;
  538. case TypeCode.UInt32: return 0U;
  539. case TypeCode.Int64: return 0L;
  540. case TypeCode.UInt64: return 0UL;
  541. case TypeCode.Single: return 0F;
  542. case TypeCode.Double: return 0D;
  543. case TypeCode.Decimal: return 0M;
  544. case TypeCode.DateTime: return DateTime.MinValue;
  545. }
  546. return null;
  547. }
  548. private Action<object, object> GetFieldSetter()
  549. {
  550. var fieldInfo = (FieldInfo)_memberInfo;
  551. if (IsReadOnly)
  552. {
  553. var message = string.Format(
  554. "The field '{0} {1}' of class '{2}' is readonly. To avoid this exception, call IsReadOnly to ensure that setting a value is allowed.",
  555. fieldInfo.FieldType.FullName, fieldInfo.Name, fieldInfo.DeclaringType.FullName);
  556. throw new BsonSerializationException(message);
  557. }
  558. var sourceType = fieldInfo.DeclaringType;
  559. var method = new DynamicMethod("Set" + fieldInfo.Name, null, new[] { typeof(object), typeof(object) }, true);
  560. var gen = method.GetILGenerator();
  561. gen.Emit(OpCodes.Ldarg_0);
  562. gen.Emit(OpCodes.Castclass, sourceType);
  563. gen.Emit(OpCodes.Ldarg_1);
  564. gen.Emit(OpCodes.Unbox_Any, fieldInfo.FieldType);
  565. gen.Emit(OpCodes.Stfld, fieldInfo);
  566. gen.Emit(OpCodes.Ret);
  567. return (Action<object, object>)method.CreateDelegate(typeof(Action<object, object>));
  568. }
  569. private Func<object, object> GetGetter()
  570. {
  571. var propertyInfo = _memberInfo as PropertyInfo;
  572. if (propertyInfo != null)
  573. {
  574. var getMethodInfo = propertyInfo.GetGetMethod(true);
  575. if (getMethodInfo == null)
  576. {
  577. var message = string.Format(
  578. "The property '{0} {1}' of class '{2}' has no 'get' accessor.",
  579. propertyInfo.PropertyType.FullName, propertyInfo.Name, propertyInfo.DeclaringType.FullName);
  580. throw new BsonSerializationException(message);
  581. }
  582. }
  583. // lambdaExpression = (obj) => (object) ((TClass) obj).Member
  584. var objParameter = Expression.Parameter(typeof(object), "obj");
  585. var lambdaExpression = Expression.Lambda<Func<object, object>>(
  586. Expression.Convert(
  587. Expression.MakeMemberAccess(
  588. Expression.Convert(objParameter, _memberInfo.DeclaringType),
  589. _memberInfo
  590. ),
  591. typeof(object)
  592. ),
  593. objParameter
  594. );
  595. return lambdaExpression.Compile();
  596. }
  597. private Action<object, object> GetPropertySetter()
  598. {
  599. var propertyInfo = (PropertyInfo)_memberInfo;
  600. var setMethodInfo = propertyInfo.GetSetMethod(true);
  601. if (IsReadOnly)
  602. {
  603. var message = string.Format(
  604. "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.",
  605. propertyInfo.PropertyType.FullName, propertyInfo.Name, propertyInfo.DeclaringType.FullName);
  606. throw new BsonSerializationException(message);
  607. }
  608. // lambdaExpression = (obj, value) => ((TClass) obj).SetMethod((TMember) value)
  609. var objParameter = Expression.Parameter(typeof(object), "obj");
  610. var valueParameter = Expression.Parameter(typeof(object), "value");
  611. var lambdaExpression = Expression.Lambda<Action<object, object>>(
  612. Expression.Call(
  613. Expression.Convert(objParameter, _memberInfo.DeclaringType),
  614. setMethodInfo,
  615. Expression.Convert(valueParameter, _memberType)
  616. ),
  617. objParameter,
  618. valueParameter
  619. );
  620. return lambdaExpression.Compile();
  621. }
  622. private void ThrowFrozenException()
  623. {
  624. var message = string.Format("Member map for {0}.{1} has been frozen and no further changes are allowed.", _classMap.ClassType.FullName, _memberInfo.Name);
  625. throw new InvalidOperationException(message);
  626. }
  627. }
  628. }