RawBsonDocument.cs 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956
  1. /* Copyright 2010-present 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;
  17. using System.Collections.Generic;
  18. using System.IO;
  19. using System.Linq;
  20. using MongoDB.Bson.IO;
  21. using MongoDB.Bson.Serialization;
  22. using MongoDB.Bson.Serialization.Attributes;
  23. using MongoDB.Bson.Serialization.Serializers;
  24. namespace MongoDB.Bson
  25. {
  26. /// <summary>
  27. /// Represents an immutable BSON document that is represented using only the raw bytes.
  28. /// </summary>
  29. [BsonSerializer(typeof(RawBsonDocumentSerializer))]
  30. public class RawBsonDocument : BsonDocument, IDisposable
  31. {
  32. // private fields
  33. private bool _disposed;
  34. private IByteBuffer _slice;
  35. private List<IDisposable> _disposableItems = new List<IDisposable>();
  36. private BsonBinaryReaderSettings _readerSettings = BsonBinaryReaderSettings.Defaults;
  37. // constructors
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="RawBsonDocument"/> class.
  40. /// </summary>
  41. /// <param name="slice">The slice.</param>
  42. /// <exception cref="System.ArgumentNullException">slice</exception>
  43. /// <exception cref="System.ArgumentException">RawBsonDocument cannot be used with an IByteBuffer that needs disposing.</exception>
  44. public RawBsonDocument(IByteBuffer slice)
  45. {
  46. if (slice == null)
  47. {
  48. throw new ArgumentNullException("slice");
  49. }
  50. _slice = slice;
  51. }
  52. /// <summary>
  53. /// Initializes a new instance of the <see cref="RawBsonDocument"/> class.
  54. /// </summary>
  55. /// <param name="bytes">The bytes.</param>
  56. public RawBsonDocument(byte[] bytes)
  57. : this(new ByteArrayBuffer(bytes, isReadOnly: true))
  58. {
  59. }
  60. // public properties
  61. /// <summary>
  62. /// Gets the number of elements.
  63. /// </summary>
  64. public override int ElementCount
  65. {
  66. get
  67. {
  68. ThrowIfDisposed();
  69. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  70. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  71. {
  72. var elementCount = 0;
  73. bsonReader.ReadStartDocument();
  74. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  75. {
  76. bsonReader.SkipName();
  77. bsonReader.SkipValue();
  78. elementCount++;
  79. }
  80. bsonReader.ReadEndDocument();
  81. return elementCount;
  82. }
  83. }
  84. }
  85. /// <summary>
  86. /// Gets the elements.
  87. /// </summary>
  88. public override IEnumerable<BsonElement> Elements
  89. {
  90. get
  91. {
  92. ThrowIfDisposed();
  93. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  94. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  95. {
  96. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  97. bsonReader.ReadStartDocument();
  98. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  99. {
  100. var name = bsonReader.ReadName();
  101. var value = DeserializeBsonValue(context);
  102. yield return new BsonElement(name, value);
  103. }
  104. bsonReader.ReadEndDocument();
  105. }
  106. }
  107. }
  108. /// <summary>
  109. /// Gets the element names.
  110. /// </summary>
  111. public override IEnumerable<string> Names
  112. {
  113. get
  114. {
  115. ThrowIfDisposed();
  116. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  117. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  118. {
  119. bsonReader.ReadStartDocument();
  120. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  121. {
  122. yield return bsonReader.ReadName();
  123. bsonReader.SkipValue();
  124. }
  125. bsonReader.ReadEndDocument();
  126. }
  127. }
  128. }
  129. /// <summary>
  130. /// Gets the raw values (see BsonValue.RawValue).
  131. /// </summary>
  132. [Obsolete("Use Values instead.")]
  133. public override IEnumerable<object> RawValues
  134. {
  135. get
  136. {
  137. ThrowIfDisposed();
  138. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  139. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  140. {
  141. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  142. bsonReader.ReadStartDocument();
  143. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  144. {
  145. bsonReader.SkipName();
  146. yield return DeserializeBsonValue(context).RawValue;
  147. }
  148. bsonReader.ReadEndDocument();
  149. }
  150. }
  151. }
  152. /// <summary>
  153. /// Gets the slice.
  154. /// </summary>
  155. /// <value>
  156. /// The slice.
  157. /// </value>
  158. public IByteBuffer Slice
  159. {
  160. get
  161. {
  162. ThrowIfDisposed();
  163. return _slice;
  164. }
  165. }
  166. /// <summary>
  167. /// Gets the values.
  168. /// </summary>
  169. public override IEnumerable<BsonValue> Values
  170. {
  171. get
  172. {
  173. ThrowIfDisposed();
  174. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  175. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  176. {
  177. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  178. bsonReader.ReadStartDocument();
  179. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  180. {
  181. bsonReader.SkipName();
  182. yield return DeserializeBsonValue(context);
  183. }
  184. bsonReader.ReadEndDocument();
  185. }
  186. }
  187. }
  188. // public indexers
  189. /// <summary>
  190. /// Gets or sets a value by position.
  191. /// </summary>
  192. /// <param name="index">The position.</param>
  193. /// <returns>The value.</returns>
  194. public override BsonValue this[int index]
  195. {
  196. get { return GetValue(index); }
  197. set { Set(index, value); }
  198. }
  199. /// <summary>
  200. /// Gets the value of an element or a default value if the element is not found.
  201. /// </summary>
  202. /// <param name="name">The name of the element.</param>
  203. /// <param name="defaultValue">The default value to return if the element is not found.</param>
  204. /// <returns>Teh value of the element or a default value if the element is not found.</returns>
  205. [Obsolete("Use GetValue(string name, BsonValue defaultValue) instead.")]
  206. public override BsonValue this[string name, BsonValue defaultValue]
  207. {
  208. get { return GetValue(name, defaultValue); }
  209. }
  210. /// <summary>
  211. /// Gets or sets a value by name.
  212. /// </summary>
  213. /// <param name="name">The name.</param>
  214. /// <returns>The value.</returns>
  215. public override BsonValue this[string name]
  216. {
  217. get { return GetValue(name); }
  218. set { Set(name, value); }
  219. }
  220. // public methods
  221. /// <summary>
  222. /// Adds an element to the document.
  223. /// </summary>
  224. /// <param name="element">The element to add.</param>
  225. /// <returns>
  226. /// The document (so method calls can be chained).
  227. /// </returns>
  228. public override BsonDocument Add(BsonElement element)
  229. {
  230. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  231. }
  232. /// <summary>
  233. /// Adds elements to the document from a dictionary of key/value pairs.
  234. /// </summary>
  235. /// <param name="dictionary">The dictionary.</param>
  236. /// <returns>The document (so method calls can be chained).</returns>
  237. [Obsolete("Use AddRange instead.")]
  238. public override BsonDocument Add(Dictionary<string, object> dictionary)
  239. {
  240. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  241. }
  242. /// <summary>
  243. /// Adds elements to the document from a dictionary of key/value pairs.
  244. /// </summary>
  245. /// <param name="dictionary">The dictionary.</param>
  246. /// <param name="keys">Which keys of the hash table to add.</param>
  247. /// <returns>The document (so method calls can be chained).</returns>
  248. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  249. public override BsonDocument Add(Dictionary<string, object> dictionary, IEnumerable<string> keys)
  250. {
  251. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  252. }
  253. /// <summary>
  254. /// Adds elements to the document from a dictionary of key/value pairs.
  255. /// </summary>
  256. /// <param name="dictionary">The dictionary.</param>
  257. /// <returns>The document (so method calls can be chained).</returns>
  258. [Obsolete("Use AddRange instead.")]
  259. public override BsonDocument Add(IDictionary<string, object> dictionary)
  260. {
  261. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  262. }
  263. /// <summary>
  264. /// Adds elements to the document from a dictionary of key/value pairs.
  265. /// </summary>
  266. /// <param name="dictionary">The dictionary.</param>
  267. /// <param name="keys">Which keys of the hash table to add.</param>
  268. /// <returns>The document (so method calls can be chained).</returns>
  269. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  270. public override BsonDocument Add(IDictionary<string, object> dictionary, IEnumerable<string> keys)
  271. {
  272. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  273. }
  274. /// <summary>
  275. /// Adds elements to the document from a dictionary of key/value pairs.
  276. /// </summary>
  277. /// <param name="dictionary">The dictionary.</param>
  278. /// <returns>The document (so method calls can be chained).</returns>
  279. [Obsolete("Use AddRange instead.")]
  280. public override BsonDocument Add(IDictionary dictionary)
  281. {
  282. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  283. }
  284. /// <summary>
  285. /// Adds elements to the document from a dictionary of key/value pairs.
  286. /// </summary>
  287. /// <param name="dictionary">The dictionary.</param>
  288. /// <param name="keys">Which keys of the hash table to add.</param>
  289. /// <returns>The document (so method calls can be chained).</returns>
  290. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  291. public override BsonDocument Add(IDictionary dictionary, IEnumerable keys)
  292. {
  293. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  294. }
  295. /// <summary>
  296. /// Adds a list of elements to the document.
  297. /// </summary>
  298. /// <param name="elements">The list of elements.</param>
  299. /// <returns>The document (so method calls can be chained).</returns>
  300. [Obsolete("Use AddRange instead.")]
  301. public override BsonDocument Add(IEnumerable<BsonElement> elements)
  302. {
  303. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  304. }
  305. /// <summary>
  306. /// Adds a list of elements to the document.
  307. /// </summary>
  308. /// <param name="elements">The list of elements.</param>
  309. /// <returns>The document (so method calls can be chained).</returns>
  310. [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
  311. public override BsonDocument Add(params BsonElement[] elements)
  312. {
  313. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  314. }
  315. /// <summary>
  316. /// Creates and adds an element to the document.
  317. /// </summary>
  318. /// <param name="name">The name of the element.</param>
  319. /// <param name="value">The value of the element.</param>
  320. /// <returns>
  321. /// The document (so method calls can be chained).
  322. /// </returns>
  323. public override BsonDocument Add(string name, BsonValue value)
  324. {
  325. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  326. }
  327. /// <summary>
  328. /// Creates and adds an element to the document, but only if the condition is true.
  329. /// </summary>
  330. /// <param name="name">The name of the element.</param>
  331. /// <param name="value">The value of the element.</param>
  332. /// <param name="condition">Whether to add the element to the document.</param>
  333. /// <returns>The document (so method calls can be chained).</returns>
  334. public override BsonDocument Add(string name, BsonValue value, bool condition)
  335. {
  336. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  337. }
  338. /// <summary>
  339. /// Adds elements to the document from a dictionary of key/value pairs.
  340. /// </summary>
  341. /// <param name="dictionary">The dictionary.</param>
  342. /// <returns>
  343. /// The document (so method calls can be chained).
  344. /// </returns>
  345. public override BsonDocument AddRange(Dictionary<string, object> dictionary)
  346. {
  347. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  348. }
  349. /// <summary>
  350. /// Adds elements to the document from a dictionary of key/value pairs.
  351. /// </summary>
  352. /// <param name="dictionary">The dictionary.</param>
  353. /// <returns>
  354. /// The document (so method calls can be chained).
  355. /// </returns>
  356. public override BsonDocument AddRange(IDictionary dictionary)
  357. {
  358. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  359. }
  360. /// <summary>
  361. /// Adds a list of elements to the document.
  362. /// </summary>
  363. /// <param name="elements">The list of elements.</param>
  364. /// <returns>
  365. /// The document (so method calls can be chained).
  366. /// </returns>
  367. public override BsonDocument AddRange(IEnumerable<BsonElement> elements)
  368. {
  369. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  370. }
  371. /// <summary>
  372. /// Adds elements to the document from a dictionary of key/value pairs.
  373. /// </summary>
  374. /// <param name="dictionary">The dictionary.</param>
  375. /// <returns>
  376. /// The document (so method calls can be chained).
  377. /// </returns>
  378. public override BsonDocument AddRange(IEnumerable<KeyValuePair<string, object>> dictionary)
  379. {
  380. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  381. }
  382. /// <summary>
  383. /// Clears the document (removes all elements).
  384. /// </summary>
  385. public override void Clear()
  386. {
  387. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  388. }
  389. /// <summary>
  390. /// Creates a shallow clone of the document (see also DeepClone).
  391. /// </summary>
  392. /// <returns>
  393. /// A shallow clone of the document.
  394. /// </returns>
  395. public override BsonValue Clone()
  396. {
  397. ThrowIfDisposed();
  398. return new RawBsonDocument(CloneSlice());
  399. }
  400. /// <summary>
  401. /// Tests whether the document contains an element with the specified name.
  402. /// </summary>
  403. /// <param name="name">The name of the element to look for.</param>
  404. /// <returns>
  405. /// True if the document contains an element with the specified name.
  406. /// </returns>
  407. public override bool Contains(string name)
  408. {
  409. if (name == null)
  410. {
  411. throw new ArgumentNullException("name");
  412. }
  413. ThrowIfDisposed();
  414. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  415. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  416. {
  417. bsonReader.ReadStartDocument();
  418. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  419. {
  420. if (bsonReader.ReadName() == name)
  421. {
  422. return true;
  423. }
  424. bsonReader.SkipValue();
  425. }
  426. bsonReader.ReadEndDocument();
  427. return false;
  428. }
  429. }
  430. /// <summary>
  431. /// Tests whether the document contains an element with the specified value.
  432. /// </summary>
  433. /// <param name="value">The value of the element to look for.</param>
  434. /// <returns>
  435. /// True if the document contains an element with the specified value.
  436. /// </returns>
  437. public override bool ContainsValue(BsonValue value)
  438. {
  439. ThrowIfDisposed();
  440. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  441. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  442. {
  443. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  444. bsonReader.ReadStartDocument();
  445. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  446. {
  447. bsonReader.SkipName();
  448. if (DeserializeBsonValue(context).Equals(value))
  449. {
  450. return true;
  451. }
  452. }
  453. bsonReader.ReadEndDocument();
  454. return false;
  455. }
  456. }
  457. /// <summary>
  458. /// Creates a deep clone of the document (see also Clone).
  459. /// </summary>
  460. /// <returns>
  461. /// A deep clone of the document.
  462. /// </returns>
  463. public override BsonValue DeepClone()
  464. {
  465. ThrowIfDisposed();
  466. return new RawBsonDocument(CloneSlice());
  467. }
  468. /// <summary>
  469. /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
  470. /// </summary>
  471. public void Dispose()
  472. {
  473. Dispose(true);
  474. GC.SuppressFinalize(this);
  475. }
  476. /// <summary>
  477. /// Gets an element of this document.
  478. /// </summary>
  479. /// <param name="index">The zero based index of the element.</param>
  480. /// <returns>
  481. /// The element.
  482. /// </returns>
  483. public override BsonElement GetElement(int index)
  484. {
  485. if (index < 0)
  486. {
  487. throw new ArgumentOutOfRangeException("index");
  488. }
  489. ThrowIfDisposed();
  490. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  491. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  492. {
  493. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  494. bsonReader.ReadStartDocument();
  495. var i = 0;
  496. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  497. {
  498. if (i == index)
  499. {
  500. var name = bsonReader.ReadName();
  501. var value = DeserializeBsonValue(context);
  502. return new BsonElement(name, value);
  503. }
  504. bsonReader.SkipName();
  505. bsonReader.SkipValue();
  506. i++;
  507. }
  508. bsonReader.ReadEndDocument();
  509. throw new ArgumentOutOfRangeException("index");
  510. }
  511. }
  512. /// <summary>
  513. /// Gets an element of this document.
  514. /// </summary>
  515. /// <param name="name">The name of the element.</param>
  516. /// <returns>
  517. /// A BsonElement.
  518. /// </returns>
  519. public override BsonElement GetElement(string name)
  520. {
  521. ThrowIfDisposed();
  522. BsonElement element;
  523. if (TryGetElement(name, out element))
  524. {
  525. return element;
  526. }
  527. string message = string.Format("Element '{0}' not found.", name);
  528. throw new KeyNotFoundException(message);
  529. }
  530. /// <summary>
  531. /// Gets an enumerator that can be used to enumerate the elements of this document.
  532. /// </summary>
  533. /// <returns>
  534. /// An enumerator.
  535. /// </returns>
  536. public override IEnumerator<BsonElement> GetEnumerator()
  537. {
  538. ThrowIfDisposed();
  539. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  540. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  541. {
  542. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  543. bsonReader.ReadStartDocument();
  544. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  545. {
  546. var name = bsonReader.ReadName();
  547. var value = DeserializeBsonValue(context);
  548. yield return new BsonElement(name, value);
  549. }
  550. bsonReader.ReadEndDocument();
  551. }
  552. }
  553. /// <summary>
  554. /// Gets the value of an element.
  555. /// </summary>
  556. /// <param name="index">The zero based index of the element.</param>
  557. /// <returns>
  558. /// The value of the element.
  559. /// </returns>
  560. public override BsonValue GetValue(int index)
  561. {
  562. if (index < 0)
  563. {
  564. throw new ArgumentOutOfRangeException("index");
  565. }
  566. ThrowIfDisposed();
  567. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  568. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  569. {
  570. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  571. bsonReader.ReadStartDocument();
  572. var i = 0;
  573. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  574. {
  575. bsonReader.SkipName();
  576. if (i == index)
  577. {
  578. return DeserializeBsonValue(context);
  579. }
  580. bsonReader.SkipValue();
  581. i++;
  582. }
  583. bsonReader.ReadEndDocument();
  584. throw new ArgumentOutOfRangeException("index");
  585. }
  586. }
  587. /// <summary>
  588. /// Gets the value of an element.
  589. /// </summary>
  590. /// <param name="name">The name of the element.</param>
  591. /// <returns>
  592. /// The value of the element.
  593. /// </returns>
  594. public override BsonValue GetValue(string name)
  595. {
  596. ThrowIfDisposed();
  597. BsonValue value;
  598. if (TryGetValue(name, out value))
  599. {
  600. return value;
  601. }
  602. string message = string.Format("Element '{0}' not found.", name);
  603. throw new KeyNotFoundException(message);
  604. }
  605. /// <summary>
  606. /// Gets the value of an element or a default value if the element is not found.
  607. /// </summary>
  608. /// <param name="name">The name of the element.</param>
  609. /// <param name="defaultValue">The default value returned if the element is not found.</param>
  610. /// <returns>
  611. /// The value of the element or the default value if the element is not found.
  612. /// </returns>
  613. public override BsonValue GetValue(string name, BsonValue defaultValue)
  614. {
  615. ThrowIfDisposed();
  616. BsonValue value;
  617. if (TryGetValue(name, out value))
  618. {
  619. return value;
  620. }
  621. return defaultValue;
  622. }
  623. /// <summary>
  624. /// Inserts a new element at a specified position.
  625. /// </summary>
  626. /// <param name="index">The position of the new element.</param>
  627. /// <param name="element">The element.</param>
  628. public override void InsertAt(int index, BsonElement element)
  629. {
  630. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  631. }
  632. /// <summary>
  633. /// Materializes the RawBsonDocument into a regular BsonDocument.
  634. /// </summary>
  635. /// <param name="binaryReaderSettings">The binary reader settings.</param>
  636. /// <returns>A BsonDocument.</returns>
  637. public BsonDocument Materialize(BsonBinaryReaderSettings binaryReaderSettings)
  638. {
  639. ThrowIfDisposed();
  640. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  641. using (var reader = new BsonBinaryReader(stream, binaryReaderSettings))
  642. {
  643. var context = BsonDeserializationContext.CreateRoot(reader);
  644. return BsonDocumentSerializer.Instance.Deserialize(context);
  645. }
  646. }
  647. /// <summary>
  648. /// Merges another document into this one. Existing elements are not overwritten.
  649. /// </summary>
  650. /// <param name="document">The other document.</param>
  651. /// <returns>
  652. /// The document (so method calls can be chained).
  653. /// </returns>
  654. public override BsonDocument Merge(BsonDocument document)
  655. {
  656. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  657. }
  658. /// <summary>
  659. /// Merges another document into this one, specifying whether existing elements are overwritten.
  660. /// </summary>
  661. /// <param name="document">The other document.</param>
  662. /// <param name="overwriteExistingElements">Whether to overwrite existing elements.</param>
  663. /// <returns>
  664. /// The document (so method calls can be chained).
  665. /// </returns>
  666. public override BsonDocument Merge(BsonDocument document, bool overwriteExistingElements)
  667. {
  668. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  669. }
  670. /// <summary>
  671. /// Removes an element from this document (if duplicate element names are allowed
  672. /// then all elements with this name will be removed).
  673. /// </summary>
  674. /// <param name="name">The name of the element to remove.</param>
  675. public override void Remove(string name)
  676. {
  677. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  678. }
  679. /// <summary>
  680. /// Removes an element from this document.
  681. /// </summary>
  682. /// <param name="index">The zero based index of the element to remove.</param>
  683. public override void RemoveAt(int index)
  684. {
  685. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  686. }
  687. /// <summary>
  688. /// Removes an element from this document.
  689. /// </summary>
  690. /// <param name="element">The element to remove.</param>
  691. public override void RemoveElement(BsonElement element)
  692. {
  693. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  694. }
  695. /// <summary>
  696. /// Sets the value of an element.
  697. /// </summary>
  698. /// <param name="index">The zero based index of the element whose value is to be set.</param>
  699. /// <param name="value">The new value.</param>
  700. /// <returns>
  701. /// The document (so method calls can be chained).
  702. /// </returns>
  703. public override BsonDocument Set(int index, BsonValue value)
  704. {
  705. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  706. }
  707. /// <summary>
  708. /// Sets the value of an element (an element will be added if no element with this name is found).
  709. /// </summary>
  710. /// <param name="name">The name of the element whose value is to be set.</param>
  711. /// <param name="value">The new value.</param>
  712. /// <returns>
  713. /// The document (so method calls can be chained).
  714. /// </returns>
  715. public override BsonDocument Set(string name, BsonValue value)
  716. {
  717. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  718. }
  719. /// <summary>
  720. /// Sets an element of the document (replaces any existing element with the same name or adds a new element if an element with the same name is not found).
  721. /// </summary>
  722. /// <param name="element">The new element.</param>
  723. /// <returns>
  724. /// The document.
  725. /// </returns>
  726. public override BsonDocument SetElement(BsonElement element)
  727. {
  728. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  729. }
  730. /// <summary>
  731. /// Sets an element of the document (replacing the existing element at that position).
  732. /// </summary>
  733. /// <param name="index">The zero based index of the element to replace.</param>
  734. /// <param name="element">The new element.</param>
  735. /// <returns>
  736. /// The document.
  737. /// </returns>
  738. public override BsonDocument SetElement(int index, BsonElement element)
  739. {
  740. throw new NotSupportedException("RawBsonDocument instances are immutable.");
  741. }
  742. /// <summary>
  743. /// Tries to get an element of this document.
  744. /// </summary>
  745. /// <param name="name">The name of the element.</param>
  746. /// <param name="element">The element.</param>
  747. /// <returns>
  748. /// True if an element with that name was found.
  749. /// </returns>
  750. public override bool TryGetElement(string name, out BsonElement element)
  751. {
  752. ThrowIfDisposed();
  753. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  754. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  755. {
  756. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  757. bsonReader.ReadStartDocument();
  758. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  759. {
  760. if (bsonReader.ReadName() == name)
  761. {
  762. var value = DeserializeBsonValue(context);
  763. element = new BsonElement(name, value);
  764. return true;
  765. }
  766. bsonReader.SkipValue();
  767. }
  768. bsonReader.ReadEndDocument();
  769. element = default(BsonElement);
  770. return false;
  771. }
  772. }
  773. /// <summary>
  774. /// Tries to get the value of an element of this document.
  775. /// </summary>
  776. /// <param name="name">The name of the element.</param>
  777. /// <param name="value">The value of the element.</param>
  778. /// <returns>
  779. /// True if an element with that name was found.
  780. /// </returns>
  781. public override bool TryGetValue(string name, out BsonValue value)
  782. {
  783. ThrowIfDisposed();
  784. using (var stream = new ByteBufferStream(_slice, ownsBuffer: false))
  785. using (var bsonReader = new BsonBinaryReader(stream, _readerSettings))
  786. {
  787. var context = BsonDeserializationContext.CreateRoot(bsonReader);
  788. bsonReader.ReadStartDocument();
  789. while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
  790. {
  791. if (bsonReader.ReadName() == name)
  792. {
  793. value = DeserializeBsonValue(context);
  794. return true;
  795. }
  796. bsonReader.SkipValue();
  797. }
  798. bsonReader.ReadEndDocument();
  799. value = null;
  800. return false;
  801. }
  802. }
  803. // protected methods
  804. /// <summary>
  805. /// Releases unmanaged and - optionally - managed resources.
  806. /// </summary>
  807. /// <param name="disposing"><c>true</c> to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param>
  808. protected virtual void Dispose(bool disposing)
  809. {
  810. if (!_disposed)
  811. {
  812. if (disposing)
  813. {
  814. if (_slice != null)
  815. {
  816. _slice.Dispose();
  817. _slice = null;
  818. }
  819. if (_disposableItems != null)
  820. {
  821. _disposableItems.ForEach(x => x.Dispose());
  822. _disposableItems = null;
  823. }
  824. }
  825. _disposed = true;
  826. }
  827. }
  828. /// <summary>
  829. /// Throws if disposed.
  830. /// </summary>
  831. /// <exception cref="System.ObjectDisposedException">RawBsonDocument</exception>
  832. protected void ThrowIfDisposed()
  833. {
  834. if (_disposed)
  835. {
  836. throw new ObjectDisposedException("RawBsonDocument");
  837. }
  838. }
  839. // private methods
  840. private IByteBuffer CloneSlice()
  841. {
  842. return _slice.GetSlice(0, _slice.Length);
  843. }
  844. private RawBsonArray DeserializeRawBsonArray(IBsonReader bsonReader)
  845. {
  846. var slice = bsonReader.ReadRawBsonArray();
  847. var nestedArray = new RawBsonArray(slice);
  848. _disposableItems.Add(nestedArray);
  849. return nestedArray;
  850. }
  851. private RawBsonDocument DeserializeRawBsonDocument(IBsonReader bsonReader)
  852. {
  853. var slice = bsonReader.ReadRawBsonDocument();
  854. var nestedDocument = new RawBsonDocument(slice);
  855. _disposableItems.Add(nestedDocument);
  856. return nestedDocument;
  857. }
  858. private BsonValue DeserializeBsonValue(BsonDeserializationContext context)
  859. {
  860. var bsonReader = context.Reader;
  861. switch (bsonReader.GetCurrentBsonType())
  862. {
  863. case BsonType.Array: return DeserializeRawBsonArray(bsonReader);
  864. case BsonType.Document: return DeserializeRawBsonDocument(bsonReader);
  865. default: return BsonValueSerializer.Instance.Deserialize(context);
  866. }
  867. }
  868. }
  869. }