示例#1
0
        private void DeserializeDataPoints(IBsonReader reader, ref Measurement m)
        {
            IDictionary <string, DataPoint> datapoints;
            DataPoint dp;
            string    key;

            datapoints = new Dictionary <string, DataPoint>();
            reader.ReadStartDocument();

            while (reader.State != BsonReaderState.EndOfDocument)
            {
                dp  = new DataPoint();
                key = reader.ReadName();
                reader.ReadStartDocument();

                while (reader.CurrentBsonType != BsonType.EndOfDocument)
                {
                    this.DeserializeDataPointAttribute(reader.ReadName(), reader, ref dp);
                    reader.ReadBsonType();
                }

                reader.ReadEndDocument();
                reader.ReadBsonType();

                datapoints[key] = dp;
            }

            reader.ReadEndDocument();
            m.Data = datapoints;
        }
        public void TestDocumentNested()
        {
            var json = "{ \"a\" : { \"x\" : 1 }, \"y\" : 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(BsonType.Int32, _bsonReader.ReadBsonType());
                Assert.Equal("x", _bsonReader.ReadName());
                Assert.Equal(1, _bsonReader.ReadInt32());
                Assert.Equal(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReadEndDocument();
                Assert.Equal(BsonType.Int32, _bsonReader.ReadBsonType());
                Assert.Equal("y", _bsonReader.ReadName());
                Assert.Equal(2, _bsonReader.ReadInt32());
                Assert.Equal(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReadEndDocument();
                Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
            }
            Assert.Equal(json, BsonSerializer.Deserialize <BsonDocument>(json).ToJson());
        }
示例#3
0
    public override Balance Deserialize(IBsonReader bsonReader)
    {
        string read = null;

        bsonReader.ReadStartDocument();
        var balance =
            bsonReader
            .ReadDocument(
                "_id",
                ref read,
                bR =>
        {
            // ReSharper disable AccessToModifiedClosure
            bR.ReadStartDocument();
            var bal =
                new Balance
            {
                Date     = bR.ReadDateTime("date", ref read),
                User     = bR.ReadString("user", ref read),
                Currency = bR.ReadString("currency", ref read),
                Title    = bR.ReadInt32("title", ref read),
                SubTitle = bR.ReadInt32("subtitle", ref read),
                Content  = bR.ReadString("content", ref read),
                Remark   = bR.ReadString("remark", ref read),
            };
            bR.ReadEndDocument();
            return(bal);
            // ReSharper restore AccessToModifiedClosure
        });

        balance.Fund = bsonReader.ReadDouble("total", ref read) ?? bsonReader.ReadInt32("count", ref read) !.Value;
        bsonReader.ReadEndDocument();

        return(balance);
    }
        internal static KeyValuePair <string, object> ReadDocument(this IBsonReader reader)
        {
            var key   = reader.ReadName();
            var value = default(object);

            // Setting bookmark to beginning of the document to rewind reader later
            var beginning = reader.GetBookmark();

            reader.ReadStartDocument();

            // Reading type before rewinding to the start
            var field = reader.ReadName();

            // Rewinding back to the start
            reader.ReturnToBookmark(beginning);

            switch (field)
            {
            case "_name":
                value = BsonSerializer.Deserialize <EntityReference>(reader);
                break;

            case "_money":
                value = BsonSerializer.Deserialize <Money>(reader);
                break;

            case "_option":
                value = BsonSerializer.Deserialize <OptionSetValue>(reader);
                break;
            }

            reader.ReadEndDocument();

            return(new KeyValuePair <string, object>(key, value));
        }
示例#5
0
        public override TValue Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            //boxing is required for SetValue to work
            object      obj        = new TValue();
            Type        actualType = args.NominalType;
            IBsonReader bsonReader = context.Reader;

            bsonReader.ReadStartDocument();

            while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
            {
                string name = bsonReader.ReadName(Utf8NameDecoder.Instance);

                FieldInfo field = actualType.GetField(name);
                if (field != null)
                {
                    object value = BsonSerializer.Deserialize(bsonReader, field.FieldType);
                    field.SetValue(obj, value);
                }
            }

            bsonReader.ReadEndDocument();

            return((TValue)obj);
        }
示例#6
0
        /// <summary>
        /// Deserialises a value from key/value pairs.
        /// </summary>
        /// <param name="context">The deserialisation context.</param>
        /// <param name="args">The deserialisation arguments.</param>
        /// <returns>
        /// A deserialised value.
        /// </returns>
        public override TStruct Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            //boxing is required for SetValue to work
            var         obj        = (object)(new TStruct());
            Type        actualType = args.NominalType;
            IBsonReader bsonReader = context.Reader;

            bsonReader.ReadStartDocument();

            while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
            {
                var name = bsonReader.ReadName();

                var field = actualType.GetField(name);
                if (field != null)
                {
                    var value = BsonSerializer.Deserialize(bsonReader, field.FieldType);
                    field.SetValue(obj, value);
                }

                var prop = actualType.GetProperty(name);
                if (prop != null)
                {
                    var value = BsonSerializer.Deserialize(bsonReader, prop.PropertyType);
                    prop.SetValue(obj, value, null);
                }
            }

            bsonReader.ReadEndDocument();

            return((TStruct)obj);
        }
        // private methods
        private bool IsCSharpNullRepresentation(IBsonReader bsonReader)
        {
            var bookmark = bsonReader.GetBookmark();

            bsonReader.ReadStartDocument();
            var bsonType = bsonReader.ReadBsonType();

            if (bsonType == BsonType.Boolean)
            {
                var name = bsonReader.ReadName();
                if (name == "_csharpnull" || name == "$csharpnull")
                {
                    var value = bsonReader.ReadBoolean();
                    if (value)
                    {
                        bsonType = bsonReader.ReadBsonType();
                        if (bsonType == BsonType.EndOfDocument)
                        {
                            bsonReader.ReadEndDocument();
                            return(true);
                        }
                    }
                }
            }

            bsonReader.ReturnToBookmark(bookmark);
            return(false);
        }
示例#8
0
        public override Voucher Deserialize(IBsonReader bsonReader)
        {
            string read = null;

            bsonReader.ReadStartDocument();

            var voucher = new Voucher
            {
                ID   = bsonReader.ReadObjectId("_id", ref read),
                Date = bsonReader.ReadDateTime("date", ref read),
                Type = VoucherType.Ordinary,
            };

            voucher.Type = bsonReader.ReadString("special", ref read) switch
            {
                "amorz" => VoucherType.Amortization,
                "acarry" => VoucherType.AnnualCarry,
                "carry" => VoucherType.Carry,
                "dep" => VoucherType.Depreciation,
                "dev" => VoucherType.Devalue,
                "unc" => VoucherType.Uncertain,
                _ => VoucherType.Ordinary,
            };

            voucher.Details = bsonReader.ReadArray("detail", ref read, new VoucherDetailSerializer().Deserialize);
            voucher.Remark  = bsonReader.ReadString("remark", ref read);
            bsonReader.ReadEndDocument();

            return(voucher);
        }
示例#9
0
        public FieldValueChange Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
        {
            FieldValueChange fieldValueChange = new FieldValueChange();
            IBsonReader      reader           = context.Reader;

            BsonType bysonType = reader.GetCurrentBsonType();

            if (bysonType == BsonType.Document)
            {
                reader.ReadStartDocument();
                string name = reader.ReadName();
                fieldValueChange.OriginalValue = base.Deserialize(context, args);
                name = reader.ReadName();
                fieldValueChange.NewValue = base.Deserialize(context, args);
                reader.ReadEndDocument();

                return(fieldValueChange);
            }
            else
            {
                fieldValueChange.OriginalValue = base.Deserialize(context, args);
            }

            return(fieldValueChange);
        }
示例#10
0
        private JObject GenerateJObject(IBsonReader reader, JToken parent)
        {
            var jobject = new JObject();

            reader.ReadStartDocument();
            string propertyName = null;

            do
            {
                if (reader.State == BsonReaderState.Type)
                {
                    reader.ReadBsonType();
                }

                if (reader.State == BsonReaderState.Name)
                {
                    propertyName = reader.ReadName();
                }

                if (reader.State == BsonReaderState.Value)
                {
                    var value = GenerateJToken(reader, jobject);
                    jobject.Add(propertyName, value);
                }
            } while (reader.State != BsonReaderState.EndOfDocument);
            reader.ReadEndDocument();
            return(jobject);
        }
        public override Amortization Deserialize(IBsonReader bsonReader)
        {
            string read = null;

            bsonReader.ReadStartDocument();

            var amort = new Amortization
            {
                ID        = bsonReader.ReadGuid("_id", ref read),
                User      = bsonReader.ReadString("user", ref read),
                Name      = bsonReader.ReadString("name", ref read),
                Value     = bsonReader.ReadDouble("value", ref read),
                Date      = bsonReader.ReadDateTime("date", ref read),
                TotalDays = bsonReader.ReadInt32("tday", ref read),
            };

            amort.Interval = bsonReader.ReadString("interval", ref read) switch
            {
                "d" => AmortizeInterval.EveryDay,
                "w" => AmortizeInterval.SameDayOfWeek,
                "W" => AmortizeInterval.LastDayOfWeek,
                "m" => AmortizeInterval.SameDayOfMonth,
                "M" => AmortizeInterval.LastDayOfMonth,
                "y" => AmortizeInterval.SameDayOfYear,
                "Y" => AmortizeInterval.LastDayOfYear,
                _ => amort.Interval,
            };

            amort.Template = bsonReader.ReadDocument("template", ref read, VoucherSerializer.Deserialize);
            amort.Schedule = bsonReader.ReadArray("schedule", ref read, ItemSerializer.Deserialize);
            amort.Remark   = bsonReader.ReadString("remark", ref read);
            bsonReader.ReadEndDocument();
            return(amort);
        }
示例#12
0
        // private methods
        private CollectionNamespace DeserializeCollectionNamespace(IBsonReader reader)
        {
            string collectionName = null;
            string databaseName   = null;

            reader.ReadStartDocument();
            while (reader.ReadBsonType() != 0)
            {
                var fieldName = reader.ReadName();
                switch (fieldName)
                {
                case "db":
                    databaseName = reader.ReadString();
                    break;

                case "coll":
                    collectionName = reader.ReadString();
                    break;

                default:
                    throw new FormatException($"Invalid field name: \"{fieldName}\".");
                }
            }
            reader.ReadEndDocument();

            var databaseNamespace = new DatabaseNamespace(databaseName);

            return(new CollectionNamespace(databaseNamespace, collectionName));
        }
示例#13
0
        public override Asset Deserialize(IBsonReader bsonReader)
        {
            string read = null;

            bsonReader.ReadStartDocument();

            var asset = new Asset
            {
                ID                       = bsonReader.ReadGuid("_id", ref read),
                User                     = bsonReader.ReadString("user", ref read),
                Name                     = bsonReader.ReadString("name", ref read),
                Date                     = bsonReader.ReadDateTime("date", ref read),
                Currency                 = bsonReader.ReadString("currency", ref read),
                Value                    = bsonReader.ReadDouble("value", ref read),
                Salvge                   = bsonReader.ReadDouble("salvge", ref read),
                Life                     = bsonReader.ReadInt32("life", ref read),
                Title                    = bsonReader.ReadInt32("title", ref read),
                DepreciationTitle        = bsonReader.ReadInt32("deptitle", ref read),
                DevaluationTitle         = bsonReader.ReadInt32("devtitle", ref read),
                DepreciationExpenseTitle = bsonReader.ReadInt32("exptitle", ref read),
                DevaluationExpenseTitle  = bsonReader.ReadInt32("exvtitle", ref read)
            };

            switch (bsonReader.ReadString("method", ref read))
            {
            case "sl":
                asset.Method = DepreciationMethod.StraightLine;
                break;

            case "sy":
                asset.Method = DepreciationMethod.SumOfTheYear;
                break;

            case "dd":
                asset.Method = DepreciationMethod.DoubleDeclineMethod;
                break;

            default:
                asset.Method = DepreciationMethod.None;
                break;
            }

            if (asset.DepreciationExpenseTitle > 100)
            {
                asset.DepreciationExpenseSubTitle = asset.DepreciationExpenseTitle % 100;
                asset.DepreciationExpenseTitle   /= 100;
            }

            if (asset.DevaluationExpenseTitle > 100)
            {
                asset.DevaluationExpenseSubTitle = asset.DevaluationExpenseTitle % 100;
                asset.DevaluationExpenseTitle   /= 100;
            }

            asset.Schedule = bsonReader.ReadArray("schedule", ref read, ItemSerializer.Deserialize);
            asset.Remark   = bsonReader.ReadString("remark", ref read);
            bsonReader.ReadEndDocument();
            return(asset);
        }
        /// <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.DateTime: return((DateTimeOffset?)ObjectSerializer.UnixEpoch.AddMilliseconds(Reader.ReadDateTime()));

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

            case BsonType.Document:
                DateTime TP = DateTime.MinValue;
                TimeSpan TZ = TimeSpan.Zero;

                Reader.ReadStartDocument();

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

                    string FieldName = Reader.ReadName();
                    switch (FieldName)
                    {
                    case "tp":
                        TP = ObjectSerializer.UnixEpoch.AddMilliseconds(Reader.ReadDateTime());
                        break;

                    case "tz":
                        TZ = TimeSpan.Parse(Reader.ReadString());
                        break;
                    }
                }

                Reader.ReadEndDocument();

                return((DateTimeOffset?)new DateTimeOffset(TP, TZ));

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

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

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

            default: throw new Exception("Expected a nullable DateTimeOffset value.");
            }
        }
        public void TestNestedDocument()
        {
            var json = "{ \"a\" : { \"b\" : 1, \"c\" : 2 } }";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReadStartDocument();
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                Assert.AreEqual("a", _bsonReader.ReadName());
                _bsonReader.ReadStartDocument();
                Assert.AreEqual("b", _bsonReader.ReadName());
                Assert.AreEqual(1, _bsonReader.ReadInt32());
                Assert.AreEqual("c", _bsonReader.ReadName());
                Assert.AreEqual(2, _bsonReader.ReadInt32());
                _bsonReader.ReadEndDocument();
                _bsonReader.ReadEndDocument();
                Assert.AreEqual(BsonReaderState.Initial, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(json).ToJson());
        }
        public override Amortization Deserialize(IBsonReader bsonReader)
        {
            string read = null;

            bsonReader.ReadStartDocument();

            var amort = new Amortization
            {
                ID        = bsonReader.ReadGuid("_id", ref read),
                User      = bsonReader.ReadString("user", ref read),
                Name      = bsonReader.ReadString("name", ref read),
                Value     = bsonReader.ReadDouble("value", ref read),
                Date      = bsonReader.ReadDateTime("date", ref read),
                TotalDays = bsonReader.ReadInt32("tday", ref read)
            };

            switch (bsonReader.ReadString("interval", ref read))
            {
            case "d":
                amort.Interval = AmortizeInterval.EveryDay;
                break;

            case "w":
                amort.Interval = AmortizeInterval.SameDayOfWeek;
                break;

            case "W":
                amort.Interval = AmortizeInterval.LastDayOfWeek;
                break;

            case "m":
                amort.Interval = AmortizeInterval.SameDayOfMonth;
                break;

            case "M":
                amort.Interval = AmortizeInterval.LastDayOfMonth;
                break;

            case "y":
                amort.Interval = AmortizeInterval.SameDayOfYear;
                break;

            case "Y":
                amort.Interval = AmortizeInterval.LastDayOfYear;
                break;
            }

            amort.Template = bsonReader.ReadDocument("template", ref read, VoucherSerializer.Deserialize);
            amort.Schedule = bsonReader.ReadArray("schedule", ref read, ItemSerializer.Deserialize);
            amort.Remark   = bsonReader.ReadString("remark", ref read);
            bsonReader.ReadEndDocument();
            return(amort);
        }
示例#17
0
        public void TestDocumentEmpty()
        {
            var json = "{ }";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.Equal(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReadStartDocument();
                Assert.Equal(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReadEndDocument();
                Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
            }
            Assert.Equal(json, BsonSerializer.Deserialize <BsonDocument>(json).ToJson());
        }
        public override Voucher Deserialize(IBsonReader bsonReader)
        {
            string read = null;

            bsonReader.ReadStartDocument();

            var voucher = new Voucher
            {
                ID   = bsonReader.ReadObjectId("_id", ref read),
                Date = bsonReader.ReadDateTime("date", ref read),
                Type = VoucherType.Ordinary
            };

            switch (bsonReader.ReadString("special", ref read))
            {
            case "amorz":
                voucher.Type = VoucherType.Amortization;
                break;

            case "acarry":
                voucher.Type = VoucherType.AnnualCarry;
                break;

            case "carry":
                voucher.Type = VoucherType.Carry;
                break;

            case "dep":
                voucher.Type = VoucherType.Depreciation;
                break;

            case "dev":
                voucher.Type = VoucherType.Devalue;
                break;

            case "unc":
                voucher.Type = VoucherType.Uncertain;
                break;

            default:
                voucher.Type = VoucherType.Ordinary;
                break;
            }

            voucher.Details = bsonReader.ReadArray("detail", ref read, new VoucherDetailSerializer().Deserialize);
            voucher.Remark  = bsonReader.ReadString("remark", ref read);
            bsonReader.ReadEndDocument();

            return(voucher);
        }
        /// <summary>
        /// Reads a date &amp; time value with offset.
        /// </summary>
        /// <param name="Reader">Binary reader.</param>
        /// <param name="FieldDataType">Field data type.</param>
        /// <returns>DateTimeOffset value.</returns>
        /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception>
        public static DateTimeOffset ReadDateTimeOffset(IBsonReader Reader, BsonType FieldDataType)
        {
            switch (FieldDataType)
            {
            case BsonType.DateTime: return((DateTimeOffset)ObjectSerializer.UnixEpoch.AddMilliseconds(Reader.ReadDateTime()));

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

            case BsonType.Document:
                DateTime TP = DateTime.MinValue;
                TimeSpan TZ = TimeSpan.Zero;

                Reader.ReadStartDocument();

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

                    string FieldName = Reader.ReadName();
                    switch (FieldName)
                    {
                    case "tp":
                        TP = ObjectSerializer.UnixEpoch.AddMilliseconds(Reader.ReadDateTime());
                        break;

                    case "tz":
                        TZ = TimeSpan.Parse(Reader.ReadString());
                        break;
                    }
                }

                Reader.ReadEndDocument();

                return(new DateTimeOffset(TP, TZ));

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

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

            default:
                throw new ArgumentException("Expected a date & time value with offset, but was a " +
                                            FieldDataType.ToString() + ".", nameof(FieldDataType));
            }
        }
示例#20
0
        static PSObject ReadCustomObject(IBsonReader bsonReader)
        {
            var ps         = new PSObject();
            var properties = ps.Properties;

            bsonReader.ReadStartDocument();
            while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
            {
                var name  = bsonReader.ReadName();
                var value = ReadObject(bsonReader);
                properties.Add(new PSNoteProperty(name, value), true);                 //! true is faster
            }
            bsonReader.ReadEndDocument();

            return(ps);
        }
        public override AmortItem Deserialize(IBsonReader bsonReader)
        {
            string read = null;

            bsonReader.ReadStartDocument();
            var item = new AmortItem
            {
                VoucherID = bsonReader.ReadObjectId("voucher", ref read),
                Date      = bsonReader.ReadDateTime("date", ref read),
                Amount    = bsonReader.ReadDouble("amount", ref read) ?? 0D,
                Remark    = bsonReader.ReadString("remark", ref read)
            };

            bsonReader.ReadEndDocument();
            return(item);
        }
示例#22
0
    public override AssetItem Deserialize(IBsonReader bsonReader)
    {
        string read = null;

        bsonReader.ReadStartDocument();
        var vid = bsonReader.ReadObjectId("voucher", ref read);
        var dt  = bsonReader.ReadDateTime("date", ref read);
        var rmk = bsonReader.ReadString("remark", ref read);

        AssetItem item;
        double?   val;

        if ((val = bsonReader.ReadDouble("acq", ref read)).HasValue)
        {
            item = new AcquisitionItem {
                VoucherID = vid, Date = dt, Remark = rmk, OrigValue = val.Value
            }
        }
        ;
        else if ((val = bsonReader.ReadDouble("dep", ref read)).HasValue)
        {
            item = new DepreciateItem {
                VoucherID = vid, Date = dt, Remark = rmk, Amount = val.Value
            }
        }
        ;
        else if ((val = bsonReader.ReadDouble("devto", ref read)).HasValue)
        {
            item = new DevalueItem {
                VoucherID = vid, Date = dt, Remark = rmk, FairValue = val.Value
            }
        }
        ;
        else if (bsonReader.ReadNull("dispo", ref read))
        {
            item = new DispositionItem {
                VoucherID = vid, Date = dt, Remark = rmk
            }
        }
        ;
        else
        {
            item = null;
        }
        bsonReader.ReadEndDocument();
        return(item);
    }
        public void TestDocumentOneElement()
        {
            var json = "{ \"x\" : 1 }";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReadStartDocument();
                Assert.AreEqual(BsonType.Int32, _bsonReader.ReadBsonType());
                Assert.AreEqual("x", _bsonReader.ReadName());
                Assert.AreEqual(1, _bsonReader.ReadInt32());
                Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
                _bsonReader.ReadEndDocument();
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(json).ToJson());
        }
示例#24
0
        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());
        }
示例#25
0
        /// <inheritdoc/>
        public override bool Read()
        {
            switch (_wrappedReader.State)
            {
            case BsonReaderState.Closed:
            case BsonReaderState.Done:
                return(false);

            case BsonReaderState.EndOfArray:
                _wrappedReader.ReadEndArray();
                SetCurrentToken(Newtonsoft.Json.JsonToken.EndArray);
                return(true);

            case BsonReaderState.EndOfDocument:
                _wrappedReader.ReadEndDocument();
                SetCurrentToken(Newtonsoft.Json.JsonToken.EndObject);
                return(true);

            case BsonReaderState.Initial:
            case BsonReaderState.Type:
                if (_wrappedReader.State == BsonReaderState.Initial && _wrappedReader.IsAtEndOfFile())
                {
                    SetCurrentToken(Newtonsoft.Json.JsonToken.None);
                    return(false);
                }
                else
                {
                    _wrappedReader.ReadBsonType();
                    return(Read());
                }

            case BsonReaderState.Name:
                var name = _wrappedReader.ReadName();
                name = _propertyNameBinder?.ReadName(name) ?? name;
                SetCurrentToken(Newtonsoft.Json.JsonToken.PropertyName, name);
                return(true);

            case BsonReaderState.Value:
                ReadValue();
                return(true);

            default:
                throw new Newtonsoft.Json.JsonReaderException(string.Format("Unexpected IBsonReader state: {0}.", _wrappedReader.State));
            }
        }
        public override VoucherDetail Deserialize(IBsonReader bsonReader)
        {
            string read = null;

            bsonReader.ReadStartDocument();
            var detail = new VoucherDetail
            {
                Currency = bsonReader.ReadString("currency", ref read),
                Title    = bsonReader.ReadInt32("title", ref read),
                SubTitle = bsonReader.ReadInt32("subtitle", ref read),
                Content  = bsonReader.ReadString("content", ref read),
                Fund     = bsonReader.ReadDouble("fund", ref read),
                Remark   = bsonReader.ReadString("remark", ref read)
            };

            bsonReader.ReadEndDocument();

            return(detail);
        }
        public void TestNestedArray()
        {
            var json = "{ \"a\" : [1, 2] }";

            using (_bsonReader = new JsonReader(json))
            {
                Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReadStartDocument();
                Assert.AreEqual(BsonType.Array, _bsonReader.ReadBsonType());
                Assert.AreEqual("a", _bsonReader.ReadName());
                _bsonReader.ReadStartArray();
                Assert.AreEqual(1, _bsonReader.ReadInt32());
                Assert.AreEqual(2, _bsonReader.ReadInt32());
                _bsonReader.ReadEndArray();
                _bsonReader.ReadEndDocument();
                Assert.AreEqual(BsonReaderState.Done, _bsonReader.State);
            }
            Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(json).ToJson());
        }
        public override ExchangeRecord Deserialize(IBsonReader bsonReader)
        {
            string read = null;

            bsonReader.ReadStartDocument();
            var record = bsonReader.ReadDocument("_id", ref read, br =>
            {
                br.ReadStartDocument();
                var rec = new ExchangeRecord
                {
                    Date = br.ReadDateTime("date", ref read).Value,
                    From = br.ReadString("from", ref read),
                    To   = br.ReadString("to", ref read),
                };
                br.ReadEndDocument();
                return(rec);
            });

            record.Value = bsonReader.ReadDouble("value", ref read).Value;
            bsonReader.ReadEndDocument();
            return(record);
        }
 public void TestDocumentTwoElements()
 {
     var json = "{ \"x\" : 1, \"y\" : 2 }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Document, _bsonReader.ReadBsonType());
         _bsonReader.ReadStartDocument();
         Assert.Equal(BsonType.Int32, _bsonReader.ReadBsonType());
         Assert.Equal("x", _bsonReader.ReadName());
         Assert.Equal(1, _bsonReader.ReadInt32());
         Assert.Equal(BsonType.Int32, _bsonReader.ReadBsonType());
         Assert.Equal("y", _bsonReader.ReadName());
         Assert.Equal(2, _bsonReader.ReadInt32());
         Assert.Equal(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
         _bsonReader.ReadEndDocument();
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonDocument>(json).ToJson());
 }
示例#30
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.Equal(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.Equal(BsonType.Document, _bsonReader.ReadBsonType());

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

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

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

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

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

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

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

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

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

                Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
            }
            Assert.Equal(json, BsonSerializer.Deserialize <BsonDocument>(json).ToJson());
        }
示例#31
0
 public void TestNestedArray()
 {
     var json = "{ \"a\" : [1, 2] }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType());
         _bsonReader.ReadStartDocument();
         Assert.AreEqual(BsonType.Array, _bsonReader.ReadBsonType());
         Assert.AreEqual("a", _bsonReader.ReadName());
         _bsonReader.ReadStartArray();
         Assert.AreEqual(1, _bsonReader.ReadInt32());
         Assert.AreEqual(2, _bsonReader.ReadInt32());
         _bsonReader.ReadEndArray();
         _bsonReader.ReadEndDocument();
         Assert.AreEqual(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.AreEqual(json, BsonSerializer.Deserialize<BsonDocument>(json).ToJson());
 }
        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.Equal(BsonType.Document, _bsonReader.ReadBsonType());
                _bsonReader.ReturnToBookmark(bookmark);
                Assert.Equal(BsonType.Document, _bsonReader.ReadBsonType());

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

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

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

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

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

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

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

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

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

                Assert.Equal(BsonReaderState.Initial, _bsonReader.State);

            }
            Assert.Equal(json, BsonSerializer.Deserialize<BsonDocument>(json).ToJson());
        }
 public void TestDocumentEmpty()
 {
     var json = "{ }";
     using (_bsonReader = new JsonReader(json))
     {
         Assert.Equal(BsonType.Document, _bsonReader.ReadBsonType());
         _bsonReader.ReadStartDocument();
         Assert.Equal(BsonType.EndOfDocument, _bsonReader.ReadBsonType());
         _bsonReader.ReadEndDocument();
         Assert.Equal(BsonReaderState.Initial, _bsonReader.State);
     }
     Assert.Equal(json, BsonSerializer.Deserialize<BsonDocument>(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());
 }
示例#35
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));
        }
 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());
 }