// public methods /// <inheritdoc/> public override object ReadJson(Newtonsoft.Json.JsonReader reader, Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { var adapter = reader as BsonReaderAdapter; if (adapter != null && adapter.BsonValue != null && adapter.BsonValue.BsonType == BsonType.Symbol) { return((BsonSymbol)adapter.BsonValue); } switch (reader.TokenType) { case Newtonsoft.Json.JsonToken.Null: return(null); case Newtonsoft.Json.JsonToken.String: return(BsonSymbolTable.Lookup((string)reader.Value)); case Newtonsoft.Json.JsonToken.StartObject: return(ReadExtendedJson(reader)); default: var message = string.Format("Error reading BsonSymbol. Unexpected token: {0}.", reader.TokenType); throw new Newtonsoft.Json.JsonReaderException(message); } }
public void TestBsonSymbolEquals() { var a = BsonSymbolTable.Lookup("symbol 1"); var b = BsonSymbolTable.Lookup("symbol 1"); var c = BsonSymbolTable.Lookup("symbol 2"); var n = (BsonString)null; Assert.IsTrue(object.Equals(a, b)); Assert.IsFalse(object.Equals(a, c)); Assert.IsFalse(object.Equals(a, BsonNull.Value)); Assert.IsFalse(a.Equals(n)); Assert.IsFalse(a.Equals(null)); Assert.IsTrue(a == b); Assert.IsFalse(a == c); Assert.IsFalse(a == BsonNull.Value); Assert.IsFalse(a == null); Assert.IsFalse(null == a); Assert.IsTrue(n == null); Assert.IsTrue(null == n); Assert.IsFalse(a != b); Assert.IsTrue(a != c); Assert.IsTrue(a != BsonNull.Value); Assert.IsTrue(a != null); Assert.IsTrue(null != a); Assert.IsFalse(n != null); Assert.IsFalse(null != n); }
public void TestTryMapToBsonValueWithBsonValues() { // test all the BsonValue subclasses because we removed them from the __fromMappings table var testValues = new BsonValue[] { new BsonArray(), new BsonBinaryData(new byte[0]), BsonBoolean.True, new BsonDateTime(DateTime.UtcNow), new BsonDocument("x", 1), new BsonDouble(1.0), new BsonInt32(1), new BsonInt64(1), new BsonJavaScript("code"), new BsonJavaScriptWithScope("code", new BsonDocument("x", 1)), BsonMaxKey.Value, BsonMinKey.Value, BsonNull.Value, new BsonObjectId(ObjectId.GenerateNewId()), new BsonRegularExpression("pattern"), new BsonString("abc"), BsonSymbolTable.Lookup("xyz"), new BsonTimestamp(0), BsonUndefined.Value }; foreach (var testValue in testValues) { BsonValue bsonValue; var ok = BsonTypeMapper.TryMapToBsonValue(testValue, out bsonValue); Assert.Equal(true, ok); Assert.Same(testValue, bsonValue); } }
public void TestBsonSymbolEquals() { BsonSymbol lhs = BsonSymbolTable.Lookup("name"); BsonSymbol rhs = BsonSymbolTable.Lookup("name"); Assert.Same(lhs, rhs); Assert.Equal(lhs, rhs); Assert.Equal(lhs.GetHashCode(), rhs.GetHashCode()); }
public void ReadJson_should_return_expected_result_when_using_wrapped_json_reader(string json, string nullableName) { var subject = new BsonSymbolConverter(); var expectedResult = nullableName == null ? null : BsonSymbolTable.Lookup(nullableName); var result = ReadJsonUsingWrappedJsonReader <BsonSymbol>(subject, json); result.Should().BeSameAs(expectedResult); }
public void ReadJson_should_return_expected_result_when_using_native_bson_reader(string json, string nullableName) { var subject = new BsonSymbolConverter(); var expectedResult = nullableName == null ? null : BsonSymbolTable.Lookup(nullableName); var result = ReadJsonUsingNativeBsonReader <BsonSymbol>(subject, ToBson(json), mustBeNested: true); result.Should().BeSameAs(expectedResult); }
public void WriteJson_should_have_expected_result_when_using_wrapped_json_writer(string nullableName, string expectedResult) { var subject = new BsonSymbolConverter(); var value = nullableName == null ? null : BsonSymbolTable.Lookup(nullableName); var result = WriteJsonUsingWrappedJsonWriter(subject, value); result.Should().Be(expectedResult); }
[TestCase("def", "{ x : { $$symbol : \"def\" } }")] // note: Json.NET can't write a BsonSymbol public void WriteJson_should_have_expected_result_when_using_native_bson_writer(string nullableName, string expectedResult) { var subject = new BsonSymbolConverter(); var value = nullableName == null ? null : BsonSymbolTable.Lookup(nullableName); var result = WriteJsonUsingNativeBsonWriter(subject, value, mustBeNested: true); result.Should().Equal(ToBson(expectedResult)); }
// private methods private BsonSymbol ReadExtendedJson(Newtonsoft.Json.JsonReader reader) { ReadExpectedPropertyName(reader, "$symbol"); var name = ReadStringValue(reader); ReadEndObject(reader); return(BsonSymbolTable.Lookup(name)); }
public void TestAsBsonSymbol() { BsonValue v = BsonSymbolTable.Lookup("name"); BsonValue s = ""; var sym = v.AsBsonSymbol; Assert.AreEqual("name", sym.Name); Assert.Throws <InvalidCastException>(() => { var x = s.AsBsonSymbol; }); }
public void TestBsonSymbolEqualsNotNull() { var query = Query <C> .Where(c => c.Symbol == BsonSymbolTable.Lookup("abc")); var json = query.ToJson(); var expected = "{ 'Symbol' : { '$symbol' : 'abc' } }".Replace("'", "\""); Assert.Equal(expected, json); }
public void TestMapBsonSymbol() { var value = BsonSymbolTable.Lookup("symbol"); var bsonValue = (BsonSymbol)BsonTypeMapper.MapToBsonValue(value); Assert.AreSame(value, bsonValue); var bsonSymbol = (BsonSymbol)BsonTypeMapper.MapToBsonValue(value, BsonType.Symbol); Assert.AreSame(value, bsonSymbol); }
public void TestSymbol() { var document = new BsonDocument { { "symbol", BsonSymbolTable.Lookup("name") } }; string expected = "{ \"symbol\" : { \"$symbol\" : \"name\" } }"; string actual = document.ToJson(); Assert.Equal(expected, actual); }
public void TestSymbol() { var document = new BsonDocument { { "symbol", BsonSymbolTable.Lookup("name") } }; using (var bsonReader = BsonReader.Create(document)) { var rehydrated = (BsonDocument)BsonDocumentSerializer.Instance.Deserialize(bsonReader, typeof(BsonDocument), null); Assert.IsTrue(document.Equals(rehydrated)); } }
public void TestSymbol() { var document = new BsonDocument { { "symbol", BsonSymbolTable.Lookup("name") } }; using (var bsonReader = new BsonDocumentReader(document)) { var rehydrated = DeserializeBsonDocument(bsonReader); Assert.True(document.Equals(rehydrated)); } }
/// <summary> /// Writes a BSON Symbol to the writer. /// </summary> /// <param name="value">The symbol.</param> public override void WriteSymbol(string value) { if (Disposed) { throw new ObjectDisposedException("BsonDocumentWriter"); } if (State != BsonWriterState.Value) { ThrowInvalidState("WriteSymbol", BsonWriterState.Value); } WriteValue(BsonSymbolTable.Lookup(value)); State = GetNextState(); }
public async Task ReadDocumentWithNonJsonProperties_AllFieldsRead() { var jScriptValue = "var i=0;"; var longValue = 9223372036854775797L; var byteArrayValue = new byte[] { 0xef, 0x23, 0x10, 0xaa }; var guidValue = Guid.NewGuid(); var symbolValue = "testSymbol"; await Collection.InsertOneAsync(new BsonDocument { { "script", new BsonJavaScript(jScriptValue) }, { "regex", new BsonRegularExpression("ab*", "si") }, { "maxKey", BsonMaxKey.Value }, { "longVal", new BsonInt64(9223372036854775797L) }, { "byteArr", byteArrayValue }, { "guid", guidValue }, { "scopedJscript", new BsonJavaScriptWithScope(jScriptValue, new BsonDocument { { "i", 1 } }) }, { "timestamp", new BsonTimestamp(1424288963, 32) }, { "symbol", BsonSymbolTable.Lookup(symbolValue) } }); using (var adapter = await new MongoDbSourceAdapterFactory() .CreateAsync(Configuration, DataTransferContextMock.Instance, CancellationToken.None)) { var dataItem = await adapter.ReadNextAsync(ReadOutputByRef.None, CancellationToken.None); Assert.AreEqual(jScriptValue, dataItem.GetValue("script"), TestResources.InvalidPropertyValueFormat, "script"); Assert.AreEqual("/ab*/si", dataItem.GetValue("regex"), TestResources.InvalidPropertyValueFormat, "regex"); Assert.IsNull(dataItem.GetValue("maxKey"), TestResources.InvalidPropertyValueFormat, "maxKey"); Assert.AreEqual(longValue, dataItem.GetValue("longVal"), TestResources.InvalidPropertyValueFormat, "longVal"); CollectionAssert.AreEqual(byteArrayValue, (byte[])dataItem.GetValue("byteArr"), TestResources.InvalidPropertyValueFormat, "longVal"); Assert.AreEqual(guidValue, dataItem.GetValue("guid"), TestResources.InvalidPropertyValueFormat, "guid"); var scopedJsReader = dataItem.GetValue("scopedJscript") as IDataItem; Assert.IsNotNull(scopedJsReader, TestResources.InvalidPropertyValueFormat, "scopedJscript"); Assert.AreEqual(jScriptValue, scopedJsReader.GetValue("code"), TestResources.InvalidPropertyValueFormat, "code"); var scopedJsScopeReader = scopedJsReader.GetValue("scope") as IDataItem; Assert.IsNotNull(scopedJsScopeReader, TestResources.InvalidPropertyValueFormat, "scope"); Assert.AreEqual(1, scopedJsScopeReader.GetValue("i"), TestResources.InvalidPropertyValueFormat, "i"); Assert.AreEqual(new DateTime(635598857630000032), dataItem.GetValue("timestamp"), TestResources.InvalidPropertyValueFormat, "timestamp"); Assert.AreEqual(symbolValue, dataItem.GetValue("symbol"), TestResources.InvalidPropertyValueFormat, "symbol"); } }
public void TestMapString() { var value = "hello"; var bsonValue = (BsonString)BsonTypeMapper.MapToBsonValue(value); Assert.Equal(value, bsonValue.Value); var bsonBoolean = (BsonBoolean)BsonTypeMapper.MapToBsonValue("1", BsonType.Boolean); Assert.Equal(true, bsonBoolean.Value); var bsonDateTime = (BsonDateTime)BsonTypeMapper.MapToBsonValue("2010-01-02", BsonType.DateTime); Assert.Equal(new DateTime(2010, 1, 2), bsonDateTime.ToUniversalTime()); var bsonDecimal128 = (BsonDecimal128)BsonTypeMapper.MapToBsonValue("1.2", BsonType.Decimal128); Assert.Equal((Decimal128)1.2M, bsonDecimal128.Value); var bsonDouble = (BsonDouble)BsonTypeMapper.MapToBsonValue("1.2", BsonType.Double); Assert.Equal(1.2, bsonDouble.Value); var bsonInt32 = (BsonInt32)BsonTypeMapper.MapToBsonValue("1", BsonType.Int32); Assert.Equal(1, bsonInt32.Value); var bsonInt64 = (BsonInt64)BsonTypeMapper.MapToBsonValue("1", BsonType.Int64); Assert.Equal(1L, bsonInt64.Value); var bsonJavaScript = (BsonJavaScript)BsonTypeMapper.MapToBsonValue("code", BsonType.JavaScript); Assert.Equal("code", bsonJavaScript.Code); var bsonJavaScriptWithScope = (BsonJavaScriptWithScope)BsonTypeMapper.MapToBsonValue("code", BsonType.JavaScriptWithScope); Assert.Equal("code", bsonJavaScriptWithScope.Code); Assert.Equal(0, bsonJavaScriptWithScope.Scope.ElementCount); var objectId = ObjectId.GenerateNewId(); var bsonObjectId = (BsonObjectId)BsonTypeMapper.MapToBsonValue(objectId.ToString(), BsonType.ObjectId); Assert.Equal(objectId, bsonObjectId.Value); var bsonRegularExpression = (BsonRegularExpression)BsonTypeMapper.MapToBsonValue(new Regex("pattern"), BsonType.RegularExpression); Assert.Equal("pattern", bsonRegularExpression.Pattern); Assert.Equal("", bsonRegularExpression.Options); var bsonString = (BsonString)BsonTypeMapper.MapToBsonValue(value, BsonType.String); Assert.Equal(value, bsonString.Value); var bsonSymbol = (BsonSymbol)BsonTypeMapper.MapToBsonValue("symbol", BsonType.Symbol); Assert.Same(BsonSymbolTable.Lookup("symbol"), bsonSymbol); var bsonTimestamp = (BsonTimestamp)BsonTypeMapper.MapToBsonValue("1", BsonType.Timestamp); Assert.Equal(1L, bsonTimestamp.Value); }
public void TestBsonSymbol() { var value = BsonSymbolTable.Lookup("name"); Assert.Throws <InvalidCastException>(() => Convert.ToBoolean(value)); Assert.Throws <InvalidCastException>(() => Convert.ToByte(value)); Assert.Throws <InvalidCastException>(() => Convert.ToChar(value)); Assert.Throws <InvalidCastException>(() => Convert.ToDateTime(value)); Assert.Throws <InvalidCastException>(() => Convert.ToDecimal(value)); Assert.Throws <InvalidCastException>(() => Convert.ToDouble(value)); Assert.Throws <InvalidCastException>(() => Convert.ToInt16(value)); Assert.Throws <InvalidCastException>(() => Convert.ToInt32(value)); Assert.Throws <InvalidCastException>(() => Convert.ToInt64(value)); Assert.Throws <InvalidCastException>(() => Convert.ToSByte(value)); Assert.Throws <InvalidCastException>(() => Convert.ToSingle(value)); Assert.Throws <InvalidCastException>(() => Convert.ToString(value)); Assert.Throws <InvalidCastException>(() => Convert.ToUInt16(value)); Assert.Throws <InvalidCastException>(() => Convert.ToUInt32(value)); Assert.Throws <InvalidCastException>(() => Convert.ToUInt64(value)); }
// public methods /// <summary> /// Deserializes an object from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the object.</param> /// <param name="actualType">The actual type of the object.</param> /// <param name="options">The serialization options.</param> /// <returns>An object.</returns> public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { VerifyTypes(nominalType, actualType, typeof(BsonSymbol)); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Symbol: return(BsonSymbolTable.Lookup(bsonReader.ReadSymbol())); default: var message = string.Format("Cannot deserialize BsonSymbol from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
// 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 BsonValue ParseExtendedJson(BsonDocument document) { if (document.ElementCount > 0) { switch (document.GetElement(0).Name) { case "$binary": if (document.ElementCount == 2 && document.GetElement(1).Name == "$type") { var bytes = Convert.FromBase64String(document[0].AsString); var subType = (BsonBinarySubType)(int)BsonUtils.ParseHexString(document[1].AsString)[0]; return(new BsonBinaryData(bytes, subType)); } break; case "$code": if (document.ElementCount == 1) { var code = document[0].AsString; return(new BsonJavaScript(code)); } else if (document.ElementCount == 2 && document.GetElement(1).Name == "$scope") { var code = document[0].AsString; var scope = document[1].AsBsonDocument; return(new BsonJavaScriptWithScope(code, scope)); } break; case "$date": if (document.ElementCount == 1) { switch (document[0].BsonType) { case BsonType.DateTime: return(document[0].AsBsonDateTime); case BsonType.Document: { var dateDocument = document[0].AsBsonDocument; if (dateDocument.ElementCount == 1 && dateDocument.GetElement(0).Name == "$numberLong") { var formattedString = dateDocument[0].AsString; var millisecondsSinceEpoch = long.Parse(formattedString, NumberFormatInfo.InvariantInfo); return(new BsonDateTime(millisecondsSinceEpoch)); } } break; case BsonType.Double: case BsonType.Int32: case BsonType.Int64: { var millisecondsSinceEpoch = document[0].ToInt64(); return(new BsonDateTime(millisecondsSinceEpoch)); } case BsonType.String: { var formattedString = document[0].AsString; var dateTime = DateTime.Parse(formattedString, DateTimeFormatInfo.InvariantInfo); return(new BsonDateTime(dateTime)); } } } break; case "$maxKey": if (document.ElementCount == 1) { return(BsonMaxKey.Value); } break; case "$minKey": if (document.ElementCount == 1) { return(BsonMinKey.Value); } break; case "$oid": if (document.ElementCount == 1) { var hexBytes = document[0].AsString; var objectId = ObjectId.Parse(hexBytes); return(new BsonObjectId(objectId)); } break; case "$regex": if (document.ElementCount == 2 && document.GetElement(1).Name == "$options") { var pattern = document[0].AsString; var options = document[1].AsString; return(new BsonRegularExpression(pattern, options)); } break; case "$symbol": if (document.ElementCount == 1) { var name = document[0].AsString; return(BsonSymbolTable.Lookup(name)); } break; case "$timestamp": if (document.ElementCount == 1) { var timestampDocument = document[0].AsBsonDocument; var timestamp = timestampDocument[0].ToInt32(); var increment = timestampDocument[1].ToInt32(); return(new BsonTimestamp(timestamp, increment)); } break; } } return(document); }
// protected methods /// <summary> /// Deserializes a value. /// </summary> /// <param name="context">The deserialization context.</param> /// <param name="args">The deserialization args.</param> /// <returns>An object.</returns> protected override BsonSymbol DeserializeValue(BsonDeserializationContext context, BsonDeserializationArgs args) { var bsonReader = context.Reader; return(BsonSymbolTable.Lookup(bsonReader.ReadSymbol())); }
public void TestExtraElementsOfAllTypes( [ClassValues(typeof(GuidModeValues))] GuidMode mode) { mode.Set(); #pragma warning disable 618 var json = "{ '_id' : 1, 'A' : 2, 'B' : 3, #X }"; var extraElements = new List <string[]> { new string[] { "XArray", "[1, 2.0]" }, new string[] { "XBinary", "HexData(2, '1234')" }, new string[] { "XBoolean", "true" }, new string[] { "XByteArray", "HexData(0, '1234')" }, new string[] { "XDateTime", "ISODate('2012-03-16T11:19:00Z')" }, new string[] { "XDocument", "{ 'a' : 1 }" }, new string[] { "XDouble", "1.0" }, new string[] { "XInt32", "1" }, new string[] { "XInt64", "NumberLong(1)" }, new string[] { "XJavaScript", "{ '$code' : 'abc' }" }, new string[] { "XJavaScriptWithScope", "{ '$code' : 'abc', '$scope' : { 'x' : 1 } }" }, new string[] { "XMaxKey", "MaxKey" }, new string[] { "XMinKey", "MinKey" }, new string[] { "XNull", "null" }, new string[] { "XObjectId", "ObjectId('00112233445566778899aabb')" }, new string[] { "XRegularExpression", "/abc/" }, new string[] { "XString", "'abc'" }, new string[] { "XSymbol", "{ '$symbol' : 'abc' }" }, new string[] { "XTimestamp", "{ '$timestamp' : NumberLong(1234) }" }, new string[] { "XUndefined", "undefined" }, }; var hasXGuidLegacy = false; var hasXGuidStandard = false; if (BsonDefaults.GuidRepresentationMode == GuidRepresentationMode.V2) { switch (BsonDefaults.GuidRepresentation) { case GuidRepresentation.CSharpLegacy: case GuidRepresentation.JavaLegacy: case GuidRepresentation.PythonLegacy: extraElements.Add(new string[] { "XGuidLegacy", "HexData(3, '00112233445566778899aabbccddeeff')" }); hasXGuidLegacy = true; break; case GuidRepresentation.Standard: extraElements.Add(new string[] { "XGuidStandard", "HexData(4, '00112233445566778899aabbccddeeff')" }); hasXGuidStandard = true; break; } } var extraElementsRepresentation = string.Join(", ", extraElements.Select(e => string.Format("'{0}' : {1}", e[0], e[1])).ToArray()); json = json.Replace("#X", extraElementsRepresentation).Replace("'", "\""); var c = BsonSerializer.Deserialize <C>(new JsonReader(json, new JsonReaderSettings())); // round trip it both ways before checking individual values json = c.ToJson(new JsonWriterSettings()); c = BsonSerializer.Deserialize <C>(new JsonReader(json, new JsonReaderSettings())); Assert.IsType <List <object> >(c.X["XArray"]); Assert.IsType <BsonBinaryData>(c.X["XBinary"]); Assert.IsType <bool>(c.X["XBoolean"]); Assert.IsType <byte[]>(c.X["XByteArray"]); Assert.IsType <DateTime>(c.X["XDateTime"]); Assert.IsType <Dictionary <string, object> >(c.X["XDocument"]); Assert.IsType <double>(c.X["XDouble"]); if (hasXGuidLegacy) { Assert.IsType <Guid>(c.X["XGuidLegacy"]); } if (hasXGuidStandard) { Assert.IsType <Guid>(c.X["XGuidStandard"]); } Assert.IsType <int>(c.X["XInt32"]); Assert.IsType <long>(c.X["XInt64"]); Assert.IsType <BsonJavaScript>(c.X["XJavaScript"]); Assert.IsType <BsonJavaScriptWithScope>(c.X["XJavaScriptWithScope"]); Assert.IsType <BsonMaxKey>(c.X["XMaxKey"]); Assert.IsType <BsonMinKey>(c.X["XMinKey"]); Assert.Null(c.X["XNull"]); Assert.IsType <ObjectId>(c.X["XObjectId"]); Assert.IsType <BsonRegularExpression>(c.X["XRegularExpression"]); Assert.IsType <string>(c.X["XString"]); Assert.IsType <BsonSymbol>(c.X["XSymbol"]); Assert.IsType <BsonTimestamp>(c.X["XTimestamp"]); Assert.IsType <BsonUndefined>(c.X["XUndefined"]); Assert.Equal(extraElements.Count, c.X.Count); Assert.True(new object[] { 1, 2.0 }.SequenceEqual((List <object>)c.X["XArray"])); Assert.Equal(BsonBinarySubType.OldBinary, ((BsonBinaryData)c.X["XBinary"]).SubType); Assert.True(new byte[] { 0x12, 0x34 }.SequenceEqual(((BsonBinaryData)c.X["XBinary"]).Bytes)); Assert.Equal(true, c.X["XBoolean"]); Assert.True(new byte[] { 0x12, 0x34 }.SequenceEqual((byte[])c.X["XByteArray"])); Assert.Equal(new DateTime(2012, 3, 16, 11, 19, 0, DateTimeKind.Utc), c.X["XDateTime"]); Assert.Equal(1, ((IDictionary <string, object>)c.X["XDocument"]).Count); Assert.Equal(1, ((IDictionary <string, object>)c.X["XDocument"])["a"]); Assert.Equal(1.0, c.X["XDouble"]); if (hasXGuidLegacy) { var expectedLegacyGuid = Guid.Empty; switch (BsonDefaults.GuidRepresentation) { case GuidRepresentation.CSharpLegacy: expectedLegacyGuid = new Guid("33221100554477668899aabbccddeeff"); break; case GuidRepresentation.JavaLegacy: expectedLegacyGuid = new Guid("7766554433221100ffeeddccbbaa9988"); break; case GuidRepresentation.PythonLegacy: expectedLegacyGuid = new Guid("00112233445566778899aabbccddeeff"); break; } Assert.Equal(expectedLegacyGuid, c.X["XGuidLegacy"]); } if (hasXGuidStandard) { Assert.Equal(new Guid("00112233-4455-6677-8899-aabbccddeeff"), c.X["XGuidStandard"]); } Assert.Equal(1, c.X["XInt32"]); Assert.Equal(1, c.X["XInt32"]); Assert.Equal(1L, c.X["XInt64"]); Assert.Equal("abc", ((BsonJavaScript)c.X["XJavaScript"]).Code); Assert.Equal("abc", ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Code); Assert.Equal(1, ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Scope.ElementCount); Assert.Equal(new BsonInt32(1), ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Scope["x"]); Assert.Same(BsonMaxKey.Value, c.X["XMaxKey"]); Assert.Same(BsonMinKey.Value, c.X["XMinKey"]); Assert.Equal(null, c.X["XNull"]); Assert.Equal(ObjectId.Parse("00112233445566778899aabb"), c.X["XObjectId"]); Assert.Equal(new BsonRegularExpression("abc"), c.X["XRegularExpression"]); Assert.Equal("abc", c.X["XString"]); Assert.Same(BsonSymbolTable.Lookup("abc"), c.X["XSymbol"]); Assert.Equal(new BsonTimestamp(1234), c.X["XTimestamp"]); Assert.Same(BsonUndefined.Value, c.X["XUndefined"]); #pragma warning disable 618 }
public void TestExtraElementsOfAllTypes() { var json = "{ '_id' : 1, 'A' : 2, 'B' : 3, #X }"; var extraElements = new string[][] { new string[] { "XArray", "[1, 2.0]" }, new string[] { "XBinary", "HexData(2, '1234')" }, new string[] { "XBoolean", "true" }, new string[] { "XByteArray", "HexData(0, '1234')" }, new string[] { "XDateTime", "ISODate('2012-03-16T11:19:00Z')" }, new string[] { "XDocument", "{ 'a' : 1 }" }, new string[] { "XDouble", "1.0" }, new string[] { "XGuidLegacy", "HexData(3, '33221100554477668899aabbccddeeff')" }, new string[] { "XGuidStandard", "HexData(4, '00112233445566778899aabbccddeeff')" }, new string[] { "XInt32", "1" }, new string[] { "XInt64", "NumberLong(1)" }, new string[] { "XJavaScript", "{ '$code' : 'abc' }" }, new string[] { "XJavaScriptWithScope", "{ '$code' : 'abc', '$scope' : { 'x' : 1 } }" }, new string[] { "XMaxKey", "MaxKey" }, new string[] { "XMinKey", "MinKey" }, new string[] { "XNull", "null" }, new string[] { "XObjectId", "ObjectId('00112233445566778899aabb')" }, new string[] { "XRegularExpression", "/abc/" }, new string[] { "XString", "'abc'" }, new string[] { "XSymbol", "{ '$symbol' : 'abc' }" }, new string[] { "XTimestamp", "{ '$timestamp' : NumberLong(1234) }" }, new string[] { "XUndefined", "undefined" }, }; var extraElementsRepresentation = string.Join(", ", extraElements.Select(e => string.Format("'{0}' : {1}", e[0], e[1])).ToArray()); json = json.Replace("#X", extraElementsRepresentation).Replace("'", "\""); var c = BsonSerializer.Deserialize <C>(json); // round trip it both ways before checking individual values json = c.ToJson(); c = BsonSerializer.Deserialize <C>(json); Assert.IsInstanceOf <List <object> >(c.X["XArray"]); Assert.IsInstanceOf <BsonBinaryData>(c.X["XBinary"]); Assert.IsInstanceOf <bool>(c.X["XBoolean"]); Assert.IsInstanceOf <byte[]>(c.X["XByteArray"]); Assert.IsInstanceOf <DateTime>(c.X["XDateTime"]); Assert.IsInstanceOf <Dictionary <string, object> >(c.X["XDocument"]); Assert.IsInstanceOf <double>(c.X["XDouble"]); Assert.IsInstanceOf <Guid>(c.X["XGuidLegacy"]); Assert.IsInstanceOf <Guid>(c.X["XGuidStandard"]); Assert.IsInstanceOf <int>(c.X["XInt32"]); Assert.IsInstanceOf <long>(c.X["XInt64"]); Assert.IsInstanceOf <BsonJavaScript>(c.X["XJavaScript"]); Assert.IsInstanceOf <BsonJavaScriptWithScope>(c.X["XJavaScriptWithScope"]); Assert.IsInstanceOf <BsonMaxKey>(c.X["XMaxKey"]); Assert.IsInstanceOf <BsonMinKey>(c.X["XMinKey"]); Assert.IsNull(c.X["XNull"]); Assert.IsInstanceOf <ObjectId>(c.X["XObjectId"]); Assert.IsInstanceOf <BsonRegularExpression>(c.X["XRegularExpression"]); Assert.IsInstanceOf <string>(c.X["XString"]); Assert.IsInstanceOf <BsonSymbol>(c.X["XSymbol"]); Assert.IsInstanceOf <BsonTimestamp>(c.X["XTimestamp"]); Assert.IsInstanceOf <BsonUndefined>(c.X["XUndefined"]); Assert.AreEqual(22, c.X.Count); Assert.IsTrue(new object[] { 1, 2.0 }.SequenceEqual((List <object>)c.X["XArray"])); #pragma warning disable 618 // OldBinary is obsolete Assert.AreEqual(BsonBinarySubType.OldBinary, ((BsonBinaryData)c.X["XBinary"]).SubType); #pragma warning restore 618 Assert.IsTrue(new byte[] { 0x12, 0x34 }.SequenceEqual(((BsonBinaryData)c.X["XBinary"]).Bytes)); Assert.AreEqual(true, c.X["XBoolean"]); Assert.IsTrue(new byte[] { 0x12, 0x34 }.SequenceEqual((byte[])c.X["XByteArray"])); Assert.AreEqual(new DateTime(2012, 3, 16, 11, 19, 0, DateTimeKind.Utc), c.X["XDateTime"]); Assert.AreEqual(1, ((IDictionary <string, object>)c.X["XDocument"]).Count); Assert.AreEqual(1, ((IDictionary <string, object>)c.X["XDocument"])["a"]); Assert.AreEqual(1.0, c.X["XDouble"]); Assert.AreEqual(new Guid("00112233-4455-6677-8899-aabbccddeeff"), c.X["XGuidLegacy"]); Assert.AreEqual(new Guid("00112233-4455-6677-8899-aabbccddeeff"), c.X["XGuidStandard"]); Assert.AreEqual(1, c.X["XInt32"]); Assert.AreEqual(1L, c.X["XInt64"]); Assert.AreEqual("abc", ((BsonJavaScript)c.X["XJavaScript"]).Code); Assert.AreEqual("abc", ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Code); Assert.AreEqual(1, ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Scope.ElementCount); Assert.AreEqual(new BsonInt32(1), ((BsonJavaScriptWithScope)c.X["XJavaScriptWithScope"]).Scope["x"]); Assert.AreSame(BsonMaxKey.Value, c.X["XMaxKey"]); Assert.AreSame(BsonMinKey.Value, c.X["XMinKey"]); Assert.AreEqual(null, c.X["XNull"]); Assert.AreEqual(ObjectId.Parse("00112233445566778899aabb"), c.X["XObjectId"]); Assert.AreEqual(new BsonRegularExpression("abc"), c.X["XRegularExpression"]); Assert.AreEqual("abc", c.X["XString"]); Assert.AreSame(BsonSymbolTable.Lookup("abc"), c.X["XSymbol"]); Assert.AreEqual(new BsonTimestamp(1234), c.X["XTimestamp"]); Assert.AreSame(BsonUndefined.Value, c.X["XUndefined"]); }