Ejemplo n.º 1
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)
        {
            if (!DataType.HasValue)
            {
                DataType = Reader.ReadBsonType();
            }

            switch (DataType.Value)
            {
            case BsonType.Boolean: return(Reader.ReadBoolean());

            case BsonType.Decimal128: return(Reader.ReadDecimal128() != 0);

            case BsonType.Double: return(Reader.ReadDouble() != 0);

            case BsonType.Int32: return(Reader.ReadInt32() != 0);

            case BsonType.Int64: return(Reader.ReadInt64() != 0);

            case BsonType.MinKey: Reader.ReadMinKey(); return(false);

            case BsonType.MaxKey: Reader.ReadMaxKey(); return(true);

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

            default: throw new Exception("Expected a nullable boolean value.");
            }
        }
        /// <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)
        {
            if (!DataType.HasValue)
            {
                DataType = Reader.ReadBsonType();
            }

            switch (DataType.Value)
            {
            case BsonType.Boolean: return(Reader.ReadBoolean() ? (uint?)1 : (uint?)0);

            case BsonType.Decimal128: return((uint?)Reader.ReadDecimal128());

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

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

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

            case BsonType.String: return((uint?)uint.Parse(Reader.ReadString()));

            case BsonType.MinKey: Reader.ReadMinKey(); return((uint?)uint.MinValue);

            case BsonType.MaxKey: Reader.ReadMaxKey(); return((uint?)uint.MaxValue);

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

            default: throw new Exception("Expected a nullable uint value.");
            }
        }
Ejemplo n.º 3
0
        /***************************************************/

        public override object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            IBsonReader reader          = context.Reader;
            BsonType    currentBsonType = reader.GetCurrentBsonType();

            switch (currentBsonType)
            {
            case BsonType.Array:
                if (context.DynamicArraySerializer != null)
                {
                    return(context.DynamicArraySerializer.Deserialize(context));
                }
                break;

            case BsonType.Binary:
            {
                BsonBinaryData    bsonBinaryData = reader.ReadBinaryData();
                BsonBinarySubType subType        = bsonBinaryData.SubType;
                if (subType == BsonBinarySubType.UuidStandard || subType == BsonBinarySubType.UuidLegacy)
                {
                    return(bsonBinaryData.ToGuid());
                }
                break;
            }

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

            case BsonType.DateTime:
                return(new BsonDateTime(reader.ReadDateTime()).ToUniversalTime());

            case BsonType.Decimal128:
                return(reader.ReadDecimal128());

            case BsonType.Document:
                return(DeserializeDiscriminatedValue(context, args));

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

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

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

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

            case BsonType.ObjectId:
                return(reader.ReadObjectId());

            case BsonType.String:
                return(reader.ReadString());
            }

            Engine.Reflection.Compute.RecordError($"ObjectSerializer does not support BSON type '{currentBsonType}'.");
            return(null);
        }
Ejemplo n.º 4
0
        static object ReadObject(IBsonReader bsonReader)         //_120509_173140 keep consistent
        {
            switch (bsonReader.GetCurrentBsonType())
            {
            case BsonType.Array: return(ReadArray(bsonReader));                                                                                               // replacement

            case BsonType.Binary: var binary = BsonSerializer.Deserialize <BsonValue>(bsonReader); return(BsonTypeMapper.MapToDotNetValue(binary) ?? binary); // byte[] or Guid else self

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

            case BsonType.DateTime: return(BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime()));

            case BsonType.Document: return(ReadCustomObject(bsonReader));                    // replacement

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

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

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

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

            case BsonType.ObjectId: return(bsonReader.ReadObjectId());

            case BsonType.String: return(bsonReader.ReadString());

            default: return(BsonSerializer.Deserialize <BsonValue>(bsonReader));
            }
        }
Ejemplo n.º 5
0
        private JToken GenerateJToken(IBsonReader reader, JToken parent)
        {
            switch (reader.CurrentBsonType)
            {
            case BsonType.Symbol:
            case BsonType.JavaScriptWithScope:
            case BsonType.JavaScript:
            case BsonType.ObjectId:
            case BsonType.RegularExpression:
            case BsonType.DateTime:
            case BsonType.Decimal128:
            case BsonType.MinKey:
            case BsonType.MaxKey:
            case BsonType.String:
                return(reader.ReadString());

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

            case BsonType.Undefined:
                reader.ReadUndefined();
                return(JValue.CreateUndefined());

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

            case BsonType.Null:
                reader.ReadNull();
                return(JValue.CreateNull());

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

            case BsonType.Int64:
            case BsonType.Timestamp:
                return(reader.ReadInt64());

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

            case BsonType.Document:
                return(GenerateJObject(reader, parent));

            case BsonType.Array:
                return(GenerateJArray(reader, parent));

            case BsonType.EndOfDocument:
                break;

            default:
                break;
            }
            return(null);
        }
Ejemplo n.º 6
0
        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 TestInt64ConstructorQuoted()
        {
            var json = "NumberLong(\"123456789012\")";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Int64, _bsonReader.ReadBsonType());
                Assert.AreEqual(123456789012, _bsonReader.ReadInt64());
                Assert.AreEqual(BsonReaderState.Initial, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <long>(json).ToJson());
        }
Ejemplo n.º 8
0
        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.º 9
0
        public override EventID Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            IBsonReader r = context.Reader;

            if (r.CurrentBsonType == BsonType.Null)
            {
                r.ReadNull();
                return(null);
            }

            EnsureBsonTypeEquals(r, BsonType.Int64);
            long rawValue = r.ReadInt64();

            return(new EventID(rawValue));
        }
Ejemplo n.º 10
0
        /*******************************************/

        public override IntPtr Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            IBsonReader bsonReader = context.Reader;

            if (bsonReader.CurrentBsonType == BsonType.Int32)
            {
                return(new IntPtr(bsonReader.ReadInt32()));
            }
            else if (bsonReader.CurrentBsonType == BsonType.Int64)
            {
                return(new IntPtr(bsonReader.ReadInt64()));
            }
            else
            {
                return(new IntPtr());
            }
        }
Ejemplo n.º 11
0
        object GetDeserializedValue(Type valueType, ref IBsonReader bsonReader)
        {
            var bsonType = bsonReader.CurrentBsonType;

            if (bsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
                return(null);
            }

            if (valueType == typeof(Guid))
            {
                var binaryData = bsonReader.ReadBinaryData();
                return(binaryData.ToGuid());
            }
            else if (valueType == typeof(double))
            {
                return(bsonReader.ReadDouble());
            }
            else if (valueType == typeof(float))
            {
                return((float)bsonReader.ReadDouble());
            }
            else if (valueType == typeof(int))
            {
                return(bsonReader.ReadInt32());
            }
            else if (valueType == typeof(long))
            {
                return(bsonReader.ReadInt64());
            }
            else if (valueType == typeof(bool))
            {
                return(bsonReader.ReadBoolean());
            }
            else if (valueType == typeof(string))
            {
                return(bsonReader.ReadString());
            }
            else if (valueType == typeof(decimal))
            {
                return(decimal.Parse(bsonReader.ReadString(), CultureInfo.InvariantCulture));
            }

            throw new FailedConceptSerialization($"Could not deserialize the concept value to '{valueType.FullName}'");
        }
Ejemplo n.º 12
0
        object GetDeserializedValue(Type valueType, ref IBsonReader bsonReader)
        {
            var bsonType = bsonReader.CurrentBsonType;

            if (bsonType == BsonType.Null)
            {
                bsonReader.ReadNull();
                return(null);
            }
            if (valueType == typeof(Guid))
            {
                var binaryData = bsonReader.ReadBinaryData();
                return(binaryData.ToGuid());
            }
            else if (valueType == typeof(double))
            {
                return(bsonReader.ReadDouble());
            }
            else if (valueType == typeof(float))
            {
                return((float)bsonReader.ReadDouble());
            }
            else if (valueType == typeof(Int32))
            {
                return(bsonReader.ReadInt32());
            }
            else if (valueType == typeof(Int64))
            {
                return(bsonReader.ReadInt64());
            }
            else if (valueType == typeof(bool))
            {
                return(bsonReader.ReadBoolean());
            }
            else if (valueType == typeof(string))
            {
                return(bsonReader.ReadString());
            }
            else if (valueType == typeof(decimal))
            {
                return(decimal.Parse(bsonReader.ReadString()));
            }

            throw new Exception();
        }
Ejemplo n.º 13
0
        static object ReadObject(IBsonReader bsonReader)         //_120509_173140 sync, test
        {
            switch (bsonReader.GetCurrentBsonType())
            {
            case BsonType.Array: return(ReadArray(bsonReader));                    // replacement

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

            case BsonType.DateTime: return(BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime()));

            case BsonType.Decimal128: return(Decimal128.ToDecimal(bsonReader.ReadDecimal128()));

            case BsonType.Document: return(ReadCustomObject(bsonReader));                    // replacement

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

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

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

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

            case BsonType.ObjectId: return(bsonReader.ReadObjectId());

            case BsonType.String: return(bsonReader.ReadString());

            case BsonType.Binary:
                var data = bsonReader.ReadBinaryData();
                switch (data.SubType)
                {
                case BsonBinarySubType.UuidLegacy:
                case BsonBinarySubType.UuidStandard:
                    return(data.ToGuid());

                default:
                    return(data);
                }

            default: return(BsonSerializer.Deserialize <BsonValue>(bsonReader));
            }
        }
        /// <summary>
        /// Reads a boolean value.
        /// </summary>
        /// <param name="Reader">Binary reader.</param>
        /// <param name="FieldDataType">Field data type.</param>
        /// <returns>Boolean value.</returns>
        /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception>
        public static bool ReadBoolean(IBsonReader Reader, BsonType FieldDataType)
        {
            switch (FieldDataType)
            {
            case BsonType.Boolean: return(Reader.ReadBoolean());

            case BsonType.Decimal128: return(Reader.ReadDecimal128() != 0);

            case BsonType.Double: return(Reader.ReadDouble() != 0);

            case BsonType.Int32: return(Reader.ReadInt32() != 0);

            case BsonType.Int64: return(Reader.ReadInt64() != 0);

            case BsonType.MinKey: Reader.ReadMinKey(); return(false);

            case BsonType.MaxKey: Reader.ReadMaxKey(); return(true);

            default:
                throw new ArgumentException("Expected a boolean value, but was a " + FieldDataType.ToString() + ".", nameof(FieldDataType));
            }
        }
        internal static object Deserialize(IBsonReader reader)
        {
            switch (reader.GetCurrentBsonType())
            {
            case BsonType.ObjectId:
                return(reader.ReadObjectId());

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

            case BsonType.DateTime:
                return(UnixTime.ToDateTime(reader.ReadDateTime()));

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

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

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

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

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

            case BsonType.String:
                return(reader.ReadString());

            default:
                throw new InvalidOperationException(
                          $"Cannot deserialize {reader.GetCurrentBsonType()} to native value.");
            }
        }
Ejemplo n.º 16
0
        public override TimeSpan Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            IBsonReader reader   = context.Reader;
            BsonType    bsonType = reader.GetCurrentBsonType();

            switch (bsonType)
            {
            case BsonType.Null:
                reader.ReadNull();
                return(TimeSpan.Zero);

            case BsonType.Int32:
                return(TimeSpan.FromMilliseconds((double)reader.ReadInt32()));

            case BsonType.Int64:
                return(TimeSpan.FromMilliseconds((double)reader.ReadInt64()));

            case BsonType.Double:
                return(TimeSpan.FromMilliseconds(reader.ReadDouble()));

            default:
                throw base.CreateCannotDeserializeFromBsonTypeException(bsonType);
            }
        }
        /// <summary>
        /// Reads a 32-bit integer value.
        /// </summary>
        /// <param name="Reader">Binary reader.</param>
        /// <param name="FieldDataType">Field data type.</param>
        /// <returns>32-bit integer value.</returns>
        /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception>
        public static int ReadInt32(IBsonReader Reader, BsonType FieldDataType)
        {
            switch (FieldDataType)
            {
            case BsonType.Boolean: return(Reader.ReadBoolean() ? (int)1 : (int)0);

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

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

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

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

            case BsonType.String: return(int.Parse(Reader.ReadString()));

            case BsonType.MinKey: Reader.ReadMinKey(); return(int.MinValue);

            case BsonType.MaxKey: Reader.ReadMaxKey(); return(int.MaxValue);

            default:
                throw new ArgumentException("Expected a 32-bit integer value, but was a " + FieldDataType.ToString() + ".", nameof(FieldDataType));
            }
        }
Ejemplo n.º 18
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 object Deserialize(IBsonReader Reader, BsonType?DataType, bool Embedded)
        {
            if (!DataType.HasValue)
            {
                DataType = Reader.ReadBsonType();
            }

            switch (DataType.Value)
            {
            case BsonType.Boolean: return(new CaseInsensitiveString(Reader.ReadBoolean().ToString()));

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

            case BsonType.Decimal128: return(new CaseInsensitiveString(Reader.ReadDecimal128().ToString()));

            case BsonType.Double: return(new CaseInsensitiveString(Reader.ReadDouble().ToString()));

            case BsonType.Int32: return(new CaseInsensitiveString(Reader.ReadInt32().ToString()));

            case BsonType.Int64: return(new CaseInsensitiveString(Reader.ReadInt64().ToString()));

            case BsonType.JavaScript: return(new CaseInsensitiveString(Reader.ReadJavaScript()));

            case BsonType.JavaScriptWithScope: return(new CaseInsensitiveString(Reader.ReadJavaScriptWithScope()));

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

            case BsonType.ObjectId: return(new CaseInsensitiveString(Reader.ReadObjectId().ToString()));

            case BsonType.String: return(new CaseInsensitiveString(Reader.ReadString()));

            case BsonType.Symbol: return(new CaseInsensitiveString(Reader.ReadSymbol()));

            default: throw new Exception("Expected a case-insensitive string value.");
            }
        }
Ejemplo n.º 19
0
        private object ReadValue(IBsonReader reader)
        {
            var type = reader.ReadBsonType();

            switch (type)
            {
            case BsonType.EndOfDocument:
                break;

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

            case BsonType.String:
                return(reader.ReadString());

            case BsonType.Document:
                return(EvaluateAsDocument(reader));

            case BsonType.Array:
                break;

            case BsonType.Binary:
                break;

            case BsonType.Undefined:
                break;

            case BsonType.ObjectId:
                break;

            case BsonType.Boolean:
                break;

            case BsonType.DateTime:
                return(reader.ReadDateTime());

            case BsonType.Null:
                return(null);

            case BsonType.RegularExpression:
                break;

            case BsonType.JavaScript:
                break;

            case BsonType.Symbol:
                break;

            case BsonType.JavaScriptWithScope:
                break;

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

            case BsonType.Timestamp:
                break;

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

            case BsonType.Decimal128:
                break;

            case BsonType.MinKey:
                break;

            case BsonType.MaxKey:
                break;

            default:
                break;
            }

            return(null);
        }
Ejemplo n.º 20
0
 /// <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());
 }
Ejemplo n.º 21
0
        // private methods
        private void ReadValue()
        {
            object jsonDotNetValue;

            switch (_wrappedReader.GetCurrentBsonType())
            {
            case BsonType.Array:
                _wrappedReader.ReadStartArray();
                SetCurrentToken(Newtonsoft.Json.JsonToken.StartArray);
                return;

            case BsonType.Binary:
                var bsonBinaryData = _wrappedReader.ReadBinaryData();
                switch (bsonBinaryData.SubType)
                {
                case BsonBinarySubType.UuidLegacy:
                    var guidRepresentation = GuidRepresentation.Unspecified;
                    var bsonReader         = _wrappedReader as BsonReader;
                    if (bsonReader != null)
                    {
                        guidRepresentation = bsonReader.Settings.GuidRepresentation;
                    }
                    jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, guidRepresentation);
                    break;

                case BsonBinarySubType.UuidStandard:
                    jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, GuidRepresentation.Standard);
                    break;

                default:
                    jsonDotNetValue = bsonBinaryData.Bytes;
                    break;
                }
                SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, jsonDotNetValue, bsonBinaryData);
                return;

            case BsonType.Boolean:
                var booleanValue = _wrappedReader.ReadBoolean();
                SetCurrentToken(Newtonsoft.Json.JsonToken.Boolean, booleanValue, (BsonBoolean)booleanValue);
                return;

            case BsonType.DateTime:
                var bsonDateTime = new BsonDateTime(_wrappedReader.ReadDateTime());
                if (bsonDateTime.IsValidDateTime)
                {
                    jsonDotNetValue = bsonDateTime.ToUniversalTime();
                }
                else
                {
                    jsonDotNetValue = bsonDateTime.MillisecondsSinceEpoch;
                }
                SetCurrentToken(Newtonsoft.Json.JsonToken.Date, jsonDotNetValue, bsonDateTime);
                return;

            case BsonType.Document:
                _wrappedReader.ReadStartDocument();
                SetCurrentToken(Newtonsoft.Json.JsonToken.StartObject);
                return;

            case BsonType.Double:
                var bsonDouble = new BsonDouble(_wrappedReader.ReadDouble());
                switch (FloatParseHandling)
                {
                case Newtonsoft.Json.FloatParseHandling.Decimal:
                    jsonDotNetValue = Convert.ToDecimal(bsonDouble);
                    break;

                case Newtonsoft.Json.FloatParseHandling.Double:
                    jsonDotNetValue = bsonDouble.Value;
                    break;

                default:
                    throw new NotSupportedException(string.Format("Unexpected FloatParseHandling value: {0}.", FloatParseHandling));
                }
                SetCurrentToken(Newtonsoft.Json.JsonToken.Float, jsonDotNetValue, bsonDouble);
                return;

            case BsonType.Int32:
                var bsonInt32 = (BsonInt32)_wrappedReader.ReadInt32();
                SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, (long)bsonInt32.Value, bsonInt32);
                return;

            case BsonType.Int64:
                var bsonInt64 = (BsonInt64)_wrappedReader.ReadInt64();
                SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonInt64.Value, bsonInt64);
                return;

            case BsonType.JavaScript:
            {
                var code           = _wrappedReader.ReadJavaScript();
                var bsonJavaScript = new BsonJavaScript(code);
                SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScript);
            }
                return;

            case BsonType.JavaScriptWithScope:
            {
                var code    = _wrappedReader.ReadJavaScriptWithScope();
                var context = BsonDeserializationContext.CreateRoot(_wrappedReader);
                var scope   = BsonDocumentSerializer.Instance.Deserialize <BsonDocument>(context);
                var bsonJavaScriptWithScope = new BsonJavaScriptWithScope(code, scope);
                SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScriptWithScope);
            }
                return;

            case BsonType.MaxKey:
                _wrappedReader.ReadMaxKey();
                SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMaxKey.Value);
                return;

            case BsonType.MinKey:
                _wrappedReader.ReadMinKey();
                SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMinKey.Value);
                return;

            case BsonType.Null:
                _wrappedReader.ReadNull();
                SetCurrentToken(Newtonsoft.Json.JsonToken.Null, null, BsonNull.Value);
                return;

            case BsonType.ObjectId:
                var bsonObjectId = new BsonObjectId(_wrappedReader.ReadObjectId());
                SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, bsonObjectId.Value.ToByteArray(), bsonObjectId);
                return;

            case BsonType.RegularExpression:
                var bsonRegularExpression = _wrappedReader.ReadRegularExpression();
                var pattern = bsonRegularExpression.Pattern;
                var options = bsonRegularExpression.Options;
                jsonDotNetValue = "/" + pattern.Replace("/", "\\/") + "/" + options;
                SetCurrentToken(Newtonsoft.Json.JsonToken.String, jsonDotNetValue, bsonRegularExpression);
                return;

            case BsonType.String:
                var stringValue = _wrappedReader.ReadString();
                SetCurrentToken(Newtonsoft.Json.JsonToken.String, stringValue, (BsonString)stringValue);
                return;

            case BsonType.Symbol:
                var bsonSymbol = BsonSymbolTable.Lookup(_wrappedReader.ReadSymbol());
                SetCurrentToken(Newtonsoft.Json.JsonToken.String, bsonSymbol.Name, bsonSymbol);
                return;

            case BsonType.Timestamp:
                var bsonTimestamp = new BsonTimestamp(_wrappedReader.ReadTimestamp());
                SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonTimestamp.Value, bsonTimestamp);
                return;

            case BsonType.Undefined:
                _wrappedReader.ReadUndefined();
                SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonUndefined.Value);
                return;

            default:
                var message = string.Format("Unexpected BsonType: {0}.", _wrappedReader.GetCurrentBsonType());
                throw new Newtonsoft.Json.JsonReaderException(message);
            }
        }
 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());
 }
 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());
 }
Ejemplo n.º 24
0
        public override bool Read()
        {
            if (bsonReader.State == BsonReaderState.Initial ||
                bsonReader.State == BsonReaderState.ScopeDocument ||
                bsonReader.State == BsonReaderState.Type)
            {
                bsonReader.ReadBsonType();
            }

            if (bsonReader.State == BsonReaderState.Name)
            {
                SetToken(NewtonsoftJsonToken.PropertyName, bsonReader.ReadName().UnescapeBson());
            }
            else if (bsonReader.State == BsonReaderState.Value)
            {
                switch (bsonReader.CurrentBsonType)
                {
                case BsonType.Document:
                    SetToken(NewtonsoftJsonToken.StartObject);
                    bsonReader.ReadStartDocument();
                    break;

                case BsonType.Array:
                    SetToken(NewtonsoftJsonToken.StartArray);
                    bsonReader.ReadStartArray();
                    break;

                case BsonType.Undefined:
                    SetToken(NewtonsoftJsonToken.Undefined);
                    bsonReader.ReadUndefined();
                    break;

                case BsonType.Null:
                    SetToken(NewtonsoftJsonToken.Null);
                    bsonReader.ReadNull();
                    break;

                case BsonType.String:
                    SetToken(NewtonsoftJsonToken.String, bsonReader.ReadString());
                    break;

                case BsonType.Binary:
                    SetToken(NewtonsoftJsonToken.Bytes, bsonReader.ReadBinaryData().Bytes);
                    break;

                case BsonType.Boolean:
                    SetToken(NewtonsoftJsonToken.Boolean, bsonReader.ReadBoolean());
                    break;

                case BsonType.DateTime:
                    SetToken(NewtonsoftJsonToken.Date, bsonReader.ReadDateTime());
                    break;

                case BsonType.Int32:
                    SetToken(NewtonsoftJsonToken.Integer, bsonReader.ReadInt32());
                    break;

                case BsonType.Int64:
                    SetToken(NewtonsoftJsonToken.Integer, bsonReader.ReadInt64());
                    break;

                case BsonType.Double:
                    SetToken(NewtonsoftJsonToken.Float, bsonReader.ReadDouble());
                    break;

                case BsonType.Decimal128:
                    SetToken(NewtonsoftJsonToken.Float, Decimal128.ToDouble(bsonReader.ReadDecimal128()));
                    break;

                default:
                    throw new NotSupportedException();
                }
            }
            else if (bsonReader.State == BsonReaderState.EndOfDocument)
            {
                SetToken(NewtonsoftJsonToken.EndObject);
                bsonReader.ReadEndDocument();
            }
            else if (bsonReader.State == BsonReaderState.EndOfArray)
            {
                SetToken(NewtonsoftJsonToken.EndArray);
                bsonReader.ReadEndArray();
            }

            if (bsonReader.State == BsonReaderState.Initial)
            {
                return(true);
            }

            return(!bsonReader.IsAtEndOfFile());
        }
Ejemplo n.º 25
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)
        {
            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));
        }
Ejemplo n.º 26
0
 public void TestInt64ConstructorQuoted()
 {
     var json = "NumberLong(\"123456789012\")";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.AreEqual(BsonType.Int64, _bsonReader.ReadBsonType());
         Assert.AreEqual(123456789012, _bsonReader.ReadInt64());
         Assert.AreEqual(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.AreEqual(json, BsonSerializer.Deserialize<long>(json).ToJson());
 }