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()); }
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); }
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; }
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)); }
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); }
/// <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); }
// 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)); }
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); }
/// <summary> /// Positions the reader to a string element by name. /// </summary> /// <param name="reader">The reader.</param> /// <param name="name">The name of the element.</param> /// <returns>True if the element was found.</returns> public static string FindStringElement(this IBsonReader reader, string name) { BsonType bsonType; while ((bsonType = reader.ReadBsonType()) != BsonType.EndOfDocument) { if (bsonType == BsonType.String) { var elementName = reader.ReadName(); if (elementName == name) { return(reader.ReadString()); } else { reader.SkipValue(); } } else { reader.SkipName(); reader.SkipValue(); } } return(null); }
/// <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); }
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); }
/// <summary> /// 安全地读入<c>null</c>类型的字段 /// </summary> /// <param name="bsonReader">Bson读取器</param> /// <param name="expected">字段名</param> /// <param name="read">字段名缓存</param> /// <returns>是否成功</returns> public static bool ReadNull(this IBsonReader bsonReader, string expected, ref string read) { if (!bsonReader.ReadName(expected, ref read)) { return(false); } bsonReader.ReadNull(); return(true); }
private static void VerifyName(IBsonReader reader, string expectedName) { var actualName = reader.ReadName(); if (actualName != expectedName) { var message = string.Format( "Expected element name to be '{0}', not '{1}'.", expectedName, actualName); throw new FormatException(message); } }
/// <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()); }
/// <summary> /// Positions the reader to an element by name. /// </summary> /// <param name="reader">The reader.</param> /// <param name="name">The name of the element.</param> /// <returns>True if the element was found.</returns> public static bool FindElement(this IBsonReader reader, string name) { while (reader.ReadBsonType() != BsonType.EndOfDocument) { var elementName = reader.ReadName(); if (elementName == name) { return(true); } reader.SkipValue(); } return(false); }
/// <summary> /// Reads a date & 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)); } }
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); }
/// <summary> /// 安全地读入指定字段的名称 /// </summary> /// <param name="bsonReader">Bson读取器</param> /// <param name="expected">字段名</param> /// <param name="read">字段名缓存</param> /// <returns>是否可以继续读入</returns> private static bool ReadName(this IBsonReader bsonReader, string expected, ref string read) { if (bsonReader.IsEndOfDocument()) { return(false); } read ??= bsonReader.ReadName(); if (read != expected) { return(false); } read = null; return(true); }
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()); }
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()); }
/// <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 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()); }
/// <summary> /// 做安全读入指定字段之前的准备工作 /// </summary> /// <param name="bsonReader">Bson读取器</param> /// <param name="expected">字段名</param> /// <param name="read">字段名缓存</param> /// <returns>是否可以继续读入</returns> private static bool ReadPrep(this IBsonReader bsonReader, string expected, ref string read) { if (!bsonReader.ReadName(expected, ref read)) { return(false); } switch (bsonReader.CurrentBsonType) { case BsonType.Null: bsonReader.ReadNull(); return(false); case BsonType.Undefined: bsonReader.ReadUndefined(); return(false); } return(true); }
/// <inheritdoc/> public Type GetActualType(IBsonReader bsonReader, Type nominalType) { ThrowIfNominalTypeIsIncorrect(nominalType); var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); Guid id = default; while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { switch (bsonReader.ReadName()) { case Type: var filterType = Enum.Parse <FilterType>(bsonReader.ReadString()); bsonReader.ReturnToBookmark(bookmark); return(filterType switch { FilterType.EventTypeId => typeof(TypePartitionFilterDefinition), FilterType.Remote => typeof(RemoteFilterDefinition), _ => throw new UnsupportedFilterTypeEnumValue(filterType, id) });
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); }
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 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()); }
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 string ReadName() { return(_reader.ReadName()); }
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 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()); }
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()); }
/// <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)); }