예제 #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;
        }
예제 #2
0
        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
        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));
        }
예제 #4
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);
        }
        /***************************************************/
        /**** Interface Methods                         ****/
        /***************************************************/

        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            Type actualType = nominalType;

            // the BsonReader is sitting at the value whose actual type needs to be found
            BsonType bsonType = bsonReader.GetCurrentBsonType();

            if (bsonType == BsonType.Document)
            {
                var bookmark = bsonReader.GetBookmark();
                bsonReader.ReadStartDocument();

                if (bsonReader.FindElement(ElementName))
                {
                    var context       = BsonDeserializationContext.CreateRoot(bsonReader);
                    var discriminator = BsonValueSerializer.Instance.Deserialize(context);
                    if (discriminator.IsBsonArray)
                    {
                        discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator
                    }
                    if (BsonSerializer.IsTypeDiscriminated(nominalType))
                    {
                        actualType = BsonSerializer.LookupActualType(nominalType, discriminator);
                    }
                }
                bsonReader.ReturnToBookmark(bookmark);
            }

            return(actualType);
        }
예제 #6
0
        /***************************************************/
        /**** Interface Methods                         ****/
        /***************************************************/

        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            // the BsonReader is sitting at the value whose actual type needs to be found
            var bsonType = bsonReader.GetCurrentBsonType();

            if (bsonType == BsonType.Document)
            {
                var bookmark = bsonReader.GetBookmark();
                bsonReader.ReadStartDocument();
                var actualType = nominalType;
                if (bsonReader.FindElement(ElementName))
                {
                    var context       = BsonDeserializationContext.CreateRoot(bsonReader);
                    var discriminator = BsonValueSerializer.Instance.Deserialize(context);
                    actualType = BsonSerializer.LookupActualType(nominalType, discriminator);
                }
                else
                {
                    actualType = typeof(CustomObject);
                }

                bsonReader.ReturnToBookmark(bookmark);
                return(actualType);
            }

            return(nominalType);
        }
예제 #7
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);
        }
    public Type GetActualType(IBsonReader bsonReader, Type nominalType)
    {
        if (!typeof(T).IsAssignableFrom(nominalType))
        {
            throw new Exception($"Cannot use DiscriminatorConvention<{typeof(T).Name}> for type " + nominalType);
        }

        var ret = nominalType;

        var bookmark = bsonReader.GetBookmark();

        bsonReader.ReadStartDocument();
        if (bsonReader.FindElement(ElementName))
        {
            var value = bsonReader.ReadString();
            ret = Type.GetType(value);

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

            if (!typeof(T).IsAssignableFrom(ret) && !ret.IsSubclassOf(typeof(T)))
            {
                throw new Exception("type is not an IRestriction");
            }
        }

        bsonReader.ReturnToBookmark(bookmark);

        return(ret);
    }
예제 #9
0
        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            if (nominalType == typeof(OrderModel))
            {
                var ret = nominalType;

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

                    ret = OrderTypeResolver.ResolveOrderType(value);

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

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

                bsonReader.ReturnToBookmark(bookmark);

                return(ret);
            }
            else
            {
                return(nominalType);
            }
        }
예제 #10
0
    /// <inheritdoc/>
    public Type GetActualType(IBsonReader bsonReader, Type nominalType)
    {
        ThrowIfNominalTypeIsIncorrect(nominalType);
        var bookmark = bsonReader.GetBookmark();

        bsonReader.ReadStartDocument();
        ObjectId id = default;

        while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
        {
            var fieldName = bsonReader.ReadName();
            if (fieldName == ElementName)
            {
                var partitioned = bsonReader.ReadBoolean();
                bsonReader.ReturnToBookmark(bookmark);
                return(partitioned ? typeof(Partitioned.PartitionedStreamProcessorState) : typeof(StreamProcessorState));
            }
            else if (fieldName == "_id")
            {
                id = bsonReader.ReadObjectId();
            }
            else
            {
                bsonReader.SkipValue();
            }
        }

        bsonReader.ReturnToBookmark(bookmark);
        throw new StreamProcessorStateDocumentIsMissingPartitionedField(id);
    }
예제 #11
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);
        }
        // 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);
        }
            public Type GetActualType(IBsonReader bsonReader, Type nominalType)
            {
                var bookmark = bsonReader.GetBookmark();

                bsonReader.ReadStartDocument();
                var actualType = nominalType;

                while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
                {
                    var name = bsonReader.ReadName();
                    if (name == "OnlyInB")
                    {
                        actualType = typeof(B);
                        break;
                    }
                    else if (name == "OnlyInC")
                    {
                        actualType = typeof(C);
                        break;
                    }
                    bsonReader.SkipValue();
                }
                bsonReader.ReturnToBookmark(bookmark);
                return(actualType);
            }
예제 #14
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);
        }
예제 #15
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));
        }
        // public methods
        /// <summary>
        /// Gets the actual type of an object by reading the discriminator from a BsonReader.
        /// </summary>
        /// <param name="bsonReader">The reader.</param>
        /// <param name="nominalType">The nominal type.</param>
        /// <returns>The actual type.</returns>
        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            // the BsonReader is sitting at the value whose actual type needs to be found
            var bsonType = bsonReader.GetCurrentBsonType();

            if (bsonType == BsonType.Document)
            {
                // ensure KnownTypes of nominalType are registered (so IsTypeDiscriminated returns correct answer)
                BsonSerializer.EnsureKnownTypesAreRegistered(nominalType);

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

            return(nominalType);
        }
예제 #17
0
        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            if (nominalType == typeof(JobTask))
            {
                var ret = nominalType;

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

                    ret = Type.GetType(value);

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

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

                bsonReader.ReturnToBookmark(bookmark);

                return ret;
            }
            else
            {
                return nominalType;
            }
        }
        public 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);
        }
예제 #19
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);
        }
예제 #20
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);
    }
예제 #21
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 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);
        }
        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());
        }
예제 #25
0
        internal static Type FindDocumentType(this IBsonReader reader, Type nominalType)
        {
            var bookmark   = reader.GetBookmark();
            var actualType = nominalType;

            reader.ReadStartDocument();

            if (reader.FindElement(Conventions.Type))
            {
                actualType = ReadActualType(reader, nominalType);
            }

            reader.ReturnToBookmark(bookmark);
            reader.ReadStartDocument();

            if (reader.FindElement(Conventions.TypeAlias))
            {
                actualType = ReadActualType(reader, nominalType);
            }

            reader.ReturnToBookmark(bookmark);
            return(actualType);
        }
예제 #26
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 Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            var bookmark = bsonReader.GetBookmark();
            bsonReader.ReadStartDocument();
            string typeValue = string.Empty;
            if (bsonReader.FindElement(ElementName))
                typeValue = bsonReader.ReadString();
            else
                throw new NotSupportedException();

            bsonReader.ReturnToBookmark(bookmark);
            var retr = Type.GetType(typeValue) ?? Type.GetType("ThreeOneThree.Proxima.Core.Entities." + typeValue);
            return retr;
        }
        public 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));
            }
        }
예제 #30
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);
        }
        public Type GetActualType(IBsonReader bsonReader, Type nominalType)
        {
            var bookmark = bsonReader.GetBookmark();

            bsonReader.ReadStartDocument();
            var t = nominalType;

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

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

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

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

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

            return nominalType;
        }
 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());
 }
예제 #39
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 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());
 }