static object ReadObject(IBsonReader bsonReader) //_120509_173140 keep consistent { switch (bsonReader.GetCurrentBsonType()) { case BsonType.Array: return(ReadArray(bsonReader)); // replacement case BsonType.Binary: var binary = BsonSerializer.Deserialize <BsonValue>(bsonReader); return(BsonTypeMapper.MapToDotNetValue(binary) ?? binary); // byte[] or Guid else self case BsonType.Boolean: return(bsonReader.ReadBoolean()); case BsonType.DateTime: return(BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime())); case BsonType.Document: return(ReadCustomObject(bsonReader)); // replacement case BsonType.Double: return(bsonReader.ReadDouble()); case BsonType.Int32: return(bsonReader.ReadInt32()); case BsonType.Int64: return(bsonReader.ReadInt64()); case BsonType.Null: bsonReader.ReadNull(); return(null); case BsonType.ObjectId: return(bsonReader.ReadObjectId()); case BsonType.String: return(bsonReader.ReadString()); default: return(BsonSerializer.Deserialize <BsonValue>(bsonReader)); } }
/***************************************************/ public override object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { IBsonReader reader = context.Reader; BsonType currentBsonType = reader.GetCurrentBsonType(); switch (currentBsonType) { case BsonType.Array: if (context.DynamicArraySerializer != null) { return(context.DynamicArraySerializer.Deserialize(context)); } break; case BsonType.Binary: { BsonBinaryData bsonBinaryData = reader.ReadBinaryData(); BsonBinarySubType subType = bsonBinaryData.SubType; if (subType == BsonBinarySubType.UuidStandard || subType == BsonBinarySubType.UuidLegacy) { return(bsonBinaryData.ToGuid()); } break; } case BsonType.Boolean: return(reader.ReadBoolean()); case BsonType.DateTime: return(new BsonDateTime(reader.ReadDateTime()).ToUniversalTime()); case BsonType.Decimal128: return(reader.ReadDecimal128()); case BsonType.Document: return(DeserializeDiscriminatedValue(context, args)); case BsonType.Double: return(reader.ReadDouble()); case BsonType.Int32: return(reader.ReadInt32()); case BsonType.Int64: return(reader.ReadInt64()); case BsonType.Null: reader.ReadNull(); return(null); case BsonType.ObjectId: return(reader.ReadObjectId()); case BsonType.String: return(reader.ReadString()); } Engine.Reflection.Compute.RecordError($"ObjectSerializer does not support BSON type '{currentBsonType}'."); return(null); }
/// <summary> /// Deserializes an object from a binary source. /// </summary> /// <param name="Reader">Binary deserializer.</param> /// <param name="DataType">Optional datatype. If not provided, will be read from the binary source.</param> /// <param name="Embedded">If the object is embedded into another.</param> /// <returns>Deserialized object.</returns> public override object Deserialize(IBsonReader Reader, BsonType?DataType, bool Embedded) { if (!DataType.HasValue) { DataType = Reader.ReadBsonType(); } switch (DataType.Value) { case BsonType.Boolean: return(Reader.ReadBoolean() ? (long)1 : (long)0); case BsonType.Decimal128: return((long)Reader.ReadDecimal128()); case BsonType.Double: return((long)Reader.ReadDouble()); case BsonType.Int32: return((long)Reader.ReadInt32()); case BsonType.Int64: return((long)Reader.ReadInt64()); case BsonType.String: return(long.Parse(Reader.ReadString())); case BsonType.MinKey: Reader.ReadMinKey(); return(long.MinValue); case BsonType.MaxKey: Reader.ReadMaxKey(); return(long.MaxValue); case BsonType.Null: Reader.ReadNull(); return(null); default: throw new Exception("Expected an Int64 value."); } }
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), 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 }); // ReSharper disable once PossibleInvalidOperationException balance.Fund = bsonReader.ReadDouble("total", ref read) ?? bsonReader.ReadInt32("count", ref read).Value; bsonReader.ReadEndDocument(); return(balance); }
/// <summary> /// Deserializes an object from a binary source. /// </summary> /// <param name="Reader">Binary deserializer.</param> /// <param name="DataType">Optional datatype. If not provided, will be read from the binary source.</param> /// <param name="Embedded">If the object is embedded into another.</param> /// <returns>Deserialized object.</returns> public override object Deserialize(IBsonReader Reader, BsonType?DataType, bool Embedded) { if (!DataType.HasValue) { DataType = Reader.ReadBsonType(); } switch (DataType.Value) { case BsonType.Boolean: return(Reader.ReadBoolean()); case BsonType.Decimal128: return(Reader.ReadDecimal128() != 0); case BsonType.Double: return(Reader.ReadDouble() != 0); case BsonType.Int32: return(Reader.ReadInt32() != 0); case BsonType.Int64: return(Reader.ReadInt64() != 0); case BsonType.MinKey: Reader.ReadMinKey(); return(false); case BsonType.MaxKey: Reader.ReadMaxKey(); return(true); case BsonType.Null: Reader.ReadNull(); return(null); default: throw new Exception("Expected a nullable boolean value."); } }
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 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), Salvage = bsonReader.ReadDouble("salvage", 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), Method = bsonReader.ReadString("method", ref read) switch { "sl" => DepreciationMethod.StraightLine, "sy" => DepreciationMethod.SumOfTheYear, "dd" => DepreciationMethod.DoubleDeclineMethod, _ => DepreciationMethod.None, }, }; 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); }
protected override decimal readAmount(IBsonReader reader) { BsonMemberMap amountMap = _map.GetMemberMap(m => m.Amount); double amountRead = reader.ReadDouble(amountMap.ElementName); decimal amount = Convert.ToDecimal(amountRead); return(amount); }
object GetDeserializedValue(Type valueType, ref IBsonReader bsonReader) { var bsonType = bsonReader.CurrentBsonType; if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } if (valueType == typeof(Guid)) { var binaryData = bsonReader.ReadBinaryData(); return(binaryData.ToGuid()); } else if (valueType == typeof(double)) { return(bsonReader.ReadDouble()); } else if (valueType == typeof(float)) { return((float)bsonReader.ReadDouble()); } else if (valueType == typeof(int)) { return(bsonReader.ReadInt32()); } else if (valueType == typeof(long)) { return(bsonReader.ReadInt64()); } else if (valueType == typeof(bool)) { return(bsonReader.ReadBoolean()); } else if (valueType == typeof(string)) { return(bsonReader.ReadString()); } else if (valueType == typeof(decimal)) { return(decimal.Parse(bsonReader.ReadString(), CultureInfo.InvariantCulture)); } throw new FailedConceptSerialization($"Could not deserialize the concept value to '{valueType.FullName}'"); }
object GetDeserializedValue(Type valueType, ref IBsonReader bsonReader) { var bsonType = bsonReader.CurrentBsonType; if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } if (valueType == typeof(Guid)) { var binaryData = bsonReader.ReadBinaryData(); return(binaryData.ToGuid()); } else if (valueType == typeof(double)) { return(bsonReader.ReadDouble()); } else if (valueType == typeof(float)) { return((float)bsonReader.ReadDouble()); } else if (valueType == typeof(Int32)) { return(bsonReader.ReadInt32()); } else if (valueType == typeof(Int64)) { return(bsonReader.ReadInt64()); } else if (valueType == typeof(bool)) { return(bsonReader.ReadBoolean()); } else if (valueType == typeof(string)) { return(bsonReader.ReadString()); } else if (valueType == typeof(decimal)) { return(decimal.Parse(bsonReader.ReadString())); } throw new Exception(); }
private void DeserializeDataPointAttribute(string attr, IBsonReader reader, ref DataPoint dataPoint) { switch (attr) { case "Value": dataPoint.Value = reader.ReadDecimal128().ToDecimal(); break; case "Unit": if (reader.GetCurrentBsonType() == BsonType.Null) { reader.ReadNull(); dataPoint.Unit = null; } else { dataPoint.Unit = reader.ReadString(); } break; case "Precision": if (reader.GetCurrentBsonType() == BsonType.Null) { reader.ReadNull(); dataPoint.Precision = null; } dataPoint.Precision = reader.ReadDouble(); break; case "Accuracy": if (reader.GetCurrentBsonType() == BsonType.Null) { reader.ReadNull(); dataPoint.Accuracy = null; } dataPoint.Accuracy = reader.ReadDouble(); break; default: throw new DatabaseException("Unknown document attribute", "Measurements"); } }
private JToken GenerateJToken(IBsonReader reader, JToken parent) { switch (reader.CurrentBsonType) { case BsonType.Symbol: case BsonType.JavaScriptWithScope: case BsonType.JavaScript: case BsonType.ObjectId: case BsonType.RegularExpression: case BsonType.DateTime: case BsonType.Decimal128: case BsonType.MinKey: case BsonType.MaxKey: case BsonType.String: return(reader.ReadString()); case BsonType.Binary: return(reader.ReadBytes()); case BsonType.Undefined: reader.ReadUndefined(); return(JValue.CreateUndefined()); case BsonType.Boolean: return(reader.ReadBoolean()); case BsonType.Null: reader.ReadNull(); return(JValue.CreateNull()); case BsonType.Int32: return(reader.ReadInt32()); case BsonType.Int64: case BsonType.Timestamp: return(reader.ReadInt64()); case BsonType.Double: return(reader.ReadDouble()); case BsonType.Document: return(GenerateJObject(reader, parent)); case BsonType.Array: return(GenerateJArray(reader, parent)); case BsonType.EndOfDocument: break; default: break; } return(null); }
public void TestDouble() { var json = "1.5"; using (_bsonReader = new JsonReader(json)) { Assert.Equal(BsonType.Double, _bsonReader.ReadBsonType()); Assert.Equal(1.5, _bsonReader.ReadDouble()); Assert.Equal(BsonReaderState.Initial, _bsonReader.State); } Assert.Equal(json, BsonSerializer.Deserialize <double>(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); }
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 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 static object ReadObject(IBsonReader reader) { var bsonType = reader.CurrentBsonType; switch (bsonType) { case BsonType.String: return(reader.ReadString()); case BsonType.Double: return(reader.ReadDouble()); case BsonType.Int32: return(reader.ReadInt32()); default: var message = string.Format("Cannot provide value for type : {0}", bsonType); throw new Exception(message); } }
static object ReadObject(IBsonReader bsonReader) //_120509_173140 sync, test { switch (bsonReader.GetCurrentBsonType()) { case BsonType.Array: return(ReadArray(bsonReader)); // replacement case BsonType.Boolean: return(bsonReader.ReadBoolean()); case BsonType.DateTime: return(BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime())); case BsonType.Decimal128: return(Decimal128.ToDecimal(bsonReader.ReadDecimal128())); case BsonType.Document: return(ReadCustomObject(bsonReader)); // replacement case BsonType.Double: return(bsonReader.ReadDouble()); case BsonType.Int32: return(bsonReader.ReadInt32()); case BsonType.Int64: return(bsonReader.ReadInt64()); case BsonType.Null: bsonReader.ReadNull(); return(null); case BsonType.ObjectId: return(bsonReader.ReadObjectId()); case BsonType.String: return(bsonReader.ReadString()); case BsonType.Binary: var data = bsonReader.ReadBinaryData(); switch (data.SubType) { case BsonBinarySubType.UuidLegacy: case BsonBinarySubType.UuidStandard: return(data.ToGuid()); default: return(data); } default: return(BsonSerializer.Deserialize <BsonValue>(bsonReader)); } }
protected virtual decimal readAmount(IBsonReader reader) { BsonMemberMap amountMap = _map.GetMemberMap(m => m.Amount); reader.ReadName(amountMap.ElementName); decimal amount; // support old numeric representations BsonType type = reader.GetCurrentBsonType(); switch (type) { case BsonType.Double: { double amountRead = reader.ReadDouble(); amount = Convert.ToDecimal(amountRead); break; } case BsonType.Decimal128: { Decimal128 amountRead = reader.ReadDecimal128(); amount = Decimal128.ToDecimal(amountRead); break; } case BsonType.String: { string amountRead = reader.ReadString(); amount = decimal.Parse(amountRead, CultureInfo.InvariantCulture); break; } default: var message = $"Cannot convert a {type} to a Decimal."; throw new NotSupportedException(message); } return(amount); }
/// <summary> /// Reads a boolean value. /// </summary> /// <param name="Reader">Binary reader.</param> /// <param name="FieldDataType">Field data type.</param> /// <returns>Boolean value.</returns> /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception> public static bool ReadBoolean(IBsonReader Reader, BsonType FieldDataType) { switch (FieldDataType) { case BsonType.Boolean: return(Reader.ReadBoolean()); case BsonType.Decimal128: return(Reader.ReadDecimal128() != 0); case BsonType.Double: return(Reader.ReadDouble() != 0); case BsonType.Int32: return(Reader.ReadInt32() != 0); case BsonType.Int64: return(Reader.ReadInt64() != 0); case BsonType.MinKey: Reader.ReadMinKey(); return(false); case BsonType.MaxKey: Reader.ReadMaxKey(); return(true); default: throw new ArgumentException("Expected a boolean value, but was a " + FieldDataType.ToString() + ".", nameof(FieldDataType)); } }
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); }
internal static object Deserialize(IBsonReader reader) { switch (reader.GetCurrentBsonType()) { case BsonType.ObjectId: return(reader.ReadObjectId()); case BsonType.Boolean: return(reader.ReadBoolean()); case BsonType.DateTime: return(UnixTime.ToDateTime(reader.ReadDateTime())); case BsonType.Int32: return(reader.ReadInt32()); case BsonType.Binary: return(reader.ReadBytes()); case BsonType.Int64: return(reader.ReadInt64()); case BsonType.Double: return(reader.ReadDouble()); case BsonType.Null: reader.ReadNull(); return(null); case BsonType.String: return(reader.ReadString()); default: throw new InvalidOperationException( $"Cannot deserialize {reader.GetCurrentBsonType()} to native value."); } }
/// <summary> /// Deserializes an object from a binary source. /// </summary> /// <param name="Reader">Binary deserializer.</param> /// <param name="DataType">Optional datatype. If not provided, will be read from the binary source.</param> /// <param name="Embedded">If the object is embedded into another.</param> /// <returns>Deserialized object.</returns> public object Deserialize(IBsonReader Reader, BsonType?DataType, bool Embedded) { if (!DataType.HasValue) { DataType = Reader.ReadBsonType(); } switch (DataType.Value) { case BsonType.Boolean: return(new CaseInsensitiveString(Reader.ReadBoolean().ToString())); case BsonType.DateTime: return(new CaseInsensitiveString(ObjectSerializer.UnixEpoch.AddMilliseconds(Reader.ReadDateTime()).ToString())); case BsonType.Decimal128: return(new CaseInsensitiveString(Reader.ReadDecimal128().ToString())); case BsonType.Double: return(new CaseInsensitiveString(Reader.ReadDouble().ToString())); case BsonType.Int32: return(new CaseInsensitiveString(Reader.ReadInt32().ToString())); case BsonType.Int64: return(new CaseInsensitiveString(Reader.ReadInt64().ToString())); case BsonType.JavaScript: return(new CaseInsensitiveString(Reader.ReadJavaScript())); case BsonType.JavaScriptWithScope: return(new CaseInsensitiveString(Reader.ReadJavaScriptWithScope())); case BsonType.Null: Reader.ReadNull(); return(null); case BsonType.ObjectId: return(new CaseInsensitiveString(Reader.ReadObjectId().ToString())); case BsonType.String: return(new CaseInsensitiveString(Reader.ReadString())); case BsonType.Symbol: return(new CaseInsensitiveString(Reader.ReadSymbol())); default: throw new Exception("Expected a case-insensitive string value."); } }
public override TimeSpan Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { IBsonReader reader = context.Reader; BsonType bsonType = reader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Null: reader.ReadNull(); return(TimeSpan.Zero); case BsonType.Int32: return(TimeSpan.FromMilliseconds((double)reader.ReadInt32())); case BsonType.Int64: return(TimeSpan.FromMilliseconds((double)reader.ReadInt64())); case BsonType.Double: return(TimeSpan.FromMilliseconds(reader.ReadDouble())); default: throw base.CreateCannotDeserializeFromBsonTypeException(bsonType); } }
/// <summary> /// Reads a 32-bit integer value. /// </summary> /// <param name="Reader">Binary reader.</param> /// <param name="FieldDataType">Field data type.</param> /// <returns>32-bit integer value.</returns> /// <exception cref="ArgumentException">If the <paramref name="FieldDataType"/> was invalid.</exception> public static int ReadInt32(IBsonReader Reader, BsonType FieldDataType) { switch (FieldDataType) { case BsonType.Boolean: return(Reader.ReadBoolean() ? (int)1 : (int)0); case BsonType.Decimal128: return((int)Reader.ReadDecimal128()); case BsonType.Double: return((int)Reader.ReadDouble()); case BsonType.Int32: return((int)Reader.ReadInt32()); case BsonType.Int64: return((int)Reader.ReadInt64()); case BsonType.String: return(int.Parse(Reader.ReadString())); case BsonType.MinKey: Reader.ReadMinKey(); return(int.MinValue); case BsonType.MaxKey: Reader.ReadMaxKey(); return(int.MaxValue); default: throw new ArgumentException("Expected a 32-bit integer value, but was a " + FieldDataType.ToString() + ".", nameof(FieldDataType)); } }
/// <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)); }
/// <summary> /// Deserializes an object from a binary source. /// </summary> /// <param name="Reader">Binary deserializer.</param> /// <param name="DataType">Optional datatype. If not provided, will be read from the binary source.</param> /// <param name="Embedded">If the object is embedded into another.</param> /// <returns>Deserialized object.</returns> public override object Deserialize(IBsonReader Reader, BsonType?DataType, bool Embedded) { if (!DataType.HasValue) { DataType = Reader.ReadBsonType(); } switch (DataType.Value) { case BsonType.Boolean: return(this.ToNullable(Enum.ToObject(this.enumType, Reader.ReadBoolean() ? 1 : 0))); case BsonType.Decimal128: return(this.ToNullable(Enum.ToObject(this.enumType, (int)Reader.ReadDecimal128()))); case BsonType.Double: return(this.ToNullable(Enum.ToObject(this.enumType, Reader.ReadDouble()))); case BsonType.Int32: return(this.ToNullable(Enum.ToObject(this.enumType, Reader.ReadInt32()))); case BsonType.Int64: return(this.ToNullable(Enum.ToObject(this.enumType, Reader.ReadInt64()))); case BsonType.String: return(this.ToNullable(Enum.Parse(this.enumType, Reader.ReadString()))); case BsonType.Null: Reader.ReadNull(); return(null); default: throw new Exception("Expected an enum value."); } }
/// <summary> /// Reads a BSON Double element from the reader. /// </summary> /// <param name="reader">The reader.</param> /// <param name="name">The name of the element.</param> /// <returns>A Double.</returns> public static double ReadDouble(this IBsonReader reader, string name) { VerifyName(reader, name); return(reader.ReadDouble()); }
// private methods private void ReadValue() { object jsonDotNetValue; switch (_wrappedReader.GetCurrentBsonType()) { case BsonType.Array: _wrappedReader.ReadStartArray(); SetCurrentToken(Newtonsoft.Json.JsonToken.StartArray); return; case BsonType.Binary: var bsonBinaryData = _wrappedReader.ReadBinaryData(); switch (bsonBinaryData.SubType) { case BsonBinarySubType.UuidLegacy: var guidRepresentation = GuidRepresentation.Unspecified; var bsonReader = _wrappedReader as BsonReader; if (bsonReader != null) { guidRepresentation = bsonReader.Settings.GuidRepresentation; } jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, guidRepresentation); break; case BsonBinarySubType.UuidStandard: jsonDotNetValue = GuidConverter.FromBytes(bsonBinaryData.Bytes, GuidRepresentation.Standard); break; default: jsonDotNetValue = bsonBinaryData.Bytes; break; } SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, jsonDotNetValue, bsonBinaryData); return; case BsonType.Boolean: var booleanValue = _wrappedReader.ReadBoolean(); SetCurrentToken(Newtonsoft.Json.JsonToken.Boolean, booleanValue, (BsonBoolean)booleanValue); return; case BsonType.DateTime: var bsonDateTime = new BsonDateTime(_wrappedReader.ReadDateTime()); if (bsonDateTime.IsValidDateTime) { jsonDotNetValue = bsonDateTime.ToUniversalTime(); } else { jsonDotNetValue = bsonDateTime.MillisecondsSinceEpoch; } SetCurrentToken(Newtonsoft.Json.JsonToken.Date, jsonDotNetValue, bsonDateTime); return; case BsonType.Document: _wrappedReader.ReadStartDocument(); SetCurrentToken(Newtonsoft.Json.JsonToken.StartObject); return; case BsonType.Double: var bsonDouble = new BsonDouble(_wrappedReader.ReadDouble()); switch (FloatParseHandling) { case Newtonsoft.Json.FloatParseHandling.Decimal: jsonDotNetValue = Convert.ToDecimal(bsonDouble); break; case Newtonsoft.Json.FloatParseHandling.Double: jsonDotNetValue = bsonDouble.Value; break; default: throw new NotSupportedException(string.Format("Unexpected FloatParseHandling value: {0}.", FloatParseHandling)); } SetCurrentToken(Newtonsoft.Json.JsonToken.Float, jsonDotNetValue, bsonDouble); return; case BsonType.Int32: var bsonInt32 = (BsonInt32)_wrappedReader.ReadInt32(); SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, (long)bsonInt32.Value, bsonInt32); return; case BsonType.Int64: var bsonInt64 = (BsonInt64)_wrappedReader.ReadInt64(); SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonInt64.Value, bsonInt64); return; case BsonType.JavaScript: { var code = _wrappedReader.ReadJavaScript(); var bsonJavaScript = new BsonJavaScript(code); SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScript); } return; case BsonType.JavaScriptWithScope: { var code = _wrappedReader.ReadJavaScriptWithScope(); var context = BsonDeserializationContext.CreateRoot(_wrappedReader); var scope = BsonDocumentSerializer.Instance.Deserialize <BsonDocument>(context); var bsonJavaScriptWithScope = new BsonJavaScriptWithScope(code, scope); SetCurrentToken(Newtonsoft.Json.JsonToken.String, code, bsonJavaScriptWithScope); } return; case BsonType.MaxKey: _wrappedReader.ReadMaxKey(); SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMaxKey.Value); return; case BsonType.MinKey: _wrappedReader.ReadMinKey(); SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonMinKey.Value); return; case BsonType.Null: _wrappedReader.ReadNull(); SetCurrentToken(Newtonsoft.Json.JsonToken.Null, null, BsonNull.Value); return; case BsonType.ObjectId: var bsonObjectId = new BsonObjectId(_wrappedReader.ReadObjectId()); SetCurrentToken(Newtonsoft.Json.JsonToken.Bytes, bsonObjectId.Value.ToByteArray(), bsonObjectId); return; case BsonType.RegularExpression: var bsonRegularExpression = _wrappedReader.ReadRegularExpression(); var pattern = bsonRegularExpression.Pattern; var options = bsonRegularExpression.Options; jsonDotNetValue = "/" + pattern.Replace("/", "\\/") + "/" + options; SetCurrentToken(Newtonsoft.Json.JsonToken.String, jsonDotNetValue, bsonRegularExpression); return; case BsonType.String: var stringValue = _wrappedReader.ReadString(); SetCurrentToken(Newtonsoft.Json.JsonToken.String, stringValue, (BsonString)stringValue); return; case BsonType.Symbol: var bsonSymbol = BsonSymbolTable.Lookup(_wrappedReader.ReadSymbol()); SetCurrentToken(Newtonsoft.Json.JsonToken.String, bsonSymbol.Name, bsonSymbol); return; case BsonType.Timestamp: var bsonTimestamp = new BsonTimestamp(_wrappedReader.ReadTimestamp()); SetCurrentToken(Newtonsoft.Json.JsonToken.Integer, bsonTimestamp.Value, bsonTimestamp); return; case BsonType.Undefined: _wrappedReader.ReadUndefined(); SetCurrentToken(Newtonsoft.Json.JsonToken.Undefined, null, BsonUndefined.Value); return; default: var message = string.Format("Unexpected BsonType: {0}.", _wrappedReader.GetCurrentBsonType()); throw new Newtonsoft.Json.JsonReaderException(message); } }
private object ReadValue(IBsonReader reader) { var type = reader.ReadBsonType(); switch (type) { case BsonType.EndOfDocument: break; case BsonType.Double: return(reader.ReadDouble()); case BsonType.String: return(reader.ReadString()); case BsonType.Document: return(EvaluateAsDocument(reader)); case BsonType.Array: break; case BsonType.Binary: break; case BsonType.Undefined: break; case BsonType.ObjectId: break; case BsonType.Boolean: break; case BsonType.DateTime: return(reader.ReadDateTime()); case BsonType.Null: return(null); case BsonType.RegularExpression: break; case BsonType.JavaScript: break; case BsonType.Symbol: break; case BsonType.JavaScriptWithScope: break; case BsonType.Int32: return(reader.ReadInt32()); case BsonType.Timestamp: break; case BsonType.Int64: return(reader.ReadInt64()); case BsonType.Decimal128: break; case BsonType.MinKey: break; case BsonType.MaxKey: break; default: break; } return(null); }
public void TestDouble() { var json = "1.5"; using (_bsonReader = new JsonReader(json)) { Assert.Equal(BsonType.Double, _bsonReader.ReadBsonType()); Assert.Equal(1.5, _bsonReader.ReadDouble()); Assert.Equal(BsonReaderState.Initial, _bsonReader.State); } Assert.Equal(json, BsonSerializer.Deserialize<double>(json).ToJson()); }