// public methods
        /// <summary>
        /// Gets the actual type of an object by reading the discriminator from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The reader.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <returns>The actual type.</returns>
        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            // the BsonReader is sitting at the value whose actual type needs to be found
            var bsonType = bsonReader.GetCurrentBsonType();
            if (bsonType == BsonType.Document)
            {
                // ensure KnownTypes of nominalType are registered (so IsTypeDiscriminated returns correct answer)
                BsonSerializer.EnsureKnownTypesAreRegistered(nominalType);

                // we can skip looking for a discriminator if nominalType has no discriminated sub types
                if (BsonSerializer.IsTypeDiscriminated(nominalType))
                {
                    var bookmark = bsonReader.GetBookmark();
                    bsonReader.ReadStartDocument();
                    var actualType = nominalType;
                    if (bsonReader.FindElement(_elementName))
                    {
                        var context = BsonDeserializationContext.CreateRoot(bsonReader);
                        var discriminator = BsonValueSerializer.Instance.Deserialize(context);
                        if (discriminator.IsBsonArray)
                        {
                            discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator
                        }
                        actualType = BsonSerializer.LookupActualType(nominalType, discriminator);
                    }
                    bsonReader.ReturnToBookmark(bookmark);
                    return actualType;
                }
            }

            return nominalType;
        }
Ejemplo n.º 2
0
        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            if (nominalType == typeof(JobTask))
            {
                var ret = nominalType;

                var bookmark = bsonReader.GetBookmark();
                bsonReader.ReadStartDocument();
                if (bsonReader.FindElement(ElementName))
                {
                    var value = bsonReader.ReadString();

                    ret = Type.GetType(value);

                    if (ret == null)
                        throw new Exception("Could not find type " + value);

                    if (!ret.IsSubclassOf(typeof(JobTask)))
                        throw new Exception("Database type does not inherit from JobTask.");
                }

                bsonReader.ReturnToBookmark(bookmark);

                return ret;
            }
            else
            {
                return nominalType;
            }
        }
        // public methods
        /// <summary>
        /// Gets the actual type of an object by reading the discriminator from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The reader.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <returns>The actual type.</returns>
        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            // the BsonReader is sitting at the value whose actual type needs to be found
            var bsonType = bsonReader.GetCurrentBsonType();
            if (bsonReader.State == BsonReaderState.Value)
            {
                Type primitiveType = null;
                switch (bsonType)
                {
                    case BsonType.Boolean: primitiveType = typeof(bool); break;
                    case BsonType.Binary:
                        var bookmark = bsonReader.GetBookmark();
                        var binaryData = bsonReader.ReadBinaryData();
                        var subType = binaryData.SubType;
                        if (subType == BsonBinarySubType.UuidStandard || subType == BsonBinarySubType.UuidLegacy)
                        {
                            primitiveType = typeof(Guid);
                        }
                        bsonReader.ReturnToBookmark(bookmark);
                        break;
                    case BsonType.DateTime: primitiveType = typeof(DateTime); break;
                    case BsonType.Decimal128: primitiveType = typeof(Decimal128); break;
                    case BsonType.Double: primitiveType = typeof(double); break;
                    case BsonType.Int32: primitiveType = typeof(int); break;
                    case BsonType.Int64: primitiveType = typeof(long); break;
                    case BsonType.ObjectId: primitiveType = typeof(ObjectId); break;
                    case BsonType.String: primitiveType = typeof(string); break;
                }

                // Type.IsAssignableFrom is extremely expensive, always perform a direct type check before calling Type.IsAssignableFrom
                if (primitiveType != null && (primitiveType == nominalType || nominalType.GetTypeInfo().IsAssignableFrom(primitiveType)))
                {
                    return primitiveType;
                }
            }

            if (bsonType == BsonType.Document)
            {
                var bookmark = bsonReader.GetBookmark();
                bsonReader.ReadStartDocument();
                var actualType = nominalType;
                if (bsonReader.FindElement(_elementName))
                {
                    var context = BsonDeserializationContext.CreateRoot(bsonReader);
                    var discriminator = BsonValueSerializer.Instance.Deserialize(context);
                    if (discriminator.IsBsonArray)
                    {
                        discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator
                    }
                    actualType = BsonSerializer.LookupActualType(nominalType, discriminator);
                }
                bsonReader.ReturnToBookmark(bookmark);
                return actualType;
            }

            return nominalType;
        }
 // constructors
 private BsonDeserializationContext(
     IBsonReader reader,
     bool allowDuplicateElementNames,
     IBsonSerializer dynamicArraySerializer,
     IBsonSerializer dynamicDocumentSerializer)
 {
     _reader = reader;
     _allowDuplicateElementNames = allowDuplicateElementNames;
     _dynamicArraySerializer = dynamicArraySerializer;
     _dynamicDocumentSerializer = dynamicDocumentSerializer;
 }
 public void TestArrayEmpty()
 {
     var json = "[]";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Array, _bsonReader.ReadBsonType());
         _bsonReader.ReadStartArray();
         Assert.Equal(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
         _bsonReader.ReadEndArray();
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonArray>(json).ToJson());
 }
        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            var bookmark = bsonReader.GetBookmark();
            bsonReader.ReadStartDocument();
            string typeValue = string.Empty;
            if (bsonReader.FindElement(ElementName))
                typeValue = bsonReader.ReadString();
            else
                throw new NotSupportedException();

            bsonReader.ReturnToBookmark(bookmark);
            var retr = Type.GetType(typeValue) ?? Type.GetType("ThreeOneThree.Proxima.Core.Entities." + typeValue);
            return retr;
        }
 public Type GetActualType(IBsonReader bsonReader, Type nominalType)
 {
     var bookmark = bsonReader.GetBookmark();
     bsonReader.ReadStartDocument();
     var actualType = nominalType;
     while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
     {
         var name = bsonReader.ReadName();
         if (name == "OnlyInB")
         {
             actualType = typeof(B);
             break;
         }
         else if (name == "OnlyInC")
         {
             actualType = typeof(C);
             break;
         }
         bsonReader.SkipValue();
     }
     bsonReader.ReturnToBookmark(bookmark);
     return actualType;
 }
 public void TestHexData()
 {
     var expectedBytes = new byte[] { 0x01, 0x23 };
     var json = "HexData(0, \"123\")";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Binary, _bsonReader.ReadBsonType());
         var bytes = _bsonReader.ReadBytes();
         Assert.True(expectedBytes.SequenceEqual(bytes));
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     var expectedJson = "new BinData(0, \"ASM=\")";
     Assert.Equal(expectedJson, BsonSerializer.Deserialize<byte[]>(json).ToJson());
 }
Ejemplo n.º 9
0
 /// <summary>
 /// Deserializes an object from a binary source.
 /// </summary>
 /// <param name="Reader">Binary deserializer.</param>
 /// <param name="DataType">Optional datatype. If not provided, will be read from the binary source.</param>
 /// <param name="Embedded">If the object is embedded into another.</param>
 /// <returns>Deserialized object.</returns>
 public override object Deserialize(IBsonReader Reader, BsonType?DataType, bool Embedded)
 {
     return(this.Deserialize(Reader, DataType, Embedded, true));
 }
 public void TestRegularExpressionShell()
 {
     var json = "/pattern/imxs";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.RegularExpression, _bsonReader.ReadBsonType());
         var regex = _bsonReader.ReadRegularExpression();
         Assert.Equal("pattern", regex.Pattern);
         Assert.Equal("imxs", regex.Options);
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonRegularExpression>(json).ToJson());
 }
 public void TestTimestampConstructor()
 {
     var json = "Timestamp(1, 2)";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Timestamp, _bsonReader.ReadBsonType());
         Assert.Equal(new BsonTimestamp(1, 2).Value, _bsonReader.ReadTimestamp());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonTimestamp>(new StringReader(json)).ToJson());
 }
Ejemplo n.º 12
0
 public MongoReaderAdapter(IBsonReader bsonReader)
 => _bson = Check.NotNull(bsonReader, nameof(bsonReader));
 /// <summary>
 /// Reads a BSON symbol element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>A string.</returns>
 public static string ReadSymbol(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadSymbol());
 }
 /// <summary>
 /// Reads a BSON boolean element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>A Boolean.</returns>
 public static bool ReadBoolean(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadBoolean());
 }
Ejemplo n.º 15
0
        private BsonDocument DeserializeBsonDocument(IBsonReader bsonReader)
        {
            var context = BsonDeserializationContext.CreateRoot(bsonReader);

            return(BsonDocumentSerializer.Instance.Deserialize(context));
        }
 /// <summary>
 /// Reads a BSON binary data element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>A BsonBinaryData.</returns>
 public static BsonBinaryData ReadBinaryData(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadBinaryData());
 }
 /// <summary>
 /// Reads a BSON undefined element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 public static void ReadUndefined(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     reader.ReadUndefined();
 }
 /// <summary>
 /// Reads a BSON timestamp element from the reader.
 /// </summary>
 /// <returns>The combined timestamp/increment.</returns>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 public static long ReadTimestamp(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadTimestamp());
 }
 public void TestInt32Constructor(string json)
 {
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Int32, _bsonReader.ReadBsonType());
         Assert.Equal(123, _bsonReader.ReadInt32());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     var canonicalJson = "123";
     Assert.Equal(canonicalJson, BsonSerializer.Deserialize<int>(new StringReader(json)).ToJson());
 }
Ejemplo n.º 20
0
        /// <summary>
        /// Deserializes an object from a binary source.
        /// </summary>
        /// <param name="Reader">Binary deserializer.</param>
        /// <param name="DataType">Optional datatype. If not provided, will be read from the binary source.</param>
        /// <param name="Embedded">If the object is embedded into another.</param>
        /// <param name="CheckFieldNames">If field names are to be extended.</param>
        /// <returns>Deserialized object.</returns>
        public object Deserialize(IBsonReader Reader, BsonType?DataType, bool Embedded, bool CheckFieldNames)
        {
            BsonReaderBookmark Bookmark    = Reader.GetBookmark();
            BsonType?          DataTypeBak = DataType;

            if (!DataType.HasValue)
            {
                DataType = Reader.ReadBsonType();
            }

            switch (DataType.Value)
            {
            case BsonType.Document:
                break;

            case BsonType.Boolean:
                return(Reader.ReadBoolean());

            case BsonType.Int32:
                return(Reader.ReadInt32());

            case BsonType.Int64:
                return(Reader.ReadInt64());

            case BsonType.Decimal128:
                return((decimal)Reader.ReadDecimal128());

            case BsonType.Double:
                return(Reader.ReadDouble());

            case BsonType.DateTime:
                return(ObjectSerializer.UnixEpoch.AddMilliseconds(Reader.ReadDateTime()));

            case BsonType.String:
            case BsonType.Symbol:
            case BsonType.JavaScript:
            case BsonType.JavaScriptWithScope:
                return(Reader.ReadString());

            case BsonType.Binary:
                return(Reader.ReadBytes());

            case BsonType.Null:
                Reader.ReadNull();
                return(null);

            default:
                throw new Exception("Object or value expected.");
            }

            LinkedList <KeyValuePair <string, object> > Properties = new LinkedList <KeyValuePair <string, object> >();
            LinkedList <KeyValuePair <string, object> > LowerCase  = null;
            string   TypeName       = string.Empty;
            Guid     ObjectId       = Guid.Empty;
            string   CollectionName = string.Empty;
            string   FieldName;
            BsonType ValueType;
            object   Value;

            Reader.ReadStartDocument();

            while (Reader.State == BsonReaderState.Type)
            {
                ValueType = Reader.ReadBsonType();
                if (ValueType == BsonType.EndOfDocument)
                {
                    break;
                }

                FieldName = Reader.ReadName();

                switch (ValueType)
                {
                case BsonType.Array:
                    Value = GeneratedObjectSerializerBase.ReadArray(null, this.Provider, Reader, ValueType);
                    break;

                case BsonType.Binary:
                    Value = Reader.ReadBytes();
                    break;

                case BsonType.Boolean:
                    Value = Reader.ReadBoolean();
                    break;

                case BsonType.DateTime:
                    Value = ObjectSerializer.UnixEpoch.AddMilliseconds(Reader.ReadDateTime());
                    break;

                case BsonType.Decimal128:
                    Value = (decimal)Reader.ReadDecimal128();
                    break;

                case BsonType.Document:
                    Value = this.Deserialize(Reader, ValueType, true);
                    break;

                case BsonType.Double:
                    Value = Reader.ReadDouble();
                    break;

                case BsonType.Int32:
                    Value = Reader.ReadInt32();
                    break;

                case BsonType.Int64:
                    Value = Reader.ReadInt64();
                    break;

                case BsonType.JavaScript:
                    Value = Reader.ReadJavaScript();
                    break;

                case BsonType.JavaScriptWithScope:
                    Value = Reader.ReadJavaScriptWithScope();
                    break;

                case BsonType.Null:
                    Value = null;
                    Reader.ReadNull();
                    break;

                case BsonType.ObjectId:
                    Value = Reader.ReadObjectId();
                    break;

                case BsonType.String:
                    Value = Reader.ReadString();
                    break;

                case BsonType.Symbol:
                    Value = Reader.ReadSymbol();
                    break;

                default:
                    throw new Exception("Unrecognized data type: " + ValueType.ToString());
                }

                switch (FieldName)
                {
                case "_id":
                    if (Value is Guid Guid)
                    {
                        ObjectId = Guid;
                    }
                    else if (Value is string s)
                    {
                        ObjectId = new Guid(s);
                    }
                    else if (Value is byte[] A)
                    {
                        ObjectId = new Guid(A);
                    }
                    else if (Value is ObjectId ObjId)
                    {
                        ObjectId = GeneratedObjectSerializerBase.ObjectIdToGuid(ObjId);
                    }
                    else
                    {
                        throw new Exception("Unrecognized Object ID type: " + Value.GetType().FullName);
                    }
                    break;

                case "_type":
                    TypeName = Value?.ToString();

                    if (this.returnTypedObjects && !string.IsNullOrEmpty(TypeName))
                    {
                        Type DesiredType = Types.GetType(TypeName);
                        if (DesiredType is null)
                        {
                            DesiredType = typeof(GenericObject);
                        }

                        if (DesiredType != typeof(GenericObject))
                        {
                            IObjectSerializer Serializer2 = this.provider.GetObjectSerializer(DesiredType);
                            Reader.ReturnToBookmark(Bookmark);
                            return(Serializer2.Deserialize(Reader, DataTypeBak, Embedded));
                        }
                    }
                    break;

                case "_collection":
                    CollectionName = Value?.ToString();
                    break;

                default:
                    if (FieldName.EndsWith("_L"))
                    {
                        string s      = FieldName.Substring(0, FieldName.Length - 2);
                        bool   Ignore = false;

                        foreach (KeyValuePair <string, object> P in Properties)
                        {
                            if (P.Key == s)
                            {
                                Ignore = true;
                                break;
                            }
                        }

                        if (!Ignore)
                        {
                            if (LowerCase is null)
                            {
                                LowerCase = new LinkedList <KeyValuePair <string, object> >();
                            }

                            LowerCase.AddLast(new KeyValuePair <string, object>(s, Value));
                        }
                    }
                    else
                    {
                        Properties.AddLast(new KeyValuePair <string, object>(FieldName, Value));
                    }
                    break;
                }
            }

            if (!(LowerCase is null))
            {
                foreach (KeyValuePair <string, object> P in LowerCase)
                {
                    bool Ignore = false;

                    foreach (KeyValuePair <string, object> P2 in Properties)
                    {
                        if (P2.Key == P.Key)
                        {
                            Ignore = true;
                            break;
                        }
                    }

                    if (!Ignore)
                    {
                        Properties.AddLast(new KeyValuePair <string, object>(P.Key + "_L", P.Value));
                    }
                }
            }

            Reader.ReadEndDocument();

            return(new GenericObject(CollectionName, TypeName, ObjectId, Properties));
        }
 public void TestInt64ExtendedJson()
 {
     var json = "{ \"$numberLong\" : \"123\" }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Int64, _bsonReader.ReadBsonType());
         Assert.Equal(123, _bsonReader.ReadInt64());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     var canonicalJson = "NumberLong(123)";
     Assert.Equal(canonicalJson, BsonSerializer.Deserialize<long>(new StringReader(json)).ToJson());
 }
Ejemplo n.º 22
0
        /***************************************************/

        private object DeserializeDiscriminatedValue(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            // First try to recover the object type
            IBsonReader        reader   = context.Reader;
            BsonReaderBookmark bookmark = reader.GetBookmark();
            Type actualType             = typeof(CustomObject);

            try
            {
                actualType = _discriminatorConvention.GetActualType(reader, typeof(object));
            }
            catch
            {
                // This is were we can call the Version_Engine to return the new type string from the old one if exists
                string recordedType = GetCurrentTypeValue(reader);

                // If failed, return Custom object
                context.Reader.ReturnToBookmark(bookmark);
                Engine.Reflection.Compute.RecordWarning("The type " + recordedType + " is unknown -> data returned as custom objects.");
                IBsonSerializer customSerializer = BsonSerializer.LookupSerializer(typeof(CustomObject));
                return(customSerializer.Deserialize(context, args));
            }

            // Handle the special case where the type is object
            if (actualType == typeof(object))
            {
                BsonType currentBsonType = reader.GetCurrentBsonType();
                if (currentBsonType == BsonType.Document && context.DynamicDocumentSerializer != null)
                {
                    return(context.DynamicDocumentSerializer.Deserialize(context, args));
                }
                reader.ReadStartDocument();
                reader.ReadEndDocument();
                return(new object());
            }

            // Handle the genral case of finding the correct deserialiser and calling it
            IBsonSerializer            bsonSerializer            = BsonSerializer.LookupSerializer(actualType);
            IBsonPolymorphicSerializer bsonPolymorphicSerializer = bsonSerializer as IBsonPolymorphicSerializer;

            if (bsonPolymorphicSerializer != null && bsonPolymorphicSerializer.IsDiscriminatorCompatibleWithObjectSerializer)
            {
                bookmark = context.Reader.GetBookmark();
                try
                {
                    return(bsonSerializer.Deserialize(context, args));
                }
                catch
                {
                    context.Reader.ReturnToBookmark(bookmark);
                    Engine.Reflection.Compute.RecordWarning("Cannot find a definition of type " + actualType.FullName + " that matches the object to deserialise -> data returned as custom objects.");
                    IBsonSerializer customSerializer = BsonSerializer.LookupSerializer(typeof(CustomObject));
                    CustomObject    fallback         = customSerializer.Deserialize(context, args) as CustomObject;

                    //This is where we will try to get the correct object type from the custom object using the versionning engine

                    // If failed, just return the custom object
                    return(fallback);
                }
            }

            object result = null;
            bool   flag   = false;

            reader.ReadStartDocument();
            while (reader.ReadBsonType() != 0)
            {
                string text = reader.ReadName();
                if (text == _discriminatorConvention.ElementName)
                {
                    reader.SkipValue();
                }
                else
                {
                    if (!(text == "_v"))
                    {
                        throw new FormatException($"Unexpected element name: '{text}'.");
                    }
                    result = bsonSerializer.Deserialize(context);
                    flag   = true;
                }
            }
            reader.ReadEndDocument();
            if (!flag)
            {
                throw new FormatException("_v element missing.");
            }
            return(result);
        }
 public void TestObjectIdShell()
 {
     var json = "ObjectId(\"4d0ce088e447ad08b4721a37\")";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.ObjectId, _bsonReader.ReadBsonType());
         var objectId = _bsonReader.ReadObjectId();
         Assert.Equal("4d0ce088e447ad08b4721a37", objectId.ToString());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<ObjectId>(json).ToJson());
 }
Ejemplo n.º 24
0
        public BsonJsonReader(IBsonReader bsonReader)
        {
            Guard.NotNull(bsonReader, nameof(bsonReader));

            this.bsonReader = bsonReader;
        }
 public void TestStringEmpty()
 {
     var json = "\"\"";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.String, _bsonReader.ReadBsonType());
         Assert.Equal("", _bsonReader.ReadString());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<string>(json).ToJson());
 }
Ejemplo n.º 26
0
        public void TestBookmark()
        {
            var json = "{ \"x\" : 1, \"y\" : 2 }";

            using (_bsonReader = new JsonReader(json))
            {
                // do everything twice returning to bookmark in between
                var bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                _bsonReader.ReadStartDocument();
                _bsonReader.ReturnToBookmark(bookmark);
                _bsonReader.ReadStartDocument();

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual("x", _bsonReader.ReadName());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual("x", _bsonReader.ReadName());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(1, _bsonReader.ReadInt32());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(1, _bsonReader.ReadInt32());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual("y", _bsonReader.ReadName());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual("y", _bsonReader.ReadName());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(2, _bsonReader.ReadInt32());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(2, _bsonReader.ReadInt32());

                bookmark = _bsonReader.GetBookmark();
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());

                bookmark = _bsonReader.GetBookmark();
                _bsonReader.ReadEndDocument();
                _bsonReader.ReturnToBookmark(bookmark);
                _bsonReader.ReadEndDocument();

                Assert.AreEqual(BsonReaderState.Initial, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(json).ToJson());
        }
 private static void VerifyName(IBsonReader reader, string expectedName)
 {
     var actualName = reader.ReadName();
     if (actualName != expectedName)
     {
         var message = string.Format(
             "Expected element name to be '{0}', not '{1}'.",
             expectedName, actualName);
         throw new FormatException(message);
     }
 }
Ejemplo n.º 28
0
        /***************************************************/

        private object DeserializeDiscriminatedValue(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            // First try to recover the object type
            IBsonReader        reader   = context.Reader;
            BsonReaderBookmark bookmark = reader.GetBookmark();
            Type actualType             = typeof(CustomObject);

            try
            {
                actualType = _discriminatorConvention.GetActualType(reader, typeof(object));
            }
            catch
            {
                try
                {
                    context.Reader.ReturnToBookmark(bookmark);
                    DeprecatedSerializer deprecatedSerialiser = new DeprecatedSerializer();
                    return(deprecatedSerialiser.Deserialize(context, args));
                }
                catch { }
            }
            context.Reader.ReturnToBookmark(bookmark);

            if (actualType == null)
            {
                return(null);
            }

            // Handle the special case where the type is object
            if (actualType == typeof(object))
            {
                BsonType currentBsonType = reader.GetCurrentBsonType();
                if (currentBsonType == BsonType.Document && context.DynamicDocumentSerializer != null)
                {
                    return(context.DynamicDocumentSerializer.Deserialize(context, args));
                }
                reader.ReadStartDocument();
                reader.ReadEndDocument();
                return(new object());
            }

            // Handle the general case of finding the correct deserialiser and calling it
            try
            {
                if (!BsonClassMap.IsClassMapRegistered(actualType))
                {
                    Compute.RegisterClassMap(actualType); // LookupSerializer creates the classMap if it doesn't exist so important to do it through our own method
                }
                IBsonSerializer bsonSerializer = BsonSerializer.LookupSerializer(actualType);

                if (bsonSerializer.GetType().Name == "EnumerableInterfaceImplementerSerializer`2" && context.Reader.CurrentBsonType == BsonType.Document)
                {
                    if (!m_FallbackSerialisers.ContainsKey(actualType))
                    {
                        CreateFallbackSerialiser(actualType);
                    }
                    bsonSerializer = m_FallbackSerialisers[actualType];
                }
                else if (actualType.Name == "Dictionary`2" && context.Reader.CurrentBsonType == BsonType.Document)
                {
                    DictionarySerializer dicSerialiser = new DictionarySerializer();
                    return(dicSerialiser.Deserialize(context, args));
                }

                return(bsonSerializer.Deserialize(context, args));
            }
            catch (Exception e)
            {
                if (e.Message.Contains("Could not load file or assembly"))
                {
                    Engine.Reflection.Compute.RecordError(e.Message);
                }

                context.Reader.ReturnToBookmark(bookmark);
                DeprecatedSerializer deprecatedSerialiser = new DeprecatedSerializer();
                return(deprecatedSerialiser.Deserialize(context, args));
            }
        }
 private RawBsonDocument DeserializeRawBsonDocument(IBsonReader bsonReader)
 {
     var slice = bsonReader.ReadRawBsonDocument();
     var nestedDocument = new RawBsonDocument(slice);
     _disposableItems.Add(nestedDocument);
     return nestedDocument;
 }
 protected abstract T DeserializeCore(IBsonReader reader);
 /// <summary>
 /// Reads a raw BSON array.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name.</param>
 /// <returns>
 /// The raw BSON array.
 /// </returns>
 public static IByteBuffer ReadRawBsonArray(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadRawBsonArray());
 }
        /// <inheritdoc />
        public Type GetActualType(
            IBsonReader bsonReader,
            Type nominalType)
        {
            if (bsonReader == null)
            {
                throw new ArgumentNullException(nameof(bsonReader));
            }

            if (nominalType == null)
            {
                throw new ArgumentNullException(nameof(nominalType));
            }

            var bookmark = bsonReader.GetBookmark();

            bsonReader.ReadStartDocument();

            Type result;

            if (bsonReader.FindElement(this.ElementName))
            {
                var value = bsonReader.ReadString();

                try
                {
                    result = value.ResolveFromLoadedTypes();

                    if (result == null)
                    {
                        throw new InvalidOperationException(Invariant($"'{nameof(result)}' is null"));
                    }
                }
                catch (ArgumentException)
                {
                    bsonReader.ReturnToBookmark(bookmark);

                    // previously persisted documents will have used Type.Name
                    // in that case ToTypeRepresentationFromAssemblyQualifiedName will throw.
                    // this is here for backward compatibility.
                    result = HierarchicalDiscriminatorConvention.GetActualType(bsonReader, nominalType);

                    if (result == null)
                    {
                        throw new InvalidOperationException(Invariant($"Found discriminator '{value}' when deserializing into {nameof(nominalType)} '{nominalType.ToStringReadable()}', but could not get the actual type using {nameof(TypeNameDiscriminator)}.{nameof(TypeNameDiscriminator.GetActualType)}(); it returned null."));
                    }
                }
            }
            else
            {
                // if _t is not in the payload then a discriminator wasn't needed
                result = nominalType;
            }

            bsonReader.ReturnToBookmark(bookmark);

            // See notes in ThrowOnUnregisteredTypeIfAppropriate for the need to make this call.
            // Note that this is a sub-par solution.  Ideally this discriminator would know
            // which serializer (and hence which serialization configuration) is being used for deserializing,
            // because it is passed as a parameter to this method.  Because that's not an option in Mongo,
            // we have to use ObcBsonSerializer.SerializationConfigurationInUseForDeserialization, which
            // tracks the thread being used for the deserialize operation and associates the serialization
            // configuration in-use with the thread.
            var serializationConfiguration = ObcBsonSerializer.GetSerializationConfigurationInUseForDeserialization();

            // serializationConfiguration is only ever null if the consumer is NOT using the front-door for serialization
            // (i.e. a serializer), but using the Mongo driver directly to deserialize.  In that case, we do not know
            // which serialization configuration is "in use".
            serializationConfiguration?.ThrowOnUnregisteredTypeIfAppropriate(result, SerializationDirection.Deserialize, null);

            return(result);
        }
Ejemplo n.º 33
0
        public static bool TryDeserializeToAny(
            this IBsonReader reader,
            IEnumerable <Type> nominalTypes,
            [MaybeNull] out object[] values
            )
        {
            values = default;
            var success = false;

            // TODO: Prioritize primitives (including string), value types, then objects.
            var orderedTypes = nominalTypes
                               .OrderBy(t => GetTypePriority(t))
                               .ToArray();

            // Oddly enough BsonSerializer.Deserialize is fine with primitive
            // arrays but not arrays of documents. Go figure.
            if (reader.GetCurrentBsonType() == BsonType.Array)
            {
                var tempList = new List <object>();
                success = true;
                reader.ReadStartArray();

                while (reader.State != BsonReaderState.EndOfArray)
                {
                    object?value = null;

                    foreach (var nominalType in nominalTypes)
                    {
                        try
                        {
                            value = BsonSerializer.Deserialize(
                                reader,
                                nominalType
                                );

                            break;
                        }
                        catch
                        { }
                    }

                    if (value is null)
                    {
                        success = false;
                    }
                    else
                    {
                        tempList.Add(value);
                    }
                }

                reader.ReadEndArray();
                values  = tempList.ToArray();
                success = values.Any();
            }
            else
            {
                values = new object[1];

                foreach (var nominalType in nominalTypes)
                {
                    try
                    {
                        values[0] = BsonSerializer.Deserialize(
                            reader,
                            nominalType
                            );

                        success = true;
                        break;
                    }
                    catch
                    { }
                }
            }

            return(success);
        }
 public void TestJavaScript()
 {
     string json = "{ \"$code\" : \"function f() { return 1; }\" }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.JavaScript, _bsonReader.ReadBsonType());
         Assert.Equal("function f() { return 1; }", _bsonReader.ReadJavaScript());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonJavaScript>(json).ToJson());
 }
 public void TestInt32()
 {
     var json = "123";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Int32, _bsonReader.ReadBsonType());
         Assert.Equal(123, _bsonReader.ReadInt32());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<int>(json).ToJson());
 }
 public void TestMinKeyExtendedJsonWithCapitalK()
 {
     var json = "{ \"$minKey\" : 1 }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.MinKey, _bsonReader.ReadBsonType());
         _bsonReader.ReadMinKey();
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     var canonicalJson = "MinKey";
     Assert.Equal(canonicalJson, BsonSerializer.Deserialize<BsonMinKey>(new StringReader(json)).ToJson());
 }
 public void TestInt64ConstructorUnqutoed()
 {
     var json = "NumberLong(123)";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Int64, _bsonReader.ReadBsonType());
         Assert.Equal(123, _bsonReader.ReadInt64());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<long>(json).ToJson());
 }
 public void TestNestedDocument()
 {
     var json = "{ \"a\" : { \"b\" : 1, \"c\" : 2 } }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Document, _bsonReader.ReadBsonType());
         _bsonReader.ReadStartDocument();
         Assert.Equal(BsonType.Document, _bsonReader.ReadBsonType());
         Assert.Equal("a", _bsonReader.ReadName());
         _bsonReader.ReadStartDocument();
         Assert.Equal("b", _bsonReader.ReadName());
         Assert.Equal(1, _bsonReader.ReadInt32());
         Assert.Equal("c", _bsonReader.ReadName());
         Assert.Equal(2, _bsonReader.ReadInt32());
         _bsonReader.ReadEndDocument();
         _bsonReader.ReadEndDocument();
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonDocument>(json).ToJson());
 }
Ejemplo n.º 39
0
        // public methods
        /// <summary>
        /// Gets the actual type of an object by reading the discriminator from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The reader.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <returns>The actual type.</returns>
        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            // the BsonReader is sitting at the value whose actual type needs to be found
            var bsonType = bsonReader.GetCurrentBsonType();

            if (bsonReader.State == BsonReaderState.Value)
            {
                Type primitiveType = null;
                switch (bsonType)
                {
                case BsonType.Boolean: primitiveType = typeof(bool); break;

                case BsonType.Binary:
                    var bookmark   = bsonReader.GetBookmark();
                    var binaryData = bsonReader.ReadBinaryData();
                    var subType    = binaryData.SubType;
                    if (subType == BsonBinarySubType.UuidStandard || subType == BsonBinarySubType.UuidLegacy)
                    {
                        primitiveType = typeof(Guid);
                    }
                    bsonReader.ReturnToBookmark(bookmark);
                    break;

                case BsonType.DateTime: primitiveType = typeof(DateTime); break;

                case BsonType.Double: primitiveType = typeof(double); break;

                case BsonType.Int32: primitiveType = typeof(int); break;

                case BsonType.Int64: primitiveType = typeof(long); break;

                case BsonType.ObjectId: primitiveType = typeof(ObjectId); break;

                case BsonType.String: primitiveType = typeof(string); break;
                }

                // Type.IsAssignableFrom is extremely expensive, always perform a direct type check before calling Type.IsAssignableFrom

                if (primitiveType != null && (primitiveType == nominalType || nominalType.IsAssignableFrom(primitiveType)))
                {
                    return(primitiveType);
                }
            }

            if (bsonType == BsonType.Document)
            {
                var bookmark = bsonReader.GetBookmark();
                bsonReader.ReadStartDocument();
                var actualType = nominalType;
                if (bsonReader.FindElement(_elementName))
                {
                    var context       = BsonDeserializationContext.CreateRoot(bsonReader);
                    var discriminator = BsonValueSerializer.Instance.Deserialize(context);
                    if (discriminator.IsBsonArray)
                    {
                        discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator
                    }
                    actualType = BsonSerializer.LookupActualType(nominalType, discriminator);
                }
                bsonReader.ReturnToBookmark(bookmark);
                return(actualType);
            }

            return(nominalType);
        }
 /// <summary>
 /// Reads a BSON regular expression element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>A BsonRegularExpression.</returns>
 public static BsonRegularExpression ReadRegularExpression(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadRegularExpression());
 }
 public void TestJavaScriptWithScope()
 {
     string json = "{ \"$code\" : \"function f() { return n; }\", \"$scope\" : { \"n\" : 1 } }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.JavaScriptWithScope, _bsonReader.ReadBsonType());
         Assert.Equal("function f() { return n; }", _bsonReader.ReadJavaScriptWithScope());
         _bsonReader.ReadStartDocument();
         Assert.Equal(BsonType.Int32, _bsonReader.ReadBsonType());
         Assert.Equal("n", _bsonReader.ReadName());
         Assert.Equal(1, _bsonReader.ReadInt32());
         _bsonReader.ReadEndDocument();
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonJavaScriptWithScope>(json).ToJson());
 }
Ejemplo n.º 42
0
 public object DeserializeValue(IBsonReader reader)
 {
     return(_strategy.ExecuteDeserialization(reader));
 }
 public void TestMinKeyKeyword()
 {
     var json = "MinKey";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.MinKey, _bsonReader.ReadBsonType());
         _bsonReader.ReadMinKey();
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonMinKey>(new StringReader(json)).ToJson());
 }
 /// <summary>
 /// Reads a BSON binary data element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>A byte array.</returns>
 public static byte[] ReadBytes(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadBytes());
 }
 public void TestNull()
 {
     var json = "null";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Null, _bsonReader.ReadBsonType());
         _bsonReader.ReadNull();
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonNull>(json).ToJson());
 }
 /// <summary>
 /// Reads a BSON Decimal128 element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>A <see cref="Decimal128"/>.</returns>
 public static Decimal128 ReadDecimal128(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadDecimal128());
 }
 public void TestObjectIdStrict()
 {
     var json = "{ \"$oid\" : \"4d0ce088e447ad08b4721a37\" }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.ObjectId, _bsonReader.ReadBsonType());
         var objectId = _bsonReader.ReadObjectId();
         Assert.Equal("4d0ce088e447ad08b4721a37", objectId.ToString());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     var jsonSettings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
     Assert.Equal(json, BsonSerializer.Deserialize<ObjectId>(json).ToJson(jsonSettings));
 }
 /// <summary>
 /// Reads a BSON Double element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>A Double.</returns>
 public static double ReadDouble(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadDouble());
 }
 public void TestRegularExpressionStrict()
 {
     var json = "{ \"$regex\" : \"pattern\", \"$options\" : \"imxs\" }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.RegularExpression, _bsonReader.ReadBsonType());
         var regex = _bsonReader.ReadRegularExpression();
         Assert.Equal("pattern", regex.Pattern);
         Assert.Equal("imxs", regex.Options);
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     var settings = new JsonWriterSettings { OutputMode = JsonOutputMode.Strict };
     Assert.Equal(json, BsonSerializer.Deserialize<BsonRegularExpression>(json).ToJson(settings));
 }
 /// <summary>
 /// Reads a BSON Int32 element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>An Int32.</returns>
 public static int ReadInt32(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadInt32());
 }
 public void TestSymbol()
 {
     var json = "{ \"$symbol\" : \"symbol\" }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Symbol, _bsonReader.ReadBsonType());
         Assert.Equal("symbol", _bsonReader.ReadSymbol());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonSymbol>(json).ToJson());
 }
 /// <summary>
 /// Reads a BSON Int64 element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>An Int64.</returns>
 public static long ReadInt64(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadInt64());
 }
 public void TestTimestampExtendedJsonNewRepresentation()
 {
     var json = "{ \"$timestamp\" : { \"t\" : 1, \"i\" : 2 } }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Timestamp, _bsonReader.ReadBsonType());
         Assert.Equal(new BsonTimestamp(1, 2).Value, _bsonReader.ReadTimestamp());
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     var canonicalJson = "Timestamp(1, 2)";
     Assert.Equal(canonicalJson, BsonSerializer.Deserialize<BsonTimestamp>(new StringReader(json)).ToJson());
 }
 /// <summary>
 /// Reads a BSON JavaScript with scope element from the reader (call ReadStartDocument next to read the scope).
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>A string.</returns>
 public static string ReadJavaScriptWithScope(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadJavaScriptWithScope());
 }
 // constructors
 public JsonReaderAdapter(IBsonReader wrappedReader)
 {
     _wrappedReader = wrappedReader;
 }
 /// <summary>
 /// Reads the name of an element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <returns>The name of the element.</returns>
 public static string ReadName(this IBsonReader reader)
 {
     return(reader.ReadName(Utf8NameDecoder.Instance));
 }
 private RawBsonArray DeserializeRawBsonArray(IBsonReader bsonReader)
 {
     var slice = bsonReader.ReadRawBsonArray();
     var nestedArray = new RawBsonArray(slice);
     _disposableItems.Add(nestedArray);
     return nestedArray;
 }
 /// <summary>
 /// Reads a BSON null element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 public static void ReadNull(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     reader.ReadNull();
 }
 /// <summary>
 /// Reads a BSON ObjectId element from the reader.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="name">The name of the element.</param>
 /// <returns>An ObjectId.</returns>
 public static ObjectId ReadObjectId(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadObjectId());
 }
 /// <summary>
 ///     安全地读入文档字段
 /// </summary>
 /// <param name="bsonReader">Bson读取器</param>
 /// <param name="expected">字段名</param>
 /// <param name="read">字段名缓存</param>
 /// <param name="parser">文档读取器</param>
 /// <returns>读取结果</returns>
 public static T ReadDocument <T>(this IBsonReader bsonReader, string expected, ref string read,
                                  Func <IBsonReader, T> parser) where T : class
 => ReadPrep(bsonReader, expected, ref read) ? parser(bsonReader) : null;