| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293 |
- /* Copyright 2010-2016 MongoDB Inc.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using MongoDB.Bson.IO;
- using MongoDB.Bson.Serialization;
- using MongoDB.Bson.Serialization.Serializers;
- using MongoDB.Shared;
- namespace MongoDB.Bson
- {
- /// <summary>
- /// Represents a BSON document.
- /// </summary>
- #if NET45
- [Serializable]
- #endif
- public class BsonDocument : BsonValue, IComparable<BsonDocument>, IConvertibleToBsonDocument, IEnumerable<BsonElement>, IEquatable<BsonDocument>
- {
- // constants
- private const int __indexesThreshold = 8; // the _indexes dictionary will not be created until the document grows to contain 8 elements
- // private fields
- // use a list and a dictionary because we want to preserve the order in which the elements were added
- // if duplicate names are present only the first one will be in the dictionary (the others can only be accessed by index)
- private readonly List<BsonElement> _elements = new List<BsonElement>();
- private Dictionary<string, int> _indexes = null; // maps names to indexes into elements list (not created until there are enough elements to justify it)
- private bool _allowDuplicateNames;
- // constructors
- /// <summary>
- /// Initializes a new instance of the BsonDocument class.
- /// </summary>
- public BsonDocument()
- {
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class specifying whether duplicate element names are allowed
- /// (allowing duplicate element names is not recommended).
- /// </summary>
- /// <param name="allowDuplicateNames">Whether duplicate element names are allowed.</param>
- public BsonDocument(bool allowDuplicateNames)
- {
- _allowDuplicateNames = allowDuplicateNames;
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and adds one element.
- /// </summary>
- /// <param name="element">An element to add to the document.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(BsonElement element)
- {
- Add(element);
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">A dictionary to initialize the document from.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(Dictionary<string, object> dictionary)
- {
- AddRange(dictionary);
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">A dictionary to initialize the document from.</param>
- /// <param name="keys">A list of keys to select values from the dictionary.</param>
- [Obsolete("Use BsonDocument(IEnumerable<BsonElement> elements) instead.")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(Dictionary<string, object> dictionary, IEnumerable<string> keys)
- {
- Add(dictionary, keys);
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">A dictionary to initialize the document from.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(IEnumerable<KeyValuePair<string, object>> dictionary)
- {
- AddRange(dictionary);
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">A dictionary to initialize the document from.</param>
- /// <param name="keys">A list of keys to select values from the dictionary.</param>
- [Obsolete("Use BsonDocument(IEnumerable<BsonElement> elements) instead.")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(IDictionary<string, object> dictionary, IEnumerable<string> keys)
- {
- Add(dictionary, keys);
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">A dictionary to initialize the document from.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(IDictionary dictionary)
- {
- AddRange(dictionary);
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and adds new elements from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">A dictionary to initialize the document from.</param>
- /// <param name="keys">A list of keys to select values from the dictionary.</param>
- [Obsolete("Use BsonDocument(IEnumerable<BsonElement> elements) instead.")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(IDictionary dictionary, IEnumerable keys)
- {
- Add(dictionary, keys);
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and adds new elements from a list of elements.
- /// </summary>
- /// <param name="elements">A list of elements to add to the document.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(IEnumerable<BsonElement> elements)
- {
- AddRange(elements);
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and adds one or more elements.
- /// </summary>
- /// <param name="elements">One or more elements to add to the document.</param>
- [Obsolete("Use BsonDocument(IEnumerable<BsonElement> elements) instead.")]
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(params BsonElement[] elements)
- {
- Add(elements);
- }
- /// <summary>
- /// Initializes a new instance of the BsonDocument class and creates and adds a new element.
- /// </summary>
- /// <param name="name">The name of the element to add to the document.</param>
- /// <param name="value">The value of the element to add to the document.</param>
- [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
- public BsonDocument(string name, BsonValue value)
- {
- Add(name, value);
- }
- // public operators
- /// <summary>
- /// Compares two BsonDocument values.
- /// </summary>
- /// <param name="lhs">The first BsonDocument.</param>
- /// <param name="rhs">The other BsonDocument.</param>
- /// <returns>True if the two BsonDocument values are not equal according to ==.</returns>
- public static bool operator !=(BsonDocument lhs, BsonDocument rhs)
- {
- return !(lhs == rhs);
- }
- /// <summary>
- /// Compares two BsonDocument values.
- /// </summary>
- /// <param name="lhs">The first BsonDocument.</param>
- /// <param name="rhs">The other BsonDocument.</param>
- /// <returns>True if the two BsonDocument values are equal according to ==.</returns>
- public static bool operator ==(BsonDocument lhs, BsonDocument rhs)
- {
- return object.Equals(lhs, rhs); // handles lhs == null correctly
- }
- // public properties
- /// <summary>
- /// Gets or sets whether to allow duplicate names (allowing duplicate names is not recommended).
- /// </summary>
- public bool AllowDuplicateNames
- {
- get { return _allowDuplicateNames; }
- set { _allowDuplicateNames = value; }
- }
- /// <summary>
- /// Gets the BsonType of this BsonValue.
- /// </summary>
- public override BsonType BsonType
- {
- get { return BsonType.Document; }
- }
- // ElementCount could be greater than the number of Names if allowDuplicateNames is true
- /// <summary>
- /// Gets the number of elements.
- /// </summary>
- public virtual int ElementCount
- {
- get { return _elements.Count; }
- }
- /// <summary>
- /// Gets the elements.
- /// </summary>
- public virtual IEnumerable<BsonElement> Elements
- {
- get { return _elements; }
- }
- /// <summary>
- /// Gets the element names.
- /// </summary>
- public virtual IEnumerable<string> Names
- {
- get { return _elements.Select(e => e.Name); }
- }
- /// <summary>
- /// Gets the raw values (see BsonValue.RawValue).
- /// </summary>
- [Obsolete("Use Values instead.")]
- public virtual IEnumerable<object> RawValues
- {
- get { return _elements.Select(e => e.Value.RawValue); }
- }
- /// <summary>
- /// Gets the values.
- /// </summary>
- public virtual IEnumerable<BsonValue> Values
- {
- get { return _elements.Select(e => e.Value); }
- }
- // public indexers
- // note: the return type of the indexers is BsonValue and NOT BsonElement so that we can write code like:
- // BsonDocument car;
- // car["color"] = "red"; // changes value of existing element or adds new element
- // note: we are using implicit conversion from string to BsonValue
- // to convert the returned BsonValue to a .NET type you have two approaches (explicit cast or As method):
- // string color = (string) car["color"]; // throws exception if value is not a string (returns null if not found)
- // string color = car["color"].AsString; // throws exception if value is not a string (results in a NullReferenceException if not found)
- // string color = car["color", "none"].AsString; // throws exception if value is not a string (default to "none" if not found)
- // the second approach offers a more fluent interface (with fewer parenthesis!)
- // string name = car["brand"].AsBsonSymbol.Name;
- // string name = ((BsonSymbol) car["brand"]).Name; // the extra parenthesis are required and harder to read
- // there are also some conversion methods (and note that ToBoolean uses the JavaScript definition of truthiness)
- // bool ok = result["ok"].ToBoolean(); // works whether ok is false, true, 0, 0.0, 1, 1.0, "", "xyz", BsonNull.Value, etc...
- // bool ok = result["ok", false].ToBoolean(); // defaults to false if ok element is not found
- // int n = result["n"].ToInt32(); // works whether n is Int32, Int64, Double or String (if it can be parsed)
- // long n = result["n"].ToInt64(); // works whether n is Int32, Int64, Double or String (if it can be parsed)
- // double d = result["n"].ToDouble(); // works whether d is Int32, Int64, Double or String (if it can be parsed)
- // to work in terms of BsonElements use Add, GetElement and SetElement
- // car.Add(new BsonElement("color", "red")); // might throw exception if allowDuplicateNames is false
- // car.SetElement(new BsonElement("color", "red")); // replaces existing element or adds new element
- // BsonElement colorElement = car.GetElement("color"); // returns null if element "color" is not found
- /// <summary>
- /// Gets or sets a value by position.
- /// </summary>
- /// <param name="index">The position.</param>
- /// <returns>The value.</returns>
- public override BsonValue this[int index]
- {
- get { return _elements[index].Value; }
- set
- {
- if (value == null)
- {
- throw new ArgumentNullException("value");
- }
- _elements[index] = new BsonElement(_elements[index].Name, value);
- }
- }
- /// <summary>
- /// Gets the value of an element or a default value if the element is not found.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <param name="defaultValue">The default value to return if the element is not found.</param>
- /// <returns>Teh value of the element or a default value if the element is not found.</returns>
- [Obsolete("Use GetValue(string name, BsonValue defaultValue) instead.")]
- public virtual BsonValue this[string name, BsonValue defaultValue]
- {
- get { return GetValue(name, defaultValue); }
- }
- /// <summary>
- /// Gets or sets a value by name.
- /// </summary>
- /// <param name="name">The name.</param>
- /// <returns>The value.</returns>
- public override BsonValue this[string name]
- {
- get
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- var index = IndexOfName(name);
- if (index != -1)
- {
- return _elements[index].Value;
- }
- else
- {
- string message = string.Format("Element '{0}' not found.", name);
- throw new KeyNotFoundException(message);
- }
- }
- set
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- if (value == null)
- {
- throw new ArgumentNullException("value");
- }
- var index = IndexOfName(name);
- if (index != -1)
- {
- _elements[index] = new BsonElement(name, value);
- }
- else
- {
- Add(new BsonElement(name, value));
- }
- }
- }
- // public static methods
- /// <summary>
- /// Creates a new BsonDocument by mapping an object to a BsonDocument.
- /// </summary>
- /// <param name="value">The object to be mapped to a BsonDocument.</param>
- /// <returns>A BsonDocument.</returns>
- public new static BsonDocument Create(object value)
- {
- if (value == null)
- {
- throw new ArgumentNullException("value");
- }
- return (BsonDocument)BsonTypeMapper.MapToBsonValue(value, BsonType.Document);
- }
- /// <summary>
- /// Parses a JSON string and returns a BsonDocument.
- /// </summary>
- /// <param name="json">The JSON string.</param>
- /// <returns>A BsonDocument.</returns>
- public static BsonDocument Parse(string json)
- {
- using (var jsonReader = new JsonReader(json))
- {
- var context = BsonDeserializationContext.CreateRoot(jsonReader);
- var document = BsonDocumentSerializer.Instance.Deserialize(context);
- if (!jsonReader.IsAtEndOfFile())
- {
- throw new FormatException("String contains extra non-whitespace characters beyond the end of the document.");
- }
- return document;
- }
- }
- // public methods
- /// <summary>
- /// Adds an element to the document.
- /// </summary>
- /// <param name="element">The element to add.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument Add(BsonElement element)
- {
- var isDuplicate = IndexOfName(element.Name) != -1;
- if (isDuplicate && !_allowDuplicateNames)
- {
- var message = string.Format("Duplicate element name '{0}'.", element.Name);
- throw new InvalidOperationException(message);
- }
- else
- {
- _elements.Add(element);
- if (!isDuplicate)
- {
- if (_indexes == null)
- {
- RebuildIndexes();
- }
- else
- {
- _indexes.Add(element.Name, _elements.Count - 1); // index of the newly added element
- }
- }
- }
- return this;
- }
- /// <summary>
- /// Adds elements to the document from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">The dictionary.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- [Obsolete("Use AddRange instead.")]
- public virtual BsonDocument Add(Dictionary<string, object> dictionary)
- {
- return AddRange(dictionary);
- }
- /// <summary>
- /// Adds elements to the document from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">The dictionary.</param>
- /// <param name="keys">Which keys of the hash table to add.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
- public virtual BsonDocument Add(Dictionary<string, object> dictionary, IEnumerable<string> keys)
- {
- return Add((IDictionary<string, object>)dictionary, keys);
- }
- /// <summary>
- /// Adds elements to the document from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">The dictionary.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- [Obsolete("Use AddRange instead.")]
- public virtual BsonDocument Add(IDictionary<string, object> dictionary)
- {
- return AddRange(dictionary);
- }
- /// <summary>
- /// Adds elements to the document from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">The dictionary.</param>
- /// <param name="keys">Which keys of the hash table to add.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
- public virtual BsonDocument Add(IDictionary<string, object> dictionary, IEnumerable<string> keys)
- {
- if (dictionary == null)
- {
- throw new ArgumentNullException("dictionary");
- }
- if (keys == null)
- {
- throw new ArgumentNullException("keys");
- }
- foreach (var key in keys)
- {
- Add(key, BsonTypeMapper.MapToBsonValue(dictionary[key]));
- }
- return this;
- }
- /// <summary>
- /// Adds elements to the document from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">The dictionary.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- [Obsolete("Use AddRange instead.")]
- public virtual BsonDocument Add(IDictionary dictionary)
- {
- return AddRange(dictionary);
- }
- /// <summary>
- /// Adds elements to the document from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">The dictionary.</param>
- /// <param name="keys">Which keys of the hash table to add.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
- public virtual BsonDocument Add(IDictionary dictionary, IEnumerable keys)
- {
- if (dictionary == null)
- {
- throw new ArgumentNullException("dictionary");
- }
- if (keys == null)
- {
- throw new ArgumentNullException("keys");
- }
- foreach (var key in keys)
- {
- if (key == null)
- {
- throw new ArgumentException("keys", "A key passed to BsonDocument.Add is null.");
- }
- if (key.GetType() != typeof(string))
- {
- throw new ArgumentOutOfRangeException("keys", "A key passed to BsonDocument.Add is not a string.");
- }
- Add((string)key, BsonTypeMapper.MapToBsonValue(dictionary[key]));
- }
- return this;
- }
- /// <summary>
- /// Adds a list of elements to the document.
- /// </summary>
- /// <param name="elements">The list of elements.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- [Obsolete("Use AddRange instead.")]
- public virtual BsonDocument Add(IEnumerable<BsonElement> elements)
- {
- return AddRange(elements);
- }
- /// <summary>
- /// Adds a list of elements to the document.
- /// </summary>
- /// <param name="elements">The list of elements.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- [Obsolete("Use AddRange(IEnumerable<BsonElement> elements) instead.")]
- public virtual BsonDocument Add(params BsonElement[] elements)
- {
- return AddRange((IEnumerable<BsonElement>)elements);
- }
- /// <summary>
- /// Creates and adds an element to the document.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <param name="value">The value of the element.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument Add(string name, BsonValue value)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- if (value == null)
- {
- throw new ArgumentNullException("value");
- }
- Add(new BsonElement(name, value));
- return this;
- }
- /// <summary>
- /// Creates and adds an element to the document, but only if the condition is true.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <param name="value">The value of the element.</param>
- /// <param name="condition">Whether to add the element to the document.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument Add(string name, BsonValue value, bool condition)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- if (condition)
- {
- // don't check for null value unless condition is true
- if (value == null)
- {
- throw new ArgumentNullException("value");
- }
- Add(new BsonElement(name, value));
- }
- return this;
- }
- /// <summary>
- /// Creates and adds an element to the document, but only if the condition is true.
- /// If the condition is false the value factory is not called at all.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <param name="valueFactory">A delegate called to compute the value of the element if condition is true.</param>
- /// <param name="condition">Whether to add the element to the document.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument Add(string name, Func<BsonValue> valueFactory, bool condition)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- if (valueFactory == null)
- {
- throw new ArgumentNullException("valueFactory");
- }
- if (condition)
- {
- Add(new BsonElement(name, valueFactory()));
- }
- return this;
- }
- /// <summary>
- /// Adds elements to the document from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">The dictionary.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument AddRange(Dictionary<string, object> dictionary)
- {
- return AddRange((IEnumerable<KeyValuePair<string, object>>)dictionary);
- }
- /// <summary>
- /// Adds elements to the document from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">The dictionary.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument AddRange(IDictionary dictionary)
- {
- if (dictionary == null)
- {
- throw new ArgumentNullException("dictionary");
- }
- foreach (DictionaryEntry entry in dictionary)
- {
- if (entry.Key == null)
- {
- throw new ArgumentException("keys", "A key passed to BsonDocument.AddRange is null.");
- }
- if (entry.Key.GetType() != typeof(string))
- {
- throw new ArgumentOutOfRangeException("dictionary", "One or more keys in the dictionary passed to BsonDocument.AddRange is not a string.");
- }
- Add((string)entry.Key, BsonTypeMapper.MapToBsonValue(entry.Value));
- }
- return this;
- }
- /// <summary>
- /// Adds a list of elements to the document.
- /// </summary>
- /// <param name="elements">The list of elements.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument AddRange(IEnumerable<BsonElement> elements)
- {
- if (elements == null)
- {
- throw new ArgumentNullException("elements");
- }
- foreach (var element in elements)
- {
- Add(element);
- }
- return this;
- }
- /// <summary>
- /// Adds elements to the document from a dictionary of key/value pairs.
- /// </summary>
- /// <param name="dictionary">The dictionary.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument AddRange(IEnumerable<KeyValuePair<string, object>> dictionary)
- {
- if (dictionary == null)
- {
- throw new ArgumentNullException("dictionary");
- }
- foreach (var entry in dictionary)
- {
- Add(entry.Key, BsonTypeMapper.MapToBsonValue(entry.Value));
- }
- return this;
- }
- /// <summary>
- /// Clears the document (removes all elements).
- /// </summary>
- public virtual void Clear()
- {
- _elements.Clear();
- _indexes = null;
- }
- /// <summary>
- /// Creates a shallow clone of the document (see also DeepClone).
- /// </summary>
- /// <returns>A shallow clone of the document.</returns>
- public override BsonValue Clone()
- {
- BsonDocument clone = new BsonDocument();
- foreach (BsonElement element in _elements)
- {
- clone.Add(element.Clone());
- }
- return clone;
- }
- /// <summary>
- /// Compares this document to another document.
- /// </summary>
- /// <param name="rhs">The other document.</param>
- /// <returns>A 32-bit signed integer that indicates whether this document is less than, equal to, or greather than the other.</returns>
- public virtual int CompareTo(BsonDocument rhs)
- {
- if (rhs == null) { return 1; }
- // lhs and rhs might be subclasses of BsonDocument
- using (var lhsEnumerator = Elements.GetEnumerator())
- using (var rhsEnumerator = rhs.Elements.GetEnumerator())
- {
- while (true)
- {
- var lhsHasNext = lhsEnumerator.MoveNext();
- var rhsHasNext = rhsEnumerator.MoveNext();
- if (!lhsHasNext && !rhsHasNext) { return 0; }
- if (!lhsHasNext) { return -1; }
- if (!rhsHasNext) { return 1; }
- var lhsElement = lhsEnumerator.Current;
- var rhsElement = rhsEnumerator.Current;
- var result = lhsElement.Name.CompareTo(rhsElement.Name);
- if (result != 0) { return result; }
- result = lhsElement.Value.CompareTo(rhsElement.Value);
- if (result != 0) { return result; }
- }
- }
- }
- /// <summary>
- /// Compares the BsonDocument to another BsonValue.
- /// </summary>
- /// <param name="other">The other BsonValue.</param>
- /// <returns>A 32-bit signed integer that indicates whether this BsonDocument is less than, equal to, or greather than the other BsonValue.</returns>
- public override int CompareTo(BsonValue other)
- {
- if (other == null) { return 1; }
- var otherDocument = other as BsonDocument;
- if (otherDocument != null)
- {
- return CompareTo(otherDocument);
- }
- return CompareTypeTo(other);
- }
- /// <summary>
- /// Tests whether the document contains an element with the specified name.
- /// </summary>
- /// <param name="name">The name of the element to look for.</param>
- /// <returns>True if the document contains an element with the specified name.</returns>
- public virtual bool Contains(string name)
- {
- return IndexOfName(name) != -1;
- }
- /// <summary>
- /// Tests whether the document contains an element with the specified value.
- /// </summary>
- /// <param name="value">The value of the element to look for.</param>
- /// <returns>True if the document contains an element with the specified value.</returns>
- public virtual bool ContainsValue(BsonValue value)
- {
- if (value == null)
- {
- throw new ArgumentNullException("value");
- }
- return _elements.Any(e => e.Value == value);
- }
- /// <summary>
- /// Creates a deep clone of the document (see also Clone).
- /// </summary>
- /// <returns>A deep clone of the document.</returns>
- public override BsonValue DeepClone()
- {
- BsonDocument clone = new BsonDocument();
- foreach (BsonElement element in _elements)
- {
- clone.Add(element.DeepClone());
- }
- return clone;
- }
- /// <summary>
- /// Compares this document to another document.
- /// </summary>
- /// <param name="obj">The other document.</param>
- /// <returns>True if the two documents are equal.</returns>
- public bool Equals(BsonDocument obj)
- {
- return Equals((object)obj); // handles obj == null correctly
- }
- /// <summary>
- /// Compares this BsonDocument to another object.
- /// </summary>
- /// <param name="obj">The other object.</param>
- /// <returns>True if the other object is a BsonDocument and equal to this one.</returns>
- public override bool Equals(object obj)
- {
- if (object.ReferenceEquals(obj, null) || !(obj is BsonDocument)) { return false; }
- // lhs and rhs might be subclasses of BsonDocument
- var rhs = (BsonDocument)obj;
- return Elements.SequenceEqual(rhs.Elements);
- }
- /// <summary>
- /// Gets an element of this document.
- /// </summary>
- /// <param name="index">The zero based index of the element.</param>
- /// <returns>The element.</returns>
- public virtual BsonElement GetElement(int index)
- {
- return _elements[index];
- }
- /// <summary>
- /// Gets an element of this document.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <returns>A BsonElement.</returns>
- public virtual BsonElement GetElement(string name)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- var index = IndexOfName(name);
- if (index != -1)
- {
- return _elements[index];
- }
- else
- {
- string message = string.Format("Element '{0}' not found.", name);
- throw new KeyNotFoundException(message);
- }
- }
- /// <summary>
- /// Gets an enumerator that can be used to enumerate the elements of this document.
- /// </summary>
- /// <returns>An enumerator.</returns>
- public virtual IEnumerator<BsonElement> GetEnumerator()
- {
- return _elements.GetEnumerator();
- }
- /// <summary>
- /// Gets the hash code.
- /// </summary>
- /// <returns>The hash code.</returns>
- public override int GetHashCode()
- {
- return new Hasher()
- .Hash(BsonType)
- .HashElements(Elements)
- .GetHashCode();
- }
- /// <summary>
- /// Gets the value of an element.
- /// </summary>
- /// <param name="index">The zero based index of the element.</param>
- /// <returns>The value of the element.</returns>
- public virtual BsonValue GetValue(int index)
- {
- return this[index];
- }
- /// <summary>
- /// Gets the value of an element.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <returns>The value of the element.</returns>
- public virtual BsonValue GetValue(string name)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- return this[name];
- }
- /// <summary>
- /// Gets the value of an element or a default value if the element is not found.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <param name="defaultValue">The default value returned if the element is not found.</param>
- /// <returns>The value of the element or the default value if the element is not found.</returns>
- public virtual BsonValue GetValue(string name, BsonValue defaultValue)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- var index = IndexOfName(name);
- if (index != -1)
- {
- return _elements[index].Value;
- }
- else
- {
- return defaultValue;
- }
- }
- /// <summary>
- /// Gets the index of an element.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <returns>The index of the element, or -1 if the element is not found.</returns>
- public virtual int IndexOfName(string name)
- {
- if (_indexes == null)
- {
- var count = _elements.Count;
- for (var index = 0; index < count; index++)
- {
- if (_elements[index].Name == name)
- {
- return index;
- }
- }
- return -1;
- }
- else
- {
- int index;
- if (_indexes.TryGetValue(name, out index))
- {
- return index;
- }
- else
- {
- return -1;
- }
- }
- }
- /// <summary>
- /// Inserts a new element at a specified position.
- /// </summary>
- /// <param name="index">The position of the new element.</param>
- /// <param name="element">The element.</param>
- public virtual void InsertAt(int index, BsonElement element)
- {
- var isDuplicate = IndexOfName(element.Name) != -1;
- if (isDuplicate && !_allowDuplicateNames)
- {
- var message = string.Format("Duplicate element name '{0}' not allowed.", element.Name);
- throw new InvalidOperationException(message);
- }
- else
- {
- _elements.Insert(index, element);
- RebuildIndexes();
- }
- }
- /// <summary>
- /// Merges another document into this one. Existing elements are not overwritten.
- /// </summary>
- /// <param name="document">The other document.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument Merge(BsonDocument document)
- {
- Merge(document, false); // don't overwriteExistingElements
- return this;
- }
- /// <summary>
- /// Merges another document into this one, specifying whether existing elements are overwritten.
- /// </summary>
- /// <param name="document">The other document.</param>
- /// <param name="overwriteExistingElements">Whether to overwrite existing elements.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument Merge(BsonDocument document, bool overwriteExistingElements)
- {
- if (document == null)
- {
- throw new ArgumentNullException("document");
- }
- foreach (BsonElement element in document)
- {
- if (overwriteExistingElements || !Contains(element.Name))
- {
- this[element.Name] = element.Value;
- }
- }
- return this;
- }
- /// <summary>
- /// Removes an element from this document (if duplicate element names are allowed
- /// then all elements with this name will be removed).
- /// </summary>
- /// <param name="name">The name of the element to remove.</param>
- public virtual void Remove(string name)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- if (_allowDuplicateNames)
- {
- var count = _elements.Count;
- var removedAny = false;
- for (var i = count - 1; i >= 0; i--)
- {
- if (_elements[i].Name == name)
- {
- _elements.RemoveAt(i);
- removedAny = true;
- }
- }
- if (removedAny)
- {
- RebuildIndexes();
- }
- }
- else
- {
- var index = IndexOfName(name);
- if (index != -1)
- {
- _elements.RemoveAt(index);
- RebuildIndexes();
- }
- }
- }
- /// <summary>
- /// Removes an element from this document.
- /// </summary>
- /// <param name="index">The zero based index of the element to remove.</param>
- public virtual void RemoveAt(int index)
- {
- _elements.RemoveAt(index);
- RebuildIndexes();
- }
- /// <summary>
- /// Removes an element from this document.
- /// </summary>
- /// <param name="element">The element to remove.</param>
- public virtual void RemoveElement(BsonElement element)
- {
- if (_elements.Remove(element))
- {
- RebuildIndexes();
- }
- }
- /// <summary>
- /// Sets the value of an element.
- /// </summary>
- /// <param name="index">The zero based index of the element whose value is to be set.</param>
- /// <param name="value">The new value.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument Set(int index, BsonValue value)
- {
- if (value == null)
- {
- throw new ArgumentNullException("value");
- }
- this[index] = value;
- return this;
- }
- /// <summary>
- /// Sets the value of an element (an element will be added if no element with this name is found).
- /// </summary>
- /// <param name="name">The name of the element whose value is to be set.</param>
- /// <param name="value">The new value.</param>
- /// <returns>The document (so method calls can be chained).</returns>
- public virtual BsonDocument Set(string name, BsonValue value)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- if (value == null)
- {
- throw new ArgumentNullException("value");
- }
- this[name] = value;
- return this;
- }
- /// <summary>
- /// Sets an element of the document (replacing the existing element at that position).
- /// </summary>
- /// <param name="index">The zero based index of the element to replace.</param>
- /// <param name="element">The new element.</param>
- /// <returns>The document.</returns>
- public virtual BsonDocument SetElement(int index, BsonElement element)
- {
- var oldName = _elements[index].Name;
- _elements[index] = element;
- if (element.Name != oldName)
- {
- RebuildIndexes();
- }
- return this;
- }
- /// <summary>
- /// 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).
- /// </summary>
- /// <param name="element">The new element.</param>
- /// <returns>The document.</returns>
- public virtual BsonDocument SetElement(BsonElement element)
- {
- var index = IndexOfName(element.Name);
- if (index != -1)
- {
- _elements[index] = element;
- }
- else
- {
- Add(element);
- }
- return this;
- }
- /// <summary>
- /// Converts the BsonDocument to a Dictionary<string, object>.
- /// </summary>
- /// <returns>A dictionary.</returns>
- public Dictionary<string, object> ToDictionary()
- {
- var options = new BsonTypeMapperOptions
- {
- DuplicateNameHandling = DuplicateNameHandling.ThrowException,
- MapBsonArrayTo = typeof(object[]), // TODO: should this be List<object>?
- MapBsonDocumentTo = typeof(Dictionary<string, object>),
- MapOldBinaryToByteArray = false
- };
- return (Dictionary<string, object>)BsonTypeMapper.MapToDotNetValue(this, options);
- }
- /// <summary>
- /// Converts the BsonDocument to a Hashtable.
- /// </summary>
- /// <returns>A hashtable.</returns>
- public Hashtable ToHashtable()
- {
- var options = new BsonTypeMapperOptions
- {
- DuplicateNameHandling = DuplicateNameHandling.ThrowException,
- MapBsonArrayTo = typeof(object[]), // TODO: should this be ArrayList?
- MapBsonDocumentTo = typeof(Hashtable),
- MapOldBinaryToByteArray = false
- };
- return (Hashtable)BsonTypeMapper.MapToDotNetValue(this, options);
- }
- /// <summary>
- /// Returns a string representation of the document.
- /// </summary>
- /// <returns>A string representation of the document.</returns>
- public override string ToString()
- {
- return this.ToJson();
- }
- /// <summary>
- /// Tries to get an element of this document.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <param name="value">The element.</param>
- /// <returns>True if an element with that name was found.</returns>
- public virtual bool TryGetElement(string name, out BsonElement value)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- var index = IndexOfName(name);
- if (index != -1)
- {
- value = _elements[index];
- return true;
- }
- else
- {
- value = default(BsonElement);
- return false;
- }
- }
- /// <summary>
- /// Tries to get the value of an element of this document.
- /// </summary>
- /// <param name="name">The name of the element.</param>
- /// <param name="value">The value of the element.</param>
- /// <returns>True if an element with that name was found.</returns>
- public virtual bool TryGetValue(string name, out BsonValue value)
- {
- if (name == null)
- {
- throw new ArgumentNullException("name");
- }
- var index = IndexOfName(name);
- if (index != -1)
- {
- value = _elements[index].Value;
- return true;
- }
- else
- {
- value = null;
- return false;
- }
- }
- // private methods
- private void RebuildIndexes()
- {
- if (_elements.Count < __indexesThreshold)
- {
- _indexes = null;
- return;
- }
- if (_indexes == null)
- {
- _indexes = new Dictionary<string, int>();
- }
- else
- {
- _indexes.Clear();
- }
- // process the elements in reverse order so that in case of duplicates the dictionary ends up pointing at the first one
- var count = _elements.Count;
- for (int index = count - 1; index >= 0; index--)
- {
- BsonElement element = _elements[index];
- _indexes[element.Name] = index;
- }
- }
- // explicit interface implementations
- BsonDocument IConvertibleToBsonDocument.ToBsonDocument()
- {
- return this;
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- }
- }
|