/// <summary>
        /// Reads a string value.
        /// </summary>
        /// <param name="Reader">Binary reader.</param>
        /// <param name="FieldDataType">Field data type.</param>
        /// <returns>String value.</returns>
        /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception>
        public static string ReadString(IBsonReader Reader, BsonType FieldDataType)
        {
            switch (FieldDataType)
            {
            case BsonType.Boolean: return(Reader.ReadBoolean().ToString());

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

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

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

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

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

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

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

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

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

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

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

            default:
                throw new ArgumentException("Expected a char value, but was a " +
                                            FieldDataType.ToString() + ".", nameof(FieldDataType));
            }
        }
예제 #2
0
        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());
        }
예제 #3
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.");
            }
        }
예제 #4
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));
        }
예제 #5
0
 /// <summary>
 /// Reads a BSON JavaScript 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 ReadJavaScript(this IBsonReader reader, string name)
 {
     VerifyName(reader, name);
     return(reader.ReadJavaScript());
 }
        // 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 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());
 }