// public methods
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            var arraySerializationOptions = EnsureSerializationOptions<ArraySerializationOptions>(options);
            var itemSerializationOptions = arraySerializationOptions.ItemSerializationOptions;

            var bsonType = bsonReader.GetCurrentBsonType();
            switch (bsonType)
            {
                case BsonType.Null:
                    bsonReader.ReadNull();
                    return null;

                case BsonType.Array:
                    var instance = CreateInstance(actualType);
                    var itemDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));
                    Type lastItemType = null;
                    IBsonSerializer lastItemSerializer = null;

                    bsonReader.ReadStartArray();
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        var itemType = itemDiscriminatorConvention.GetActualType(bsonReader, typeof(object));
                        IBsonSerializer itemSerializer;
                        if (itemType == lastItemType)
                        {
                            itemSerializer = lastItemSerializer;
                        }
                        else
                        {
                            itemSerializer = BsonSerializer.LookupSerializer(itemType);
                            lastItemType = itemType;
                            lastItemSerializer = itemSerializer;
                        }
                        var item = itemSerializer.Deserialize(bsonReader, typeof(object), itemType, itemSerializationOptions);
                        AddItem(instance, item);
                    }
                    bsonReader.ReadEndArray();

                    return FinalizeResult(instance, actualType);

                case BsonType.Document:
                    bsonReader.ReadStartDocument();
                    bsonReader.ReadString("_t"); // skip over discriminator
                    bsonReader.ReadName("_v");
                    var value = Deserialize(bsonReader, actualType, actualType, options);
                    bsonReader.ReadEndDocument();
                    return value;

                default:
                    var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType);
                    throw new FileFormatException(message);
            }
        }
Exemplo n.º 2
0
        public void TestJavaScript()
        {
            string json = "{ \"$code\" : \"function f() { return 1; }\" }";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.JavaScript, bsonReader.ReadBsonType());
                Assert.AreEqual("function f() { return 1; }", bsonReader.ReadJavaScript());
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonJavaScript>(new StringReader(json)).ToJson());
        }
Exemplo n.º 3
0
        public void TestStringEmpty()
        {
            var json = "\"\"";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.String, bsonReader.ReadBsonType());
                Assert.AreEqual("", bsonReader.ReadString());
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <string>(new StringReader(json)).ToJson());
        }
Exemplo n.º 4
0
        public void TestMinKey()
        {
            var json = "{ \"$minkey\" : 1 }";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.MinKey, bsonReader.ReadBsonType());
                bsonReader.ReadMinKey();
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonMinKey>(new StringReader(json)).ToJson());
        }
Exemplo n.º 5
0
 public static IEnumerable <T> StringReader <T>(string text)
 {
     using (StringReader stringReader = new StringReader(text))
     {
         BsonReader reader = BsonReader.Create(stringReader);
         while (reader.ReadBsonType() != BsonType.EndOfDocument)
         {
             yield return(BsonSerializer.Deserialize <T>(reader));
         }
     }
 }
Exemplo n.º 6
0
        public void TestNestedDocument()
        {
            var json = "{ \"a\" : { \"b\" : 1, \"c\" : 2 } }";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.Document, bsonReader.ReadBsonType());
                bsonReader.ReadStartDocument();
                Assert.AreEqual(BsonType.Document, bsonReader.ReadBsonType());
                Assert.AreEqual("a", bsonReader.ReadName());
                bsonReader.ReadStartDocument();
                Assert.AreEqual("b", bsonReader.ReadName());
                Assert.AreEqual(1, bsonReader.ReadInt32());
                Assert.AreEqual("c", bsonReader.ReadName());
                Assert.AreEqual(2, bsonReader.ReadInt32());
                bsonReader.ReadEndDocument();
                bsonReader.ReadEndDocument();
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(new StringReader(json)).ToJson());
        }
Exemplo n.º 7
0
        public void TestUndefined()
        {
            var json = "undefined";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.Undefined, bsonReader.ReadBsonType());
                bsonReader.ReadUndefined();
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonUndefined>(new StringReader(json)).ToJson());
        }
Exemplo n.º 8
0
        public void TestSymbol()
        {
            var json = "{ \"$symbol\" : \"symbol\" }";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.Symbol, bsonReader.ReadBsonType());
                Assert.AreEqual("symbol", bsonReader.ReadSymbol());
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonSymbol>(new StringReader(json)).ToJson());
        }
Exemplo n.º 9
0
        public void TestTimestamp()
        {
            var json = "{ \"$timestamp\" : NumberLong(1234) }";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.Timestamp, bsonReader.ReadBsonType());
                Assert.AreEqual(1234L, bsonReader.ReadTimestamp());
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonTimestamp>(new StringReader(json)).ToJson());
        }
Exemplo n.º 10
0
        public void TestNull()
        {
            var json = "null";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.Null, bsonReader.ReadBsonType());
                bsonReader.ReadNull();
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonNull>(new StringReader(json)).ToJson());
        }
Exemplo n.º 11
0
        public void TestDocumentTwoElements()
        {
            var json = "{ \"x\" : 1, \"y\" : 2 }";

            using (_bsonReader = BsonReader.Create(json))
            {
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReadStartDocument();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                Assert.AreEqual("x", _bsonReader.ReadName());
                Assert.AreEqual(1, _bsonReader.ReadInt32());
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                Assert.AreEqual("y", _bsonReader.ReadName());
                Assert.AreEqual(2, _bsonReader.ReadInt32());
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReadEndDocument();
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(new StringReader(json)).ToJson());
        }
Exemplo n.º 12
0
        public void TestInt64NumberLong()
        {
            var json = "NumberLong(123)";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.Int64, bsonReader.ReadBsonType());
                Assert.AreEqual(123, bsonReader.ReadInt64());
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <long>(new StringReader(json)).ToJson());
        }
Exemplo n.º 13
0
        public void TestInt32()
        {
            var json = "123";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType());
                Assert.AreEqual(123, bsonReader.ReadInt32());
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <int>(new StringReader(json)).ToJson());
        }
Exemplo n.º 14
0
        public void TestDouble()
        {
            var json = "1.5";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.Double, bsonReader.ReadBsonType());
                Assert.AreEqual(1.5, bsonReader.ReadDouble());
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <double>(new StringReader(json)).ToJson());
        }
Exemplo n.º 15
0
        public void TestDateTimeMaxBson()
        {
            var json = "new Date(9223372036854775807)";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.DateTime, bsonReader.ReadBsonType());
                Assert.AreEqual(9223372036854775807, bsonReader.ReadDateTime());
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDateTime>(new StringReader(json)).ToJson());
        }
Exemplo n.º 16
0
        public void TestBooleanTrue()
        {
            var json = "true";

            using (bsonReader = BsonReader.Create(json)) {
                Assert.AreEqual(BsonType.Boolean, bsonReader.ReadBsonType());
                Assert.AreEqual(true, bsonReader.ReadBoolean());
                Assert.AreEqual(BsonReaderState.Done, bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <bool>(new StringReader(json)).ToJson());
        }
Exemplo n.º 17
0
        public void TestInt32Constructor(string json)
        {
            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                Assert.AreEqual(123, _bsonReader.ReadInt32());
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            var canonicalJson = "123";

            Assert.AreEqual(canonicalJson, BsonSerializer.Deserialize <int>(new StringReader(json)).ToJson());
        }
Exemplo n.º 18
0
        public void TestUndefined()
        {
            var json = "undefined";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Undefined, _bsonReader.ReadBsonType());
                _bsonReader.ReadUndefined();
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonUndefined>(json).ToJson());
        }
Exemplo n.º 19
0
        public void TestTimestampConstructor()
        {
            var json = "Timestamp(1, 2)";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Timestamp, _bsonReader.ReadBsonType());
                Assert.AreEqual(new BsonTimestamp(1, 2).Value, _bsonReader.ReadTimestamp());
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonTimestamp>(new StringReader(json)).ToJson());
        }
Exemplo n.º 20
0
        public void TestDateTimeMinBson()
        {
            var json = "new Date(-9223372036854775808)";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.DateTime, _bsonReader.ReadBsonType());
                Assert.AreEqual(-9223372036854775808, _bsonReader.ReadDateTime());
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDateTime>(json).ToJson());
        }
Exemplo n.º 21
0
        public void TestInt64ConstructorUnqutoed()
        {
            var json = "NumberLong(123)";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Int64, _bsonReader.ReadBsonType());
                Assert.AreEqual(123, _bsonReader.ReadInt64());
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <long>(json).ToJson());
        }
Exemplo n.º 22
0
        public void TestBooleanFalse()
        {
            var json = "false";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Boolean, _bsonReader.ReadBsonType());
                Assert.AreEqual(false, _bsonReader.ReadBoolean());
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <bool>(json).ToJson());
        }
Exemplo n.º 23
0
        public void TestMinKeyKeyword()
        {
            var json = "MinKey";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.MinKey, _bsonReader.ReadBsonType());
                _bsonReader.ReadMinKey();
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonMinKey>(new StringReader(json)).ToJson());
        }
Exemplo n.º 24
0
        public void TestString()
        {
            var json = "\"abc\"";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.String, _bsonReader.ReadBsonType());
                Assert.AreEqual("abc", _bsonReader.ReadString());
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <string>(json).ToJson());
        }
Exemplo n.º 25
0
        public static BsonDocument ReadBsonDocumentWOStartEnd(BsonReader bsonReader)
        {
            var document = new BsonDocument();

            while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
            {
                var name  = bsonReader.ReadName();
                var value = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
                document.Add(name, value);
            }
            return(document);
        }
Exemplo n.º 26
0
        public void TestNull()
        {
            var json = "null";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Null, _bsonReader.ReadBsonType());
                _bsonReader.ReadNull();
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonNull>(json).ToJson());
        }
Exemplo n.º 27
0
        public void TestMinKey()
        {
            var json = "{ \"$minkey\" : 1 }";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.MinKey, _bsonReader.ReadBsonType());
                _bsonReader.ReadMinKey();
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonMinKey>(json).ToJson());
        }
Exemplo n.º 28
0
        public void TestInt64()
        {
            var json = "NumberLong(\"123456789012\")";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Int64, _bsonReader.ReadBsonType());
                Assert.AreEqual(123456789012, _bsonReader.ReadInt64());
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <long>(json).ToJson());
        }
Exemplo n.º 29
0
        public void TestInt32()
        {
            var json = "123";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                Assert.AreEqual(123, _bsonReader.ReadInt32());
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <int>(json).ToJson());
        }
Exemplo n.º 30
0
        public void TestDocumentNested()
        {
            var json = "{ \"a\" : { \"x\" : 1 }, \"y\" : 2 }";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReadStartDocument();
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                Assert.AreEqual("a", _bsonReader.ReadName());
                _bsonReader.ReadStartDocument();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                Assert.AreEqual("x", _bsonReader.ReadName());
                Assert.AreEqual(1, _bsonReader.ReadInt32());
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReadEndDocument();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                Assert.AreEqual("y", _bsonReader.ReadName());
                Assert.AreEqual(2, _bsonReader.ReadInt32());
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReadEndDocument();
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(json).ToJson());
        }
Exemplo n.º 31
0
        public void TestObjectIdShell()
        {
            var json = "ObjectId(\"4d0ce088e447ad08b4721a37\")";

            using (_bsonReader = BsonReader.Create(json))
            {
                Assert.AreEqual(BsonType.ObjectId, _bsonReader.ReadBsonType());
                var objectId = _bsonReader.ReadObjectId();
                Assert.AreEqual("4d0ce088e447ad08b4721a37", objectId.ToString());
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <ObjectId>(new StringReader(json)).ToJson());
        }
        // public methods
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options)
        {
            if (nominalType != typeof(object))
            {
                var message = string.Format("ObjectSerializer can only be used with nominal type System.Object, not type {0}.", nominalType.FullName);
                throw new InvalidOperationException(message);
            }

            var bsonType = bsonReader.GetCurrentBsonType();
            if (bsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
                return null;
            }
            else if (bsonType == BsonType.Document)
            {
                var bookmark = bsonReader.GetBookmark();
                bsonReader.ReadStartDocument();
                if (bsonReader.ReadBsonType() == BsonType.EndOfDocument)
                {
                    bsonReader.ReadEndDocument();
                    return new object();
                }
                else
                {
                    bsonReader.ReturnToBookmark(bookmark);
                }
            }

            var discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));
            var actualType = discriminatorConvention.GetActualType(bsonReader, typeof(object));
            if (actualType == typeof(object))
            {
                var message = string.Format("Unable to determine actual type of object to deserialize. NominalType is System.Object and BsonType is {0}.", bsonType);
                throw new FileFormatException(message);
            }

            var serializer = BsonSerializer.LookupSerializer(actualType);
            return serializer.Deserialize(bsonReader, nominalType, actualType, options);
        }
        // public methods
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            VerifyTypes(nominalType, actualType, typeof(BsonDocument));

            var bsonType = bsonReader.GetCurrentBsonType();
            string message;
            switch (bsonType)
            {
                case BsonType.Document:
                    var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions;
                    if (documentSerializationOptions == null)
                    {
                        message = string.Format(
                            "Serialize method of BsonDocument expected serialization options of type {0}, not {1}.",
                            BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)),
                            BsonUtils.GetFriendlyTypeName(options.GetType()));
                        throw new BsonSerializationException(message);
                    }

                    bsonReader.ReadStartDocument();
                    var document = new BsonDocument(documentSerializationOptions.AllowDuplicateNames);
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        var name = bsonReader.ReadName();
                        var value = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null);
                        document.Add(name, value);
                    }
                    bsonReader.ReadEndDocument();

                    return document;
                default:
                    message = string.Format("Cannot deserialize BsonDocument from BsonType {0}.", bsonType);
                    throw new FileFormatException(message);
            }
        }
Exemplo n.º 34
0
        // public methods
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            var arraySerializationOptions = EnsureSerializationOptions<ArraySerializationOptions>(options);
            var itemSerializationOptions = arraySerializationOptions.ItemSerializationOptions;

            var bsonType = bsonReader.GetCurrentBsonType();
            switch (bsonType)
            {
                case BsonType.Null:
                    bsonReader.ReadNull();
                    return null;
                case BsonType.Array:
                    bsonReader.ReadStartArray();
                    var stack = new Stack();
                    var discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        var elementType = discriminatorConvention.GetActualType(bsonReader, typeof(object));
                        var serializer = BsonSerializer.LookupSerializer(elementType);
                        var element = serializer.Deserialize(bsonReader, typeof(object), elementType, itemSerializationOptions);
                        stack.Push(element);
                    }
                    bsonReader.ReadEndArray();
                    return stack;
                case BsonType.Document:
                    bsonReader.ReadStartDocument();
                    bsonReader.ReadString("_t"); // skip over discriminator
                    bsonReader.ReadName("_v");
                    var value = Deserialize(bsonReader, actualType, actualType, options);
                    bsonReader.ReadEndDocument();
                    return value;
                default:
                    var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType);
                    throw new FileFormatException(message);
            }
        }
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public object Deserialize(
           BsonReader bsonReader,
           Type nominalType,
           Type actualType,
           IBsonSerializationOptions options)
        {
            if (actualType != typeof(object))
            {
                var message = string.Format("ObjectSerializer can only be used with actual type System.Object, not type {0}.", actualType.FullName);
                throw new ArgumentException(message, "actualType");
            }

            var bsonType = bsonReader.GetCurrentBsonType();
            if (bsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
                return null;
            }
            else if (bsonType == BsonType.Document)
            {
                bsonReader.ReadStartDocument();
                if (bsonReader.ReadBsonType() == BsonType.EndOfDocument)
                {
                    bsonReader.ReadEndDocument();
                    return new object();
                }
                else
                {
                    var message = string.Format("A document being deserialized to System.Object must be empty.");
                    throw new FileFormatException(message);
                }
            }
            else
            {
                var message = string.Format("Cannot deserialize System.Object from BsonType {0}.", bsonType);
                throw new FileFormatException(message);
            }
        }
Exemplo n.º 36
0
        // public methods
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            var dictionarySerializationOptions = EnsureSerializationOptions(options);
            var dictionaryRepresentation = dictionarySerializationOptions.Representation;
            var keyValuePairSerializationOptions = dictionarySerializationOptions.KeyValuePairSerializationOptions;

            var bsonType = bsonReader.GetCurrentBsonType();
            if (bsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
                return null;
            }
            else if (bsonType == BsonType.Document)
            {
                if (nominalType == typeof(object))
                {
                    bsonReader.ReadStartDocument();
                    bsonReader.ReadString("_t"); // skip over discriminator
                    bsonReader.ReadName("_v");
                    var value = Deserialize(bsonReader, actualType, options); // recursive call replacing nominalType with actualType
                    bsonReader.ReadEndDocument();
                    return value;
                }

                var dictionary = CreateInstance(actualType);
                var valueDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object));

                bsonReader.ReadStartDocument();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    var key = bsonReader.ReadName();
                    var valueType = valueDiscriminatorConvention.GetActualType(bsonReader, typeof(object));
                    var valueSerializer = BsonSerializer.LookupSerializer(valueType);
                    var value = valueSerializer.Deserialize(bsonReader, typeof(object), valueType, keyValuePairSerializationOptions.ValueSerializationOptions);
                    dictionary.Add(key, value);
                }
                bsonReader.ReadEndDocument();

                return dictionary;
            }
            else if (bsonType == BsonType.Array)
            {
                var dictionary = CreateInstance(actualType);

                bsonReader.ReadStartArray();
                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    var keyValuePair = (KeyValuePair<object, object>)_keyValuePairSerializer.Deserialize(
                        bsonReader,
                        typeof(KeyValuePair<object, object>),
                        keyValuePairSerializationOptions);
                    dictionary.Add(keyValuePair.Key, keyValuePair.Value);
                }
                bsonReader.ReadEndArray();

                return dictionary;
            }
            else
            {
                var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType);
                throw new FileFormatException(message);
            }
        }
        // private methods
        private bool IsCSharpNullRepresentation(BsonReader bsonReader)
        {
            var bookmark = bsonReader.GetBookmark();
            bsonReader.ReadStartDocument();
            var bsonType = bsonReader.ReadBsonType();
            if (bsonType == BsonType.Boolean)
            {
                var name = bsonReader.ReadName();
                if (name == "_csharpnull" || name == "$csharpnull")
                {
                    var value = bsonReader.ReadBoolean();
                    if (value)
                    {
                        bsonType = bsonReader.ReadBsonType();
                        if (bsonType == BsonType.EndOfDocument)
                        {
                            bsonReader.ReadEndDocument();
                            return true;
                        }
                    }
                }
            }

            bsonReader.ReturnToBookmark(bookmark);
            return false;
        }
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            VerifyNominalType(nominalType);
            var bsonType = bsonReader.GetCurrentBsonType();
            if (bsonType == Bson.BsonType.Null)
            {
                bsonReader.ReadNull();
                return null;
            }
            else
            {
                if (actualType != _classMap.ClassType)
                {
                    var message = string.Format("BsonClassMapSerializer.Deserialize for type {0} was called with actualType {1}.",
                        BsonUtils.GetFriendlyTypeName(_classMap.ClassType), BsonUtils.GetFriendlyTypeName(actualType));
                    throw new BsonSerializationException(message);
                }

                if (actualType.IsValueType)
                {
                    var message = string.Format("Value class {0} cannot be deserialized.", actualType.FullName);
                    throw new BsonSerializationException(message);
                }

                if (_classMap.IsAnonymous)
                {
                    throw new InvalidOperationException("An anonymous class cannot be deserialized.");
                }

                if (bsonType != BsonType.Document)
                {
                    var message = string.Format(
                        "Expected a nested document representing the serialized form of a {0} value, but found a value of type {1} instead.",
                        actualType.FullName, bsonType);
                    throw new FileFormatException(message);
                }

                Dictionary<string, object> values = null;
                object obj = null;
                ISupportInitialize supportsInitialization = null;
                if (_classMap.HasCreatorMaps)
                {
                    // for creator-based deserialization we first gather the values in a dictionary and then call a matching creator
                    values = new Dictionary<string, object>();
                }
                else
                {
                    // for mutable classes we deserialize the values directly into the result object
                    obj = _classMap.CreateInstance();

                    supportsInitialization = obj as ISupportInitialize;
                    if (supportsInitialization != null)
                    {
                        supportsInitialization.BeginInit();
                    }
                }

                var discriminatorConvention = _classMap.GetDiscriminatorConvention();
                var allMemberMaps = _classMap.AllMemberMaps;
                var extraElementsMemberMapIndex = _classMap.ExtraElementsMemberMapIndex;
                var memberMapBitArray = FastMemberMapHelper.GetBitArray(allMemberMaps.Count);

                bsonReader.ReadStartDocument();
                var elementTrie = _classMap.ElementTrie;
                bool memberMapFound;
                int memberMapIndex;
                while (bsonReader.ReadBsonType(elementTrie, out memberMapFound, out memberMapIndex) != BsonType.EndOfDocument)
                {
                    var elementName = bsonReader.ReadName();
                    if (memberMapFound)
                    {
                        var memberMap = allMemberMaps[memberMapIndex];
                        if (memberMapIndex != extraElementsMemberMapIndex)
                        {
                            if (obj != null)
                            {
                                if (memberMap.IsReadOnly)
                                {
                                    bsonReader.SkipValue();
                                }
                                else
                                {
                                    var value = DeserializeMemberValue(bsonReader, memberMap);
                                    memberMap.Setter(obj, value);
                                }
                            }
                            else
                            {
                                var value = DeserializeMemberValue(bsonReader, memberMap);
                                values[elementName] = value;
                            }
                        }
                        else
                        {
                            DeserializeExtraElement(bsonReader, obj, elementName, memberMap);
                        }
                        memberMapBitArray[memberMapIndex >> 5] |= 1U << (memberMapIndex & 31);
                    }
                    else
                    {
                        if (elementName == discriminatorConvention.ElementName)
                        {
                            bsonReader.SkipValue(); // skip over discriminator
                            continue;
                        }

                        if (extraElementsMemberMapIndex >= 0)
                        {
                            DeserializeExtraElement(bsonReader, obj, elementName, _classMap.ExtraElementsMemberMap);
                            memberMapBitArray[extraElementsMemberMapIndex >> 5] |= 1U << (extraElementsMemberMapIndex & 31);
                        }
                        else if (_classMap.IgnoreExtraElements)
                        {
                            bsonReader.SkipValue();
                        }
                        else
                        {
                            //james.wei 针对/_id属性没有扩展映射的提示。
                            var message = string.Format("Element '{0}' does not match any field or property of class {1}.",elementName, _classMap.ClassType.FullName);
                            throw new FileFormatException(message);
                        }
                    }
                }
                bsonReader.ReadEndDocument();

                // check any members left over that we didn't have elements for (in blocks of 32 elements at a time)
                for (var bitArrayIndex = 0; bitArrayIndex < memberMapBitArray.Length; ++bitArrayIndex)
                {
                    memberMapIndex = bitArrayIndex << 5;
                    var memberMapBlock = ~memberMapBitArray[bitArrayIndex]; // notice that bits are flipped so 1's are now the missing elements

                    // work through this memberMapBlock of 32 elements
                    while (true)
                    {
                        // examine missing elements (memberMapBlock is shifted right as we work through the block)
                        for (; (memberMapBlock & 1) != 0; ++memberMapIndex, memberMapBlock >>= 1)
                        {
                            var memberMap = allMemberMaps[memberMapIndex];
                            if (memberMap.IsReadOnly)
                            {
                                continue;
                            }

                            if (memberMap.IsRequired)
                            {
                                var fieldOrProperty = (memberMap.MemberInfo.MemberType == MemberTypes.Field) ? "field" : "property";
                                var message = string.Format(
                                    "Required element '{0}' for {1} '{2}' of class {3} is missing.",
                                    memberMap.ElementName, fieldOrProperty, memberMap.MemberName, _classMap.ClassType.FullName);
                                throw new FileFormatException(message);
                            }

                            if (obj != null)
                            {
                                memberMap.ApplyDefaultValue(obj);
                            }
                            else if (memberMap.IsDefaultValueSpecified && !memberMap.IsReadOnly)
                            {
                                values[memberMap.ElementName] = memberMap.DefaultValue;
                            }
                        }

                        if (memberMapBlock == 0)
                        {
                            break;
                        }

                        // skip ahead to the next missing element
                        var leastSignificantBit = FastMemberMapHelper.GetLeastSignificantBit(memberMapBlock);
                        memberMapIndex += leastSignificantBit;
                        memberMapBlock >>= leastSignificantBit;
                    }
                }

                if (obj != null)
                {
                    if (supportsInitialization != null)
                    {
                        supportsInitialization.EndInit();
                    }

                    return obj;
                }
                else
                {
                    return CreateInstanceUsingCreator(values);
                }

            }
        }
Exemplo n.º 39
0
        // public methods
        /// <summary>
        /// Deserializes an object from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The BsonReader.</param>
        /// <param name="nominalType">The nominal type of the object.</param>
        /// <param name="actualType">The actual type of the object.</param>
        /// <param name="options">The serialization options.</param>
        /// <returns>An object.</returns>
        public override object Deserialize(
            BsonReader bsonReader,
            Type nominalType,
            Type actualType,
            IBsonSerializationOptions options)
        {
            VerifyTypes(nominalType, actualType, typeof(Version));

            BsonType bsonType = bsonReader.GetCurrentBsonType();
            string message;
            switch (bsonType)
            {
                case BsonType.Null:
                    bsonReader.ReadNull();
                    return null;
                case BsonType.Document:
                    bsonReader.ReadStartDocument();
                    int major = -1, minor = -1, build = -1, revision = -1;
                    while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                    {
                        var name = bsonReader.ReadName();
                        switch (name)
                        {
                            case "Major": major = bsonReader.ReadInt32(); break;
                            case "Minor": minor = bsonReader.ReadInt32(); break;
                            case "Build": build = bsonReader.ReadInt32(); break;
                            case "Revision": revision = bsonReader.ReadInt32(); break;
                            default:
                                message = string.Format("Unrecognized element '{0}' while deserializing a Version value.", name);
                                throw new FileFormatException(message);
                        }
                    }
                    bsonReader.ReadEndDocument();
                    if (major == -1)
                    {
                        message = string.Format("Version missing Major element.");
                        throw new FileFormatException(message);
                    }
                    else if (minor == -1)
                    {
                        message = string.Format("Version missing Minor element.");
                        throw new FileFormatException(message);
                    }
                    else if (build == -1)
                    {
                        return new Version(major, minor);
                    }
                    else if (revision == -1)
                    {
                        return new Version(major, minor, build);
                    }
                    else
                    {
                        return new Version(major, minor, build, revision);
                    }
                case BsonType.String:
                    return new Version(bsonReader.ReadString());
                default:
                    message = string.Format("Cannot deserialize Version from BsonType {0}.", bsonType);
                    throw new FileFormatException(message);
            }
        }