BsonClassMap.cs 63 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623
  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.Collections.Generic;
  17. using System.Collections.ObjectModel;
  18. using System.Linq;
  19. using System.Linq.Expressions;
  20. using System.Reflection;
  21. using System.Runtime.CompilerServices;
  22. using System.Runtime.Serialization;
  23. using MongoDB.Bson.IO;
  24. using MongoDB.Bson.Serialization.Conventions;
  25. namespace MongoDB.Bson.Serialization
  26. {
  27. /// <summary>
  28. /// Represents a mapping between a class and a BSON document.
  29. /// </summary>
  30. public abstract class BsonClassMap
  31. {
  32. // private static fields
  33. private readonly static Dictionary<Type, BsonClassMap> __classMaps = new Dictionary<Type, BsonClassMap>();
  34. private readonly static Queue<Type> __knownTypesQueue = new Queue<Type>();
  35. private static int __freezeNestingLevel = 0;
  36. // private fields
  37. private bool _frozen; // once a class map has been frozen no further changes are allowed
  38. private BsonClassMap _baseClassMap; // null for class object and interfaces
  39. private Type _classType;
  40. private volatile IDiscriminatorConvention _cachedDiscriminatorConvention;
  41. private readonly List<BsonCreatorMap> _creatorMaps;
  42. private Func<object> _creator;
  43. private IConventionPack _conventionPack;
  44. private string _discriminator;
  45. private bool _discriminatorIsRequired;
  46. private bool _hasRootClass;
  47. private bool _isRootClass;
  48. private bool _isAnonymous;
  49. private BsonMemberMap _idMemberMap;
  50. private readonly List<BsonMemberMap> _allMemberMaps; // includes inherited member maps
  51. private readonly ReadOnlyCollection<BsonMemberMap> _allMemberMapsReadonly;
  52. private readonly List<BsonMemberMap> _declaredMemberMaps; // only the members declared in this class
  53. private readonly BsonTrie<int> _elementTrie;
  54. private bool _ignoreExtraElements;
  55. private bool _ignoreExtraElementsIsInherited;
  56. private BsonMemberMap _extraElementsMemberMap;
  57. private int _extraElementsMemberIndex = -1;
  58. private List<Type> _knownTypes = new List<Type>();
  59. // constructors
  60. /// <summary>
  61. /// Initializes a new instance of the BsonClassMap class.
  62. /// </summary>
  63. /// <param name="classType">The class type.</param>
  64. protected BsonClassMap(Type classType)
  65. {
  66. _classType = classType;
  67. _creatorMaps = new List<BsonCreatorMap>();
  68. _conventionPack = ConventionRegistry.Lookup(classType);
  69. _isAnonymous = IsAnonymousType(classType);
  70. _allMemberMaps = new List<BsonMemberMap>();
  71. _allMemberMapsReadonly = _allMemberMaps.AsReadOnly();
  72. _declaredMemberMaps = new List<BsonMemberMap>();
  73. _elementTrie = new BsonTrie<int>();
  74. Reset();
  75. }
  76. // public properties
  77. /// <summary>
  78. /// Gets all the member maps (including maps for inherited members).
  79. /// </summary>
  80. public ReadOnlyCollection<BsonMemberMap> AllMemberMaps
  81. {
  82. get { return _allMemberMapsReadonly; }
  83. }
  84. /// <summary>
  85. /// Gets the base class map.
  86. /// </summary>
  87. public BsonClassMap BaseClassMap
  88. {
  89. get { return _baseClassMap; }
  90. }
  91. /// <summary>
  92. /// Gets the class type.
  93. /// </summary>
  94. public Type ClassType
  95. {
  96. get { return _classType; }
  97. }
  98. /// <summary>
  99. /// Gets the constructor maps.
  100. /// </summary>
  101. public IEnumerable<BsonCreatorMap> CreatorMaps
  102. {
  103. get { return _creatorMaps; }
  104. }
  105. /// <summary>
  106. /// Gets the conventions used for auto mapping.
  107. /// </summary>
  108. public IConventionPack ConventionPack
  109. {
  110. get { return _conventionPack; }
  111. }
  112. /// <summary>
  113. /// Gets the conventions used with this class.
  114. /// </summary>
  115. [Obsolete("Use ConventionPack instead.")]
  116. public ConventionProfile Conventions
  117. {
  118. get
  119. {
  120. var profile = _conventionPack as ConventionProfile;
  121. if (profile != null)
  122. {
  123. return profile;
  124. }
  125. throw new NotSupportedException("This class map was setup using an IConventionPack, part of the new conventions api. Use the ConventionPack property for access to the conventions.");
  126. }
  127. }
  128. /// <summary>
  129. /// Gets the declared member maps (only for members declared in this class).
  130. /// </summary>
  131. public IEnumerable<BsonMemberMap> DeclaredMemberMaps
  132. {
  133. get { return _declaredMemberMaps; }
  134. }
  135. /// <summary>
  136. /// Gets the discriminator.
  137. /// </summary>
  138. public string Discriminator
  139. {
  140. get { return _discriminator; }
  141. }
  142. /// <summary>
  143. /// Gets whether a discriminator is required when serializing this class.
  144. /// </summary>
  145. public bool DiscriminatorIsRequired
  146. {
  147. get { return _discriminatorIsRequired; }
  148. }
  149. /// <summary>
  150. /// Gets the member map of the member used to hold extra elements.
  151. /// </summary>
  152. public BsonMemberMap ExtraElementsMemberMap
  153. {
  154. get { return _extraElementsMemberMap; }
  155. }
  156. /// <summary>
  157. /// Gets whether this class map has any creator maps.
  158. /// </summary>
  159. public bool HasCreatorMaps
  160. {
  161. get { return _creatorMaps.Count > 0; }
  162. }
  163. /// <summary>
  164. /// Gets whether this class has a root class ancestor.
  165. /// </summary>
  166. public bool HasRootClass
  167. {
  168. get { return _hasRootClass; }
  169. }
  170. /// <summary>
  171. /// Gets the Id member map (null if none).
  172. /// </summary>
  173. public BsonMemberMap IdMemberMap
  174. {
  175. get { return _idMemberMap; }
  176. }
  177. /// <summary>
  178. /// Gets whether extra elements should be ignored when deserializing.
  179. /// </summary>
  180. public bool IgnoreExtraElements
  181. {
  182. get { return _ignoreExtraElements; }
  183. }
  184. /// <summary>
  185. /// Gets whether the IgnoreExtraElements value should be inherited by derived classes.
  186. /// </summary>
  187. public bool IgnoreExtraElementsIsInherited
  188. {
  189. get { return _ignoreExtraElementsIsInherited; }
  190. }
  191. /// <summary>
  192. /// Gets whether this class is anonymous.
  193. /// </summary>
  194. public bool IsAnonymous
  195. {
  196. get { return _isAnonymous; }
  197. }
  198. /// <summary>
  199. /// Gets whether the class map is frozen.
  200. /// </summary>
  201. public bool IsFrozen
  202. {
  203. get { return _frozen; }
  204. }
  205. /// <summary>
  206. /// Gets whether this class is a root class.
  207. /// </summary>
  208. public bool IsRootClass
  209. {
  210. get { return _isRootClass; }
  211. }
  212. /// <summary>
  213. /// Gets the known types of this class.
  214. /// </summary>
  215. public IEnumerable<Type> KnownTypes
  216. {
  217. get { return _knownTypes; }
  218. }
  219. // internal properties
  220. /// <summary>
  221. /// Gets the element name to member index trie.
  222. /// </summary>
  223. internal BsonTrie<int> ElementTrie
  224. {
  225. get { return _elementTrie; }
  226. }
  227. /// <summary>
  228. /// Gets the member index of the member used to hold extra elements.
  229. /// </summary>
  230. internal int ExtraElementsMemberMapIndex
  231. {
  232. get { return _extraElementsMemberIndex; }
  233. }
  234. // public static methods
  235. /// <summary>
  236. /// Gets the type of a member.
  237. /// </summary>
  238. /// <param name="memberInfo">The member info.</param>
  239. /// <returns>The type of the member.</returns>
  240. public static Type GetMemberInfoType(MemberInfo memberInfo)
  241. {
  242. if (memberInfo == null)
  243. {
  244. throw new ArgumentNullException("memberInfo");
  245. }
  246. if (memberInfo.MemberType == MemberTypes.Field)
  247. {
  248. return ((FieldInfo)memberInfo).FieldType;
  249. }
  250. else if (memberInfo.MemberType == MemberTypes.Property)
  251. {
  252. return ((PropertyInfo)memberInfo).PropertyType;
  253. }
  254. throw new NotSupportedException("Only field and properties are supported at this time.");
  255. }
  256. /// <summary>
  257. /// Gets all registered class maps.
  258. /// </summary>
  259. /// <returns>All registered class maps.</returns>
  260. public static IEnumerable<BsonClassMap> GetRegisteredClassMaps()
  261. {
  262. return __classMaps.Values;
  263. }
  264. /// <summary>
  265. /// Checks whether a class map is registered for a type.
  266. /// </summary>
  267. /// <param name="type">The type to check.</param>
  268. /// <returns>True if there is a class map registered for the type.</returns>
  269. public static bool IsClassMapRegistered(Type type)
  270. {
  271. if (type == null)
  272. {
  273. throw new ArgumentNullException("type");
  274. }
  275. BsonSerializer.ConfigLock.EnterReadLock();
  276. try
  277. {
  278. return __classMaps.ContainsKey(type);
  279. }
  280. finally
  281. {
  282. BsonSerializer.ConfigLock.ExitReadLock();
  283. }
  284. }
  285. /// <summary>
  286. /// Looks up a class map (will AutoMap the class if no class map is registered).
  287. /// </summary>
  288. /// <param name="classType">The class type.</param>
  289. /// <returns>The class map.</returns>
  290. public static BsonClassMap LookupClassMap(Type classType)
  291. {
  292. if (classType == null)
  293. {
  294. throw new ArgumentNullException("classType");
  295. }
  296. BsonSerializer.ConfigLock.EnterReadLock();
  297. try
  298. {
  299. BsonClassMap classMap;
  300. if (__classMaps.TryGetValue(classType, out classMap))
  301. {
  302. if (classMap.IsFrozen)
  303. {
  304. return classMap;
  305. }
  306. }
  307. }
  308. finally
  309. {
  310. BsonSerializer.ConfigLock.ExitReadLock();
  311. }
  312. BsonSerializer.ConfigLock.EnterWriteLock();
  313. try
  314. {
  315. BsonClassMap classMap;
  316. if (!__classMaps.TryGetValue(classType, out classMap))
  317. {
  318. // automatically create a classMap for classType and register it
  319. var classMapDefinition = typeof(BsonClassMap<>);
  320. var classMapType = classMapDefinition.MakeGenericType(classType);
  321. classMap = (BsonClassMap)Activator.CreateInstance(classMapType);
  322. classMap.AutoMap();
  323. RegisterClassMap(classMap);
  324. }
  325. return classMap.Freeze();
  326. }
  327. finally
  328. {
  329. BsonSerializer.ConfigLock.ExitWriteLock();
  330. }
  331. }
  332. /// <summary>
  333. /// Looks up the conventions profile for a type.
  334. /// </summary>
  335. /// <param name="type">The type.</param>
  336. /// <returns>The conventions profile for that type.</returns>
  337. [Obsolete("Use ConventionRegistry.Lookup instead.")]
  338. public static ConventionProfile LookupConventions(Type type)
  339. {
  340. var pack = ConventionRegistry.Lookup(type);
  341. var profile = pack as ConventionProfile;
  342. if (profile != null)
  343. {
  344. return profile;
  345. }
  346. var message = string.Format("Type {0} was setup using an IConventionPack, part of the new conventions api. Use the ConventionPack property for access to the conventions.", type);
  347. throw new NotSupportedException(message);
  348. }
  349. /// <summary>
  350. /// Creates and registers a class map.
  351. /// </summary>
  352. /// <typeparam name="TClass">The class.</typeparam>
  353. /// <returns>The class map.</returns>
  354. public static BsonClassMap<TClass> RegisterClassMap<TClass>()
  355. {
  356. return RegisterClassMap<TClass>(cm => { cm.AutoMap(); });
  357. }
  358. /// <summary>
  359. /// Creates and registers a class map.
  360. /// </summary>
  361. /// <typeparam name="TClass">The class.</typeparam>
  362. /// <param name="classMapInitializer">The class map initializer.</param>
  363. /// <returns>The class map.</returns>
  364. public static BsonClassMap<TClass> RegisterClassMap<TClass>(Action<BsonClassMap<TClass>> classMapInitializer)
  365. {
  366. var classMap = new BsonClassMap<TClass>(classMapInitializer);
  367. RegisterClassMap(classMap);
  368. return classMap;
  369. }
  370. /// <summary>
  371. /// Registers a class map.
  372. /// </summary>
  373. /// <param name="classMap">The class map.</param>
  374. public static void RegisterClassMap(BsonClassMap classMap)
  375. {
  376. if (classMap == null)
  377. {
  378. throw new ArgumentNullException("classMap");
  379. }
  380. BsonSerializer.ConfigLock.EnterWriteLock();
  381. try
  382. {
  383. // note: class maps can NOT be replaced (because derived classes refer to existing instance)
  384. __classMaps.Add(classMap.ClassType, classMap);
  385. BsonSerializer.RegisterDiscriminator(classMap.ClassType, classMap.Discriminator);
  386. }
  387. finally
  388. {
  389. BsonSerializer.ConfigLock.ExitWriteLock();
  390. }
  391. }
  392. /// <summary>
  393. /// Registers a conventions profile.
  394. /// </summary>
  395. /// <param name="conventions">The conventions profile.</param>
  396. /// <param name="filter">The filter function that determines which types this profile applies to.</param>
  397. [Obsolete("Use ConventionRegistry.Register instead.")]
  398. public static void RegisterConventions(ConventionProfile conventions, Func<Type, bool> filter)
  399. {
  400. ConventionRegistry.Register("conventions", conventions, filter);
  401. }
  402. // public methods
  403. /// <summary>
  404. /// Automaps the class.
  405. /// </summary>
  406. public void AutoMap()
  407. {
  408. if (_frozen) { ThrowFrozenException(); }
  409. AutoMapClass();
  410. }
  411. /// <summary>
  412. /// Creates an instance of the class.
  413. /// </summary>
  414. /// <returns>An object.</returns>
  415. public object CreateInstance()
  416. {
  417. if (!_frozen) { ThrowNotFrozenException(); }
  418. var creator = GetCreator();
  419. return creator.Invoke();
  420. }
  421. /// <summary>
  422. /// Freezes the class map.
  423. /// </summary>
  424. /// <returns>The frozen class map.</returns>
  425. public BsonClassMap Freeze()
  426. {
  427. BsonSerializer.ConfigLock.EnterReadLock();
  428. try
  429. {
  430. if (_frozen)
  431. {
  432. return this;
  433. }
  434. }
  435. finally
  436. {
  437. BsonSerializer.ConfigLock.ExitReadLock();
  438. }
  439. BsonSerializer.ConfigLock.EnterWriteLock();
  440. try
  441. {
  442. if (!_frozen)
  443. {
  444. __freezeNestingLevel++;
  445. try
  446. {
  447. var baseType = _classType.BaseType;
  448. if (baseType != null)
  449. {
  450. _baseClassMap = LookupClassMap(baseType);
  451. _discriminatorIsRequired |= _baseClassMap._discriminatorIsRequired;
  452. _hasRootClass |= (_isRootClass || _baseClassMap.HasRootClass);
  453. _allMemberMaps.AddRange(_baseClassMap.AllMemberMaps);
  454. if (_baseClassMap.IgnoreExtraElements && _baseClassMap.IgnoreExtraElementsIsInherited)
  455. {
  456. _ignoreExtraElements = true;
  457. _ignoreExtraElementsIsInherited = true;
  458. }
  459. }
  460. _allMemberMaps.AddRange(_declaredMemberMaps);
  461. if (_idMemberMap == null)
  462. {
  463. // see if we can inherit the idMemberMap from our base class
  464. if (_baseClassMap != null)
  465. {
  466. _idMemberMap = _baseClassMap.IdMemberMap;
  467. }
  468. }
  469. else
  470. {
  471. if (_idMemberMap.ClassMap == this)
  472. {
  473. // conventions could have set this to an improper value
  474. _idMemberMap.SetElementName("_id");
  475. }
  476. }
  477. if (_extraElementsMemberMap == null)
  478. {
  479. // see if we can inherit the extraElementsMemberMap from our base class
  480. if (_baseClassMap != null)
  481. {
  482. _extraElementsMemberMap = _baseClassMap.ExtraElementsMemberMap;
  483. }
  484. }
  485. _extraElementsMemberIndex = -1;
  486. for (int memberIndex = 0; memberIndex < _allMemberMaps.Count; ++memberIndex)
  487. {
  488. var memberMap = _allMemberMaps[memberIndex];
  489. int conflictingMemberIndex;
  490. if (!_elementTrie.TryGetValue(memberMap.ElementName, out conflictingMemberIndex))
  491. {
  492. _elementTrie.Add(memberMap.ElementName, memberIndex);
  493. }
  494. else
  495. {
  496. var conflictingMemberMap = _allMemberMaps[conflictingMemberIndex];
  497. var fieldOrProperty = (memberMap.MemberInfo.MemberType == MemberTypes.Field) ? "field" : "property";
  498. var conflictingFieldOrProperty = (conflictingMemberMap.MemberInfo.MemberType == MemberTypes.Field) ? "field" : "property";
  499. var conflictingType = conflictingMemberMap.MemberInfo.DeclaringType;
  500. string message;
  501. if (conflictingType == _classType)
  502. {
  503. message = string.Format(
  504. "The {0} '{1}' of type '{2}' cannot use element name '{3}' because it is already being used by {4} '{5}'.",
  505. fieldOrProperty, memberMap.MemberName, _classType.FullName, memberMap.ElementName, conflictingFieldOrProperty, conflictingMemberMap.MemberName);
  506. }
  507. else
  508. {
  509. message = string.Format(
  510. "The {0} '{1}' of type '{2}' cannot use element name '{3}' because it is already being used by {4} '{5}' of type '{6}'.",
  511. fieldOrProperty, memberMap.MemberName, _classType.FullName, memberMap.ElementName, conflictingFieldOrProperty, conflictingMemberMap.MemberName, conflictingType.FullName);
  512. }
  513. throw new BsonSerializationException(message);
  514. }
  515. if (memberMap == _extraElementsMemberMap)
  516. {
  517. _extraElementsMemberIndex = memberIndex;
  518. }
  519. }
  520. // mark this classMap frozen before we start working on knownTypes
  521. // because we might get back to this same classMap while processing knownTypes
  522. foreach (var creatorMap in _creatorMaps)
  523. {
  524. creatorMap.Freeze();
  525. }
  526. foreach (var memberMap in _declaredMemberMaps)
  527. {
  528. memberMap.Freeze();
  529. }
  530. _frozen = true;
  531. // use a queue to postpone processing of known types until we get back to the first level call to Freeze
  532. // this avoids infinite recursion when going back down the inheritance tree while processing known types
  533. foreach (var knownType in _knownTypes)
  534. {
  535. __knownTypesQueue.Enqueue(knownType);
  536. }
  537. // if we are back to the first level go ahead and process any queued known types
  538. if (__freezeNestingLevel == 1)
  539. {
  540. while (__knownTypesQueue.Count != 0)
  541. {
  542. var knownType = __knownTypesQueue.Dequeue();
  543. LookupClassMap(knownType); // will AutoMap and/or Freeze knownType if necessary
  544. }
  545. }
  546. }
  547. finally
  548. {
  549. __freezeNestingLevel--;
  550. }
  551. }
  552. }
  553. finally
  554. {
  555. BsonSerializer.ConfigLock.ExitWriteLock();
  556. }
  557. return this;
  558. }
  559. /// <summary>
  560. /// Gets a member map (only considers members declared in this class).
  561. /// </summary>
  562. /// <param name="memberName">The member name.</param>
  563. /// <returns>The member map (or null if the member was not found).</returns>
  564. public BsonMemberMap GetMemberMap(string memberName)
  565. {
  566. if (memberName == null)
  567. {
  568. throw new ArgumentNullException("memberName");
  569. }
  570. // can be called whether frozen or not
  571. return _declaredMemberMaps.Find(m => m.MemberName == memberName);
  572. }
  573. /// <summary>
  574. /// Gets the member map for a BSON element.
  575. /// </summary>
  576. /// <param name="elementName">The name of the element.</param>
  577. /// <returns>The member map.</returns>
  578. public BsonMemberMap GetMemberMapForElement(string elementName)
  579. {
  580. if (elementName == null)
  581. {
  582. throw new ArgumentNullException("elementName");
  583. }
  584. if (!_frozen) { ThrowNotFrozenException(); }
  585. int memberIndex;
  586. if (!_elementTrie.TryGetValue(elementName, out memberIndex))
  587. {
  588. return null;
  589. }
  590. var memberMap = _allMemberMaps[memberIndex];
  591. return memberMap;
  592. }
  593. /// <summary>
  594. /// Creates a creator map for a constructor and adds it to the class map.
  595. /// </summary>
  596. /// <param name="constructorInfo">The constructor info.</param>
  597. /// <returns>The creator map (so method calls can be chained).</returns>
  598. public BsonCreatorMap MapConstructor(ConstructorInfo constructorInfo)
  599. {
  600. if (constructorInfo == null)
  601. {
  602. throw new ArgumentNullException("constructorInfo");
  603. }
  604. EnsureMemberInfoIsForThisClass(constructorInfo);
  605. if (_frozen) { ThrowFrozenException(); }
  606. var creatorMap = _creatorMaps.FirstOrDefault(m => m.MemberInfo == constructorInfo);
  607. if (creatorMap == null)
  608. {
  609. var @delegate = new CreatorMapDelegateCompiler().CompileConstructorDelegate(constructorInfo);
  610. creatorMap = new BsonCreatorMap(this, constructorInfo, @delegate);
  611. _creatorMaps.Add(creatorMap);
  612. }
  613. return creatorMap;
  614. }
  615. /// <summary>
  616. /// Creates a creator map for a constructor and adds it to the class map.
  617. /// </summary>
  618. /// <param name="constructorInfo">The constructor info.</param>
  619. /// <param name="argumentNames">The argument names.</param>
  620. /// <returns>The creator map (so method calls can be chained).</returns>
  621. public BsonCreatorMap MapConstructor(ConstructorInfo constructorInfo, params string[] argumentNames)
  622. {
  623. var creatorMap = MapConstructor(constructorInfo);
  624. creatorMap.SetArguments(argumentNames);
  625. return creatorMap;
  626. }
  627. /// <summary>
  628. /// Creates a creator map and adds it to the class.
  629. /// </summary>
  630. /// <param name="delegate">The delegate.</param>
  631. /// <returns>The factory method map (so method calls can be chained).</returns>
  632. public BsonCreatorMap MapCreator(Delegate @delegate)
  633. {
  634. if (@delegate == null)
  635. {
  636. throw new ArgumentNullException("delegate");
  637. }
  638. if (_frozen) { ThrowFrozenException(); }
  639. var creatorMap = new BsonCreatorMap(this, null, @delegate);
  640. _creatorMaps.Add(creatorMap);
  641. return creatorMap;
  642. }
  643. /// <summary>
  644. /// Creates a creator map and adds it to the class.
  645. /// </summary>
  646. /// <param name="delegate">The delegate.</param>
  647. /// <param name="argumentNames">The argument names.</param>
  648. /// <returns>The factory method map (so method calls can be chained).</returns>
  649. public BsonCreatorMap MapCreator(Delegate @delegate, params string[] argumentNames)
  650. {
  651. var creatorMap = MapCreator(@delegate);
  652. creatorMap.SetArguments(argumentNames);
  653. return creatorMap;
  654. }
  655. /// <summary>
  656. /// Creates a member map for the extra elements field and adds it to the class map.
  657. /// </summary>
  658. /// <param name="fieldName">The name of the extra elements field.</param>
  659. /// <returns>The member map (so method calls can be chained).</returns>
  660. public BsonMemberMap MapExtraElementsField(string fieldName)
  661. {
  662. if (fieldName == null)
  663. {
  664. throw new ArgumentNullException("fieldName");
  665. }
  666. if (_frozen) { ThrowFrozenException(); }
  667. var fieldMap = MapField(fieldName);
  668. SetExtraElementsMember(fieldMap);
  669. return fieldMap;
  670. }
  671. /// <summary>
  672. /// Creates a member map for the extra elements member and adds it to the class map.
  673. /// </summary>
  674. /// <param name="memberInfo">The member info for the extra elements member.</param>
  675. /// <returns>The member map (so method calls can be chained).</returns>
  676. public BsonMemberMap MapExtraElementsMember(MemberInfo memberInfo)
  677. {
  678. if (memberInfo == null)
  679. {
  680. throw new ArgumentNullException("memberInfo");
  681. }
  682. if (_frozen) { ThrowFrozenException(); }
  683. var memberMap = MapMember(memberInfo);
  684. SetExtraElementsMember(memberMap);
  685. return memberMap;
  686. }
  687. /// <summary>
  688. /// Creates a member map for the extra elements property and adds it to the class map.
  689. /// </summary>
  690. /// <param name="propertyName">The name of the property.</param>
  691. /// <returns>The member map (so method calls can be chained).</returns>
  692. public BsonMemberMap MapExtraElementsProperty(string propertyName)
  693. {
  694. if (propertyName == null)
  695. {
  696. throw new ArgumentNullException("propertyName");
  697. }
  698. if (_frozen) { ThrowFrozenException(); }
  699. var propertyMap = MapProperty(propertyName);
  700. SetExtraElementsMember(propertyMap);
  701. return propertyMap;
  702. }
  703. /// <summary>
  704. /// Creates a creator map for a factory method and adds it to the class.
  705. /// </summary>
  706. /// <param name="methodInfo">The method info.</param>
  707. /// <returns>The creator map (so method calls can be chained).</returns>
  708. public BsonCreatorMap MapFactoryMethod(MethodInfo methodInfo)
  709. {
  710. if (methodInfo == null)
  711. {
  712. throw new ArgumentNullException("methodInfo");
  713. }
  714. EnsureMemberInfoIsForThisClass(methodInfo);
  715. if (_frozen) { ThrowFrozenException(); }
  716. var creatorMap = _creatorMaps.FirstOrDefault(m => m.MemberInfo == methodInfo);
  717. if (creatorMap == null)
  718. {
  719. var @delegate = new CreatorMapDelegateCompiler().CompileFactoryMethodDelegate(methodInfo);
  720. creatorMap = new BsonCreatorMap(this, methodInfo, @delegate);
  721. _creatorMaps.Add(creatorMap);
  722. }
  723. return creatorMap;
  724. }
  725. /// <summary>
  726. /// Creates a creator map for a factory method and adds it to the class.
  727. /// </summary>
  728. /// <param name="methodInfo">The method info.</param>
  729. /// <param name="argumentNames">The argument names.</param>
  730. /// <returns>The creator map (so method calls can be chained).</returns>
  731. public BsonCreatorMap MapFactoryMethod(MethodInfo methodInfo, params string[] argumentNames)
  732. {
  733. var creatorMap = MapFactoryMethod(methodInfo);
  734. creatorMap.SetArguments(argumentNames);
  735. return creatorMap;
  736. }
  737. /// <summary>
  738. /// Creates a member map for a field and adds it to the class map.
  739. /// </summary>
  740. /// <param name="fieldName">The name of the field.</param>
  741. /// <returns>The member map (so method calls can be chained).</returns>
  742. public BsonMemberMap MapField(string fieldName)
  743. {
  744. if (fieldName == null)
  745. {
  746. throw new ArgumentNullException("fieldName");
  747. }
  748. if (_frozen) { ThrowFrozenException(); }
  749. var fieldInfo = _classType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  750. if (fieldInfo == null)
  751. {
  752. var message = string.Format("The class '{0}' does not have a field named '{1}'.", _classType.FullName, fieldName);
  753. throw new BsonSerializationException(message);
  754. }
  755. return MapMember(fieldInfo);
  756. }
  757. /// <summary>
  758. /// Creates a member map for the Id field and adds it to the class map.
  759. /// </summary>
  760. /// <param name="fieldName">The name of the Id field.</param>
  761. /// <returns>The member map (so method calls can be chained).</returns>
  762. public BsonMemberMap MapIdField(string fieldName)
  763. {
  764. if (fieldName == null)
  765. {
  766. throw new ArgumentNullException("fieldName");
  767. }
  768. if (_frozen) { ThrowFrozenException(); }
  769. var fieldMap = MapField(fieldName);
  770. SetIdMember(fieldMap);
  771. return fieldMap;
  772. }
  773. /// <summary>
  774. /// Creates a member map for the Id member and adds it to the class map.
  775. /// </summary>
  776. /// <param name="memberInfo">The member info for the Id member.</param>
  777. /// <returns>The member map (so method calls can be chained).</returns>
  778. public BsonMemberMap MapIdMember(MemberInfo memberInfo)
  779. {
  780. if (memberInfo == null)
  781. {
  782. throw new ArgumentNullException("memberInfo");
  783. }
  784. if (_frozen) { ThrowFrozenException(); }
  785. var memberMap = MapMember(memberInfo);
  786. SetIdMember(memberMap);
  787. return memberMap;
  788. }
  789. /// <summary>
  790. /// Creates a member map for the Id property and adds it to the class map.
  791. /// </summary>
  792. /// <param name="propertyName">The name of the Id property.</param>
  793. /// <returns>The member map (so method calls can be chained).</returns>
  794. public BsonMemberMap MapIdProperty(string propertyName)
  795. {
  796. if (propertyName == null)
  797. {
  798. throw new ArgumentNullException("propertyName");
  799. }
  800. if (_frozen) { ThrowFrozenException(); }
  801. var propertyMap = MapProperty(propertyName);
  802. SetIdMember(propertyMap);
  803. return propertyMap;
  804. }
  805. /// <summary>
  806. /// Creates a member map for a member and adds it to the class map.
  807. /// </summary>
  808. /// <param name="memberInfo">The member info.</param>
  809. /// <returns>The member map (so method calls can be chained).</returns>
  810. public BsonMemberMap MapMember(MemberInfo memberInfo)
  811. {
  812. if (memberInfo == null)
  813. {
  814. throw new ArgumentNullException("memberInfo");
  815. }
  816. if (!(memberInfo is FieldInfo) && !(memberInfo is PropertyInfo))
  817. {
  818. throw new ArgumentException("MemberInfo must be either a FieldInfo or a PropertyInfo.", "memberInfo");
  819. }
  820. EnsureMemberInfoIsForThisClass(memberInfo);
  821. if (_frozen) { ThrowFrozenException(); }
  822. var memberMap = _declaredMemberMaps.Find(m => m.MemberInfo == memberInfo);
  823. if (memberMap == null)
  824. {
  825. memberMap = new BsonMemberMap(this, memberInfo);
  826. _declaredMemberMaps.Add(memberMap);
  827. }
  828. return memberMap;
  829. }
  830. /// <summary>
  831. /// Creates a member map for a property and adds it to the class map.
  832. /// </summary>
  833. /// <param name="propertyName">The name of the property.</param>
  834. /// <returns>The member map (so method calls can be chained).</returns>
  835. public BsonMemberMap MapProperty(string propertyName)
  836. {
  837. if (propertyName == null)
  838. {
  839. throw new ArgumentNullException("propertyName");
  840. }
  841. if (_frozen) { ThrowFrozenException(); }
  842. var propertyInfo = _classType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  843. if (propertyInfo == null)
  844. {
  845. var message = string.Format("The class '{0}' does not have a property named '{1}'.", _classType.FullName, propertyName);
  846. throw new BsonSerializationException(message);
  847. }
  848. return MapMember(propertyInfo);
  849. }
  850. /// <summary>
  851. /// Resets the class map back to its initial state.
  852. /// </summary>
  853. public void Reset()
  854. {
  855. if (_frozen) { ThrowFrozenException(); }
  856. _creatorMaps.Clear();
  857. _creator = null;
  858. _declaredMemberMaps.Clear();
  859. _discriminator = _classType.Name;
  860. _discriminatorIsRequired = false;
  861. _extraElementsMemberMap = null;
  862. _idMemberMap = null;
  863. _ignoreExtraElements = true; // TODO: should this really be false?
  864. _ignoreExtraElementsIsInherited = false;
  865. _isRootClass = false;
  866. _knownTypes.Clear();
  867. }
  868. /// <summary>
  869. /// Sets the creator for the object.
  870. /// </summary>
  871. /// <param name="creator">The creator.</param>
  872. /// <returns>The class map (so method calls can be chained).</returns>
  873. public BsonClassMap SetCreator(Func<object> creator)
  874. {
  875. _creator = creator;
  876. return this;
  877. }
  878. /// <summary>
  879. /// Sets the discriminator.
  880. /// </summary>
  881. /// <param name="discriminator">The discriminator.</param>
  882. public void SetDiscriminator(string discriminator)
  883. {
  884. if (discriminator == null)
  885. {
  886. throw new ArgumentNullException("discriminator");
  887. }
  888. if (_frozen) { ThrowFrozenException(); }
  889. _discriminator = discriminator;
  890. }
  891. /// <summary>
  892. /// Sets whether a discriminator is required when serializing this class.
  893. /// </summary>
  894. /// <param name="discriminatorIsRequired">Whether a discriminator is required.</param>
  895. public void SetDiscriminatorIsRequired(bool discriminatorIsRequired)
  896. {
  897. if (_frozen) { ThrowFrozenException(); }
  898. _discriminatorIsRequired = discriminatorIsRequired;
  899. }
  900. /// <summary>
  901. /// Sets the member map of the member used to hold extra elements.
  902. /// </summary>
  903. /// <param name="memberMap">The extra elements member map.</param>
  904. public void SetExtraElementsMember(BsonMemberMap memberMap)
  905. {
  906. if (memberMap == null)
  907. {
  908. throw new ArgumentNullException("memberMap");
  909. }
  910. EnsureMemberMapIsForThisClass(memberMap);
  911. if (_frozen) { ThrowFrozenException(); }
  912. if (memberMap.MemberType != typeof(BsonDocument) && !typeof(IDictionary<string, object>).IsAssignableFrom(memberMap.MemberType))
  913. {
  914. var message = string.Format("Type of ExtraElements member must be BsonDocument or implement IDictionary<string, object>.");
  915. throw new InvalidOperationException(message);
  916. }
  917. _extraElementsMemberMap = memberMap;
  918. }
  919. /// <summary>
  920. /// Adds a known type to the class map.
  921. /// </summary>
  922. /// <param name="type">The known type.</param>
  923. public void AddKnownType(Type type)
  924. {
  925. if (!_classType.IsAssignableFrom(type))
  926. {
  927. string message = string.Format("Class {0} cannot be assigned to Class {1}. Ensure that known types are derived from the mapped class.", type.FullName, _classType.FullName);
  928. throw new ArgumentNullException("type", message);
  929. }
  930. if (_frozen) { ThrowFrozenException(); }
  931. _knownTypes.Add(type);
  932. }
  933. /// <summary>
  934. /// Sets the Id member.
  935. /// </summary>
  936. /// <param name="memberMap">The Id member (null if none).</param>
  937. public void SetIdMember(BsonMemberMap memberMap)
  938. {
  939. if (memberMap != null)
  940. {
  941. EnsureMemberMapIsForThisClass(memberMap);
  942. }
  943. if (_frozen) { ThrowFrozenException(); }
  944. _idMemberMap = memberMap;
  945. }
  946. /// <summary>
  947. /// Sets whether extra elements should be ignored when deserializing.
  948. /// </summary>
  949. /// <param name="ignoreExtraElements">Whether extra elements should be ignored when deserializing.</param>
  950. public void SetIgnoreExtraElements(bool ignoreExtraElements)
  951. {
  952. if (_frozen) { ThrowFrozenException(); }
  953. _ignoreExtraElements = ignoreExtraElements;
  954. }
  955. /// <summary>
  956. /// Sets whether the IgnoreExtraElements value should be inherited by derived classes.
  957. /// </summary>
  958. /// <param name="ignoreExtraElementsIsInherited">Whether the IgnoreExtraElements value should be inherited by derived classes.</param>
  959. public void SetIgnoreExtraElementsIsInherited(bool ignoreExtraElementsIsInherited)
  960. {
  961. if (_frozen) { ThrowFrozenException(); }
  962. _ignoreExtraElementsIsInherited = ignoreExtraElementsIsInherited;
  963. }
  964. /// <summary>
  965. /// Sets whether this class is a root class.
  966. /// </summary>
  967. /// <param name="isRootClass">Whether this class is a root class.</param>
  968. public void SetIsRootClass(bool isRootClass)
  969. {
  970. if (_frozen) { ThrowFrozenException(); }
  971. _isRootClass = isRootClass;
  972. }
  973. /// <summary>
  974. /// Removes a creator map for a constructor from the class map.
  975. /// </summary>
  976. /// <param name="constructorInfo">The constructor info.</param>
  977. public void UnmapConstructor(ConstructorInfo constructorInfo)
  978. {
  979. if (constructorInfo == null)
  980. {
  981. throw new ArgumentNullException("constructorInfo");
  982. }
  983. EnsureMemberInfoIsForThisClass(constructorInfo);
  984. if (_frozen) { ThrowFrozenException(); }
  985. var creatorMap = _creatorMaps.FirstOrDefault(m => m.MemberInfo == constructorInfo);
  986. if (creatorMap != null)
  987. {
  988. _creatorMaps.Remove(creatorMap);
  989. }
  990. }
  991. /// <summary>
  992. /// Removes a creator map for a factory method from the class map.
  993. /// </summary>
  994. /// <param name="methodInfo">The method info.</param>
  995. public void UnmapFactoryMethod(MethodInfo methodInfo)
  996. {
  997. if (methodInfo == null)
  998. {
  999. throw new ArgumentNullException("methodInfo");
  1000. }
  1001. EnsureMemberInfoIsForThisClass(methodInfo);
  1002. if (_frozen) { ThrowFrozenException(); }
  1003. var creatorMap = _creatorMaps.FirstOrDefault(m => m.MemberInfo == methodInfo);
  1004. if (creatorMap != null)
  1005. {
  1006. _creatorMaps.Remove(creatorMap);
  1007. }
  1008. }
  1009. /// <summary>
  1010. /// Removes the member map for a field from the class map.
  1011. /// </summary>
  1012. /// <param name="fieldName">The name of the field.</param>
  1013. public void UnmapField(string fieldName)
  1014. {
  1015. if (fieldName == null)
  1016. {
  1017. throw new ArgumentNullException("fieldName");
  1018. }
  1019. if (_frozen) { ThrowFrozenException(); }
  1020. var fieldInfo = _classType.GetField(fieldName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  1021. if (fieldInfo == null)
  1022. {
  1023. var message = string.Format("The class '{0}' does not have a field named '{1}'.", _classType.FullName, fieldName);
  1024. throw new BsonSerializationException(message);
  1025. }
  1026. UnmapMember(fieldInfo);
  1027. }
  1028. /// <summary>
  1029. /// Removes a member map from the class map.
  1030. /// </summary>
  1031. /// <param name="memberInfo">The member info.</param>
  1032. public void UnmapMember(MemberInfo memberInfo)
  1033. {
  1034. if (memberInfo == null)
  1035. {
  1036. throw new ArgumentNullException("memberInfo");
  1037. }
  1038. EnsureMemberInfoIsForThisClass(memberInfo);
  1039. if (_frozen) { ThrowFrozenException(); }
  1040. var memberMap = _declaredMemberMaps.Find(m => m.MemberInfo == memberInfo);
  1041. if (memberMap != null)
  1042. {
  1043. _declaredMemberMaps.Remove(memberMap);
  1044. if (_idMemberMap == memberMap)
  1045. {
  1046. _idMemberMap = null;
  1047. }
  1048. if (_extraElementsMemberMap == memberMap)
  1049. {
  1050. _extraElementsMemberMap = null;
  1051. }
  1052. }
  1053. }
  1054. /// <summary>
  1055. /// Removes the member map for a property from the class map.
  1056. /// </summary>
  1057. /// <param name="propertyName">The name of the property.</param>
  1058. public void UnmapProperty(string propertyName)
  1059. {
  1060. if (propertyName == null)
  1061. {
  1062. throw new ArgumentNullException("propertyName");
  1063. }
  1064. if (_frozen) { ThrowFrozenException(); }
  1065. var propertyInfo = _classType.GetProperty(propertyName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.DeclaredOnly);
  1066. if (propertyInfo == null)
  1067. {
  1068. var message = string.Format("The class '{0}' does not have a property named '{1}'.", _classType.FullName, propertyName);
  1069. throw new BsonSerializationException(message);
  1070. }
  1071. UnmapMember(propertyInfo);
  1072. }
  1073. // internal methods
  1074. /// <summary>
  1075. /// Gets the discriminator convention for the class.
  1076. /// </summary>
  1077. /// <returns>The discriminator convention for the class.</returns>
  1078. internal IDiscriminatorConvention GetDiscriminatorConvention()
  1079. {
  1080. // return a cached discriminator convention when possible
  1081. var discriminatorConvention = _cachedDiscriminatorConvention;
  1082. if (discriminatorConvention == null)
  1083. {
  1084. // it's possible but harmless for multiple threads to do the initial lookup at the same time
  1085. discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(_classType);
  1086. _cachedDiscriminatorConvention = discriminatorConvention;
  1087. }
  1088. return discriminatorConvention;
  1089. }
  1090. // private methods
  1091. private void AutoMapClass()
  1092. {
  1093. new ConventionRunner(_conventionPack).Apply(this);
  1094. OrderMembers();
  1095. foreach (var memberMap in _declaredMemberMaps)
  1096. {
  1097. TryFindShouldSerializeMethod(memberMap);
  1098. }
  1099. }
  1100. private void OrderMembers()
  1101. {
  1102. // only auto map properties declared in this class (and not in base classes)
  1103. var hasOrderedElements = false;
  1104. var hasUnorderedElements = false;
  1105. foreach (var memberMap in _declaredMemberMaps)
  1106. {
  1107. if (memberMap.Order != int.MaxValue)
  1108. {
  1109. hasOrderedElements |= true;
  1110. }
  1111. else
  1112. {
  1113. hasUnorderedElements |= true;
  1114. }
  1115. }
  1116. if (hasOrderedElements)
  1117. {
  1118. if (hasUnorderedElements)
  1119. {
  1120. // split out the unordered elements and add them back at the end (because Sort is unstable, see online help)
  1121. var unorderedElements = new List<BsonMemberMap>(_declaredMemberMaps.Where(pm => pm.Order == int.MaxValue));
  1122. _declaredMemberMaps.RemoveAll(m => m.Order == int.MaxValue);
  1123. _declaredMemberMaps.Sort((x, y) => x.Order.CompareTo(y.Order));
  1124. _declaredMemberMaps.AddRange(unorderedElements);
  1125. }
  1126. else
  1127. {
  1128. _declaredMemberMaps.Sort((x, y) => x.Order.CompareTo(y.Order));
  1129. }
  1130. }
  1131. }
  1132. private void TryFindShouldSerializeMethod(BsonMemberMap memberMap)
  1133. {
  1134. // see if the class has a method called ShouldSerializeXyz where Xyz is the name of this member
  1135. var shouldSerializeMethod = GetShouldSerializeMethod(memberMap.MemberInfo);
  1136. if (shouldSerializeMethod != null)
  1137. {
  1138. memberMap.SetShouldSerializeMethod(shouldSerializeMethod);
  1139. }
  1140. }
  1141. private void EnsureMemberInfoIsForThisClass(MemberInfo memberInfo)
  1142. {
  1143. if (memberInfo.DeclaringType != _classType)
  1144. {
  1145. var message = string.Format(
  1146. "The memberInfo argument must be for class {0}, but was for class {1}.",
  1147. _classType.Name,
  1148. memberInfo.DeclaringType.Name);
  1149. throw new ArgumentOutOfRangeException("memberInfo", message);
  1150. }
  1151. }
  1152. private void EnsureMemberMapIsForThisClass(BsonMemberMap memberMap)
  1153. {
  1154. if (memberMap.ClassMap != this)
  1155. {
  1156. var message = string.Format(
  1157. "The memberMap argument must be for class {0}, but was for class {1}.",
  1158. _classType.Name,
  1159. memberMap.ClassMap.ClassType.Name);
  1160. throw new ArgumentOutOfRangeException("memberMap", message);
  1161. }
  1162. }
  1163. private Func<object> GetCreator()
  1164. {
  1165. if (_creator == null)
  1166. {
  1167. Expression body;
  1168. var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
  1169. var defaultConstructor = _classType.GetConstructor(bindingFlags, null, new Type[0], null);
  1170. if (defaultConstructor != null)
  1171. {
  1172. // lambdaExpression = () => (object) new TClass()
  1173. body = Expression.New(defaultConstructor);
  1174. }
  1175. else
  1176. {
  1177. // lambdaExpression = () => FormatterServices.GetUninitializedObject(classType)
  1178. var getUnitializedObjectMethodInfo = typeof(FormatterServices).GetMethod("GetUninitializedObject", BindingFlags.Public | BindingFlags.Static);
  1179. body = Expression.Call(getUnitializedObjectMethodInfo, Expression.Constant(_classType));
  1180. }
  1181. var lambdaExpression = Expression.Lambda<Func<object>>(body);
  1182. _creator = lambdaExpression.Compile();
  1183. }
  1184. return _creator;
  1185. }
  1186. private Func<object, bool> GetShouldSerializeMethod(MemberInfo memberInfo)
  1187. {
  1188. var shouldSerializeMethodName = "ShouldSerialize" + memberInfo.Name;
  1189. var shouldSerializeMethodInfo = _classType.GetMethod(shouldSerializeMethodName, new Type[] { });
  1190. if (shouldSerializeMethodInfo != null &&
  1191. shouldSerializeMethodInfo.IsPublic &&
  1192. shouldSerializeMethodInfo.ReturnType == typeof(bool))
  1193. {
  1194. // lambdaExpression = (obj) => ((TClass) obj).ShouldSerializeXyz()
  1195. var objParameter = Expression.Parameter(typeof(object), "obj");
  1196. var lambdaExpression = Expression.Lambda<Func<object, bool>>(Expression.Call(Expression.Convert(objParameter, _classType), shouldSerializeMethodInfo), objParameter);
  1197. return lambdaExpression.Compile();
  1198. }
  1199. else
  1200. {
  1201. return null;
  1202. }
  1203. }
  1204. private bool IsAnonymousType(Type type)
  1205. {
  1206. // don't test for too many things in case implementation details change in the future
  1207. return
  1208. Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false) &&
  1209. type.IsGenericType &&
  1210. type.Name.Contains("Anon"); // don't check for more than "Anon" so it works in mono also
  1211. }
  1212. private void ThrowFrozenException()
  1213. {
  1214. var message = string.Format("Class map for {0} has been frozen and no further changes are allowed.", _classType.FullName);
  1215. throw new InvalidOperationException(message);
  1216. }
  1217. private void ThrowNotFrozenException()
  1218. {
  1219. var message = string.Format("Class map for {0} has been not been frozen yet.", _classType.FullName);
  1220. throw new InvalidOperationException(message);
  1221. }
  1222. }
  1223. /// <summary>
  1224. /// Represents a mapping between a class and a BSON document.
  1225. /// </summary>
  1226. /// <typeparam name="TClass">The class.</typeparam>
  1227. public class BsonClassMap<TClass> : BsonClassMap
  1228. {
  1229. // constructors
  1230. /// <summary>
  1231. /// Initializes a new instance of the BsonClassMap class.
  1232. /// </summary>
  1233. public BsonClassMap()
  1234. : base(typeof(TClass))
  1235. {
  1236. }
  1237. /// <summary>
  1238. /// Initializes a new instance of the BsonClassMap class.
  1239. /// </summary>
  1240. /// <param name="classMapInitializer">The class map initializer.</param>
  1241. public BsonClassMap(Action<BsonClassMap<TClass>> classMapInitializer)
  1242. : base(typeof(TClass))
  1243. {
  1244. classMapInitializer(this);
  1245. }
  1246. // public methods
  1247. /// <summary>
  1248. /// Gets a member map.
  1249. /// </summary>
  1250. /// <typeparam name="TMember">The member type.</typeparam>
  1251. /// <param name="memberLambda">A lambda expression specifying the member.</param>
  1252. /// <returns>The member map.</returns>
  1253. public BsonMemberMap GetMemberMap<TMember>(Expression<Func<TClass, TMember>> memberLambda)
  1254. {
  1255. var memberName = GetMemberNameFromLambda(memberLambda);
  1256. return GetMemberMap(memberName);
  1257. }
  1258. /// <summary>
  1259. /// Creates a creator map and adds it to the class map.
  1260. /// </summary>
  1261. /// <param name="creatorLambda">Lambda expression specifying the creator code and parameters to use.</param>
  1262. /// <returns>The member map.</returns>
  1263. public BsonCreatorMap MapCreator(Expression<Func<TClass, TClass>> creatorLambda)
  1264. {
  1265. if (creatorLambda == null)
  1266. {
  1267. throw new ArgumentNullException("creatorLambda");
  1268. }
  1269. IEnumerable<MemberInfo> arguments;
  1270. var @delegate = new CreatorMapDelegateCompiler().CompileCreatorDelegate(creatorLambda, out arguments);
  1271. var creatorMap = MapCreator(@delegate);
  1272. creatorMap.SetArguments(arguments);
  1273. return creatorMap;
  1274. }
  1275. /// <summary>
  1276. /// Creates a member map for the extra elements field and adds it to the class map.
  1277. /// </summary>
  1278. /// <typeparam name="TMember">The member type.</typeparam>
  1279. /// <param name="fieldLambda">A lambda expression specifying the extra elements field.</param>
  1280. /// <returns>The member map.</returns>
  1281. public BsonMemberMap MapExtraElementsField<TMember>(Expression<Func<TClass, TMember>> fieldLambda)
  1282. {
  1283. var fieldMap = MapField(fieldLambda);
  1284. SetExtraElementsMember(fieldMap);
  1285. return fieldMap;
  1286. }
  1287. /// <summary>
  1288. /// Creates a member map for the extra elements member and adds it to the class map.
  1289. /// </summary>
  1290. /// <typeparam name="TMember">The member type.</typeparam>
  1291. /// <param name="memberLambda">A lambda expression specifying the extra elements member.</param>
  1292. /// <returns>The member map.</returns>
  1293. public BsonMemberMap MapExtraElementsMember<TMember>(Expression<Func<TClass, TMember>> memberLambda)
  1294. {
  1295. var memberMap = MapMember(memberLambda);
  1296. SetExtraElementsMember(memberMap);
  1297. return memberMap;
  1298. }
  1299. /// <summary>
  1300. /// Creates a member map for the extra elements property and adds it to the class map.
  1301. /// </summary>
  1302. /// <typeparam name="TMember">The member type.</typeparam>
  1303. /// <param name="propertyLambda">A lambda expression specifying the extra elements property.</param>
  1304. /// <returns>The member map.</returns>
  1305. public BsonMemberMap MapExtraElementsProperty<TMember>(Expression<Func<TClass, TMember>> propertyLambda)
  1306. {
  1307. var propertyMap = MapProperty(propertyLambda);
  1308. SetExtraElementsMember(propertyMap);
  1309. return propertyMap;
  1310. }
  1311. /// <summary>
  1312. /// Creates a member map for a field and adds it to the class map.
  1313. /// </summary>
  1314. /// <typeparam name="TMember">The member type.</typeparam>
  1315. /// <param name="fieldLambda">A lambda expression specifying the field.</param>
  1316. /// <returns>The member map.</returns>
  1317. public BsonMemberMap MapField<TMember>(Expression<Func<TClass, TMember>> fieldLambda)
  1318. {
  1319. return MapMember(fieldLambda);
  1320. }
  1321. /// <summary>
  1322. /// Creates a member map for the Id field and adds it to the class map.
  1323. /// </summary>
  1324. /// <typeparam name="TMember">The member type.</typeparam>
  1325. /// <param name="fieldLambda">A lambda expression specifying the Id field.</param>
  1326. /// <returns>The member map.</returns>
  1327. public BsonMemberMap MapIdField<TMember>(Expression<Func<TClass, TMember>> fieldLambda)
  1328. {
  1329. var fieldMap = MapField(fieldLambda);
  1330. SetIdMember(fieldMap);
  1331. return fieldMap;
  1332. }
  1333. /// <summary>
  1334. /// Creates a member map for the Id member and adds it to the class map.
  1335. /// </summary>
  1336. /// <typeparam name="TMember">The member type.</typeparam>
  1337. /// <param name="memberLambda">A lambda expression specifying the Id member.</param>
  1338. /// <returns>The member map.</returns>
  1339. public BsonMemberMap MapIdMember<TMember>(Expression<Func<TClass, TMember>> memberLambda)
  1340. {
  1341. var memberMap = MapMember(memberLambda);
  1342. SetIdMember(memberMap);
  1343. return memberMap;
  1344. }
  1345. /// <summary>
  1346. /// Creates a member map for the Id property and adds it to the class map.
  1347. /// </summary>
  1348. /// <typeparam name="TMember">The member type.</typeparam>
  1349. /// <param name="propertyLambda">A lambda expression specifying the Id property.</param>
  1350. /// <returns>The member map.</returns>
  1351. public BsonMemberMap MapIdProperty<TMember>(Expression<Func<TClass, TMember>> propertyLambda)
  1352. {
  1353. var propertyMap = MapProperty(propertyLambda);
  1354. SetIdMember(propertyMap);
  1355. return propertyMap;
  1356. }
  1357. /// <summary>
  1358. /// Creates a member map and adds it to the class map.
  1359. /// </summary>
  1360. /// <typeparam name="TMember">The member type.</typeparam>
  1361. /// <param name="memberLambda">A lambda expression specifying the member.</param>
  1362. /// <returns>The member map.</returns>
  1363. public BsonMemberMap MapMember<TMember>(Expression<Func<TClass, TMember>> memberLambda)
  1364. {
  1365. var memberInfo = GetMemberInfoFromLambda(memberLambda);
  1366. return MapMember(memberInfo);
  1367. }
  1368. /// <summary>
  1369. /// Creates a member map for the Id property and adds it to the class map.
  1370. /// </summary>
  1371. /// <typeparam name="TMember">The member type.</typeparam>
  1372. /// <param name="propertyLambda">A lambda expression specifying the Id property.</param>
  1373. /// <returns>The member map.</returns>
  1374. public BsonMemberMap MapProperty<TMember>(Expression<Func<TClass, TMember>> propertyLambda)
  1375. {
  1376. return MapMember(propertyLambda);
  1377. }
  1378. /// <summary>
  1379. /// Removes the member map for a field from the class map.
  1380. /// </summary>
  1381. /// <typeparam name="TMember">The member type.</typeparam>
  1382. /// <param name="fieldLambda">A lambda expression specifying the field.</param>
  1383. public void UnmapField<TMember>(Expression<Func<TClass, TMember>> fieldLambda)
  1384. {
  1385. UnmapMember(fieldLambda);
  1386. }
  1387. /// <summary>
  1388. /// Removes a member map from the class map.
  1389. /// </summary>
  1390. /// <typeparam name="TMember">The member type.</typeparam>
  1391. /// <param name="memberLambda">A lambda expression specifying the member.</param>
  1392. public void UnmapMember<TMember>(Expression<Func<TClass, TMember>> memberLambda)
  1393. {
  1394. var memberInfo = GetMemberInfoFromLambda(memberLambda);
  1395. UnmapMember(memberInfo);
  1396. }
  1397. /// <summary>
  1398. /// Removes a member map for a property from the class map.
  1399. /// </summary>
  1400. /// <typeparam name="TMember">The member type.</typeparam>
  1401. /// <param name="propertyLambda">A lambda expression specifying the property.</param>
  1402. public void UnmapProperty<TMember>(Expression<Func<TClass, TMember>> propertyLambda)
  1403. {
  1404. UnmapMember(propertyLambda);
  1405. }
  1406. // private static methods
  1407. private static MemberInfo GetMemberInfoFromLambda<TMember>(Expression<Func<TClass, TMember>> memberLambda)
  1408. {
  1409. var body = memberLambda.Body;
  1410. MemberExpression memberExpression;
  1411. switch (body.NodeType)
  1412. {
  1413. case ExpressionType.MemberAccess:
  1414. memberExpression = (MemberExpression)body;
  1415. break;
  1416. case ExpressionType.Convert:
  1417. var convertExpression = (UnaryExpression)body;
  1418. memberExpression = (MemberExpression)convertExpression.Operand;
  1419. break;
  1420. default:
  1421. throw new BsonSerializationException("Invalid lambda expression");
  1422. }
  1423. var memberInfo = memberExpression.Member;
  1424. switch (memberInfo.MemberType)
  1425. {
  1426. case MemberTypes.Field:
  1427. break;
  1428. case MemberTypes.Property:
  1429. if (memberInfo.DeclaringType.IsInterface)
  1430. {
  1431. memberInfo = FindPropertyImplementation((PropertyInfo)memberInfo, typeof(TClass));
  1432. }
  1433. break;
  1434. default:
  1435. memberInfo = null;
  1436. break;
  1437. }
  1438. if (memberInfo == null)
  1439. {
  1440. throw new BsonSerializationException("Invalid lambda expression");
  1441. }
  1442. return memberInfo;
  1443. }
  1444. private static string GetMemberNameFromLambda<TMember>(Expression<Func<TClass, TMember>> memberLambda)
  1445. {
  1446. return GetMemberInfoFromLambda(memberLambda).Name;
  1447. }
  1448. private static PropertyInfo FindPropertyImplementation(PropertyInfo interfacePropertyInfo, Type actualType)
  1449. {
  1450. var interfaceType = interfacePropertyInfo.DeclaringType;
  1451. // An interface map must be used because because there is no
  1452. // other officially documented way to derive the explicitly
  1453. // implemented property name.
  1454. var interfaceMap = actualType.GetInterfaceMap(interfaceType);
  1455. var interfacePropertyAccessors = interfacePropertyInfo.GetAccessors(true);
  1456. var actualPropertyAccessors = interfacePropertyAccessors.Select(interfacePropertyAccessor =>
  1457. {
  1458. var index = Array.IndexOf<MethodInfo>(interfaceMap.InterfaceMethods, interfacePropertyAccessor);
  1459. return interfaceMap.TargetMethods[index];
  1460. });
  1461. // Binding must be done by accessor methods because interface
  1462. // maps only map accessor methods and do not map properties.
  1463. return actualType.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
  1464. .Single(propertyInfo =>
  1465. {
  1466. // we are looking for a property that implements all the required accessors
  1467. var propertyAccessors = propertyInfo.GetAccessors(true);
  1468. return actualPropertyAccessors.All(x => propertyAccessors.Contains(x));
  1469. });
  1470. }
  1471. }
  1472. }