public void TestBookmark() { var json = "{ \"x\" : 1, \"y\" : 2 }"; using (bsonReader = BsonReader.Create(json)) { // do everything twice returning to bookmark in between var bookmark = bsonReader.GetBookmark(); Assert.AreEqual(BsonType.Document, bsonReader.ReadBsonType()); bsonReader.ReturnToBookmark(bookmark); Assert.AreEqual(BsonType.Document, bsonReader.ReadBsonType()); bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); bsonReader.ReturnToBookmark(bookmark); bsonReader.ReadStartDocument(); bookmark = bsonReader.GetBookmark(); Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType()); bsonReader.ReturnToBookmark(bookmark); Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType()); bookmark = bsonReader.GetBookmark(); Assert.AreEqual("x", bsonReader.ReadName()); bsonReader.ReturnToBookmark(bookmark); Assert.AreEqual("x", bsonReader.ReadName()); bookmark = bsonReader.GetBookmark(); Assert.AreEqual(1, bsonReader.ReadInt32()); bsonReader.ReturnToBookmark(bookmark); Assert.AreEqual(1, bsonReader.ReadInt32()); bookmark = bsonReader.GetBookmark(); Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType()); bsonReader.ReturnToBookmark(bookmark); Assert.AreEqual(BsonType.Int32, bsonReader.ReadBsonType()); bookmark = bsonReader.GetBookmark(); Assert.AreEqual("y", bsonReader.ReadName()); bsonReader.ReturnToBookmark(bookmark); Assert.AreEqual("y", bsonReader.ReadName()); bookmark = bsonReader.GetBookmark(); Assert.AreEqual(2, bsonReader.ReadInt32()); bsonReader.ReturnToBookmark(bookmark); Assert.AreEqual(2, bsonReader.ReadInt32()); bookmark = bsonReader.GetBookmark(); Assert.AreEqual(BsonType.EndOfDocument, bsonReader.ReadBsonType()); bsonReader.ReturnToBookmark(bookmark); Assert.AreEqual(BsonType.EndOfDocument, bsonReader.ReadBsonType()); bookmark = bsonReader.GetBookmark(); bsonReader.ReadEndDocument(); bsonReader.ReturnToBookmark(bookmark); bsonReader.ReadEndDocument(); Assert.AreEqual(BsonReaderState.Done, bsonReader.State); } Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(new StringReader(json)).ToJson()); }
// 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) { if (bsonReader.GetCurrentBsonType() == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { bsonReader.ReadStartDocument(); DeserializeType(bsonReader, "link"); bsonReader.ReadName("properties"); bsonReader.ReadStartDocument(); var href = bsonReader.ReadString("href"); string hrefType = null; if (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { hrefType = bsonReader.ReadString("type"); } bsonReader.ReadEndDocument(); bsonReader.ReadEndDocument(); return(new GeoJsonLinkedCoordinateReferenceSystem(href, hrefType)); } }
public void TestDocumentNested() { var json = "{ \"a\" : { \"x\" : 1 }, \"y\" : 2 }"; using (_bsonReader = BsonReader.Create(json)) { Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType()); _bsonReader.ReadStartDocument(); Assert.AreEqual(BsonType.Document, _bsonReader.ReadBsonType()); Assert.AreEqual("a", _bsonReader.ReadName()); _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(BsonType.Int32, _bsonReader.ReadBsonType()); Assert.AreEqual("y", _bsonReader.ReadName()); Assert.AreEqual(2, _bsonReader.ReadInt32()); Assert.AreEqual(BsonType.EndOfDocument, _bsonReader.ReadBsonType()); _bsonReader.ReadEndDocument(); Assert.AreEqual(BsonReaderState.Done, _bsonReader.State); } Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(new StringReader(json)).ToJson()); }
// private methods private Type GetActualType(BsonReader bsonReader) { var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); if (bsonReader.FindElement("type")) { var type = bsonReader.ReadString(); bsonReader.ReturnToBookmark(bookmark); switch (type) { case "link": return(typeof(GeoJsonLinkedCoordinateReferenceSystem)); case "name": return(typeof(GeoJsonNamedCoordinateReferenceSystem)); default: var message = string.Format("The type field of the GeoJsonCoordinateReferenceSystem is not valid: '{0}'.", type); throw new FormatException(message); } } else { throw new FormatException("GeoJsonCoordinateReferenceSystem object is missing the type field."); } }
public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { var obj = Activator.CreateInstance(actualType); 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(obj); }
private ZValue ReadZValueFromBsonDocument(BsonReader bsonReader) { // { "_t" : "ZString", "value" : "" } bsonReader.ReadStartDocument(); BsonType type = bsonReader.ReadBsonType(); if (type != BsonType.String) { throw new PBException("error reading ZValue can't find ZValue type \"_t\""); } string name = bsonReader.ReadName(); if (name != "_t") { throw new PBException("error reading ZValue can't find ZValue type \"_t\""); } string typeName = bsonReader.ReadString(); type = bsonReader.ReadBsonType(); name = bsonReader.ReadName(); if (name != "value") { throw new PBException("error reading ZValue can't find ZValue value \"value\""); } ZValue value = null; switch (typeName) { case "ZString": if (type != BsonType.String) { throw new PBException("error reading ZString value is'nt a string ({0})", type); } value = new ZString(bsonReader.ReadString()); break; //case "ZStringArray": // if (type != BsonType.Array) // throw new PBException("error reading ZStringArray value is'nt an array ({0})", type); // value = new ZString(bsonReader.ReadString()); // break; case "ZInt": if (type != BsonType.Int32) { throw new PBException("error reading ZInt value is'nt an int32 ({0})", type); } value = new ZInt(bsonReader.ReadInt32()); break; default: throw new PBException("error reading ZValue type \"{0}\" is'nt a ZValue type", typeName); } type = bsonReader.ReadBsonType(); if (type != BsonType.EndOfDocument) { throw new PBException("error reading ZValue cant find end of document ({0})", type); } bsonReader.ReadEndDocument(); return(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(CultureInfo)); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return(null); case BsonType.Document: bsonReader.ReadStartDocument(); var name = bsonReader.ReadString("Name"); var useUserOverride = bsonReader.ReadBoolean("UseUserOverride"); bsonReader.ReadEndDocument(); return(new CultureInfo(name, useUserOverride)); case BsonType.String: return(new CultureInfo(bsonReader.ReadString())); default: var message = string.Format("Cannot deserialize CultureInfo from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
// 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(DateTimeOffset)); BsonType bsonType = bsonReader.GetCurrentBsonType(); long ticks; TimeSpan offset; switch (bsonType) { case BsonType.Array: bsonReader.ReadStartArray(); ticks = bsonReader.ReadInt64(); offset = TimeSpan.FromMinutes(bsonReader.ReadInt32()); bsonReader.ReadEndArray(); return new DateTimeOffset(ticks, offset); case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadDateTime("DateTime"); // ignore value ticks = bsonReader.ReadInt64("Ticks"); offset = TimeSpan.FromMinutes(bsonReader.ReadInt32("Offset")); bsonReader.ReadEndDocument(); return new DateTimeOffset(ticks, offset); case BsonType.String: return XmlConvert.ToDateTimeOffset(bsonReader.ReadString()); default: var message = string.Format("Cannot deserialize DateTimeOffset from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
// private methods private bool IsCSharpNullRepresentation(BsonReader bsonReader) { var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); var bsonType = bsonReader.ReadBsonType(); if (bsonType == BsonType.Boolean) { var name = bsonReader.ReadName(); if (name == "_csharpnull" || name == "$csharpnull") { var value = bsonReader.ReadBoolean(); if (value) { bsonType = bsonReader.ReadBsonType(); if (bsonType == BsonType.EndOfDocument) { bsonReader.ReadEndDocument(); return(true); } } } } bsonReader.ReturnToBookmark(bookmark); return(false); }
public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { VerifyTypes(nominalType, actualType, typeof(DateTimeOffset)); BsonType bsonType = bsonReader.GetCurrentBsonType(); long ticks; TimeSpan offset; switch (bsonType) { case BsonType.Array: bsonReader.ReadStartArray(); ticks = bsonReader.ReadInt64(); offset = TimeSpan.FromMinutes(bsonReader.ReadInt32()); bsonReader.ReadEndArray(); return(new DateTimeOffset(ticks, offset).Add(offset)); case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadDateTime("DateTime"); ticks = bsonReader.ReadInt64("Ticks"); offset = TimeSpan.FromMinutes(bsonReader.ReadInt32("Offset")); bsonReader.ReadEndDocument(); return(new DateTimeOffset(ticks, offset).Add(offset)); default: var message = string.Format("Cannot deserialize DateTimeOffset from BsonType {0}.", bsonType); throw new ArgumentException(message); } }
public Type GetActualType(BsonReader bsonReader, Type nominalType) { //Edit: added additional check for list if (nominalType != typeof(IRestriction) && nominalType != typeof(List <IRestriction>)) { throw new Exception("Cannot use IRestrictionDiscriminatorConvention for type " + nominalType); } var ret = nominalType; var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); if (bsonReader.FindElement(ElementName)) { var value = bsonReader.ReadString(); ret = Type.GetType(value); if (ret == null) { throw new Exception("Could not find type from " + value); } //Edit: doing the checking a little different if (!typeof(IRestriction).IsAssignableFrom(ret) && !ret.IsSubclassOf(typeof(IRestriction))) { throw new Exception("type is not an IRestriction"); } } bsonReader.ReturnToBookmark(bookmark); return(ret); }
// 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(CultureInfo)); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return null; case BsonType.Document: bsonReader.ReadStartDocument(); var name = bsonReader.ReadString("Name"); var useUserOverride = bsonReader.ReadBoolean("UseUserOverride"); bsonReader.ReadEndDocument(); return new CultureInfo(name, useUserOverride); case BsonType.String: return new CultureInfo(bsonReader.ReadString()); default: var message = string.Format("Cannot deserialize CultureInfo from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
// public methods /// <summary> /// Gets the actual type of an object by reading the discriminator from a BsonReader. /// </summary> /// <param name="bsonReader">The reader.</param> /// <param name="nominalType">The nominal type.</param> /// <returns>The actual type.</returns> public Type GetActualType(BsonReader bsonReader, Type nominalType) { // the BsonReader is sitting at the value whose actual type needs to be found var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Document) { // ensure KnownTypes of nominalType are registered (so IsTypeDiscriminated returns correct answer) BsonSerializer.EnsureKnownTypesAreRegistered(nominalType); // we can skip looking for a discriminator if nominalType has no discriminated sub types if (BsonSerializer.IsTypeDiscriminated(nominalType)) { var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); var actualType = nominalType; if (bsonReader.FindElement(_elementName)) { var context = BsonDeserializationContext.CreateRoot <BsonValue>(bsonReader); var discriminator = BsonValueSerializer.Instance.Deserialize(context); if (discriminator.IsBsonArray) { discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator } actualType = BsonSerializer.LookupActualType(nominalType, discriminator); } bsonReader.ReturnToBookmark(bookmark); return(actualType); } } return(nominalType); }
public Type GetActualType( BsonReader 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> /// 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 object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { if (actualType != typeof(object)) { var message = string.Format("ObjectSerializer can only be used with actual type System.Object, not type {1}.", actualType.FullName); throw new ArgumentException(message, "actualType"); } var bsonType = bsonReader.CurrentBsonType; if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } else if (bsonType == BsonType.Document) { bsonReader.ReadStartDocument(); if (bsonReader.ReadBsonType() == BsonType.EndOfDocument) { bsonReader.ReadEndDocument(); return(new object()); } else { var message = string.Format("A document being deserialized to System.Object must be empty."); throw new FileFormatException(message); } } else { var message = string.Format("Cannot deserialize System.Object from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
/// <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, // ignored IBsonSerializationOptions options ) { var bsonType = bsonReader.CurrentBsonType; if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } else if (bsonType == BsonType.Document) { var dictionary = CreateInstance(nominalType); bsonReader.ReadStartDocument(); var valueDiscriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(typeof(TValue)); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var key = (TKey)(object)bsonReader.ReadName(); var valueType = valueDiscriminatorConvention.GetActualType(bsonReader, typeof(TValue)); var valueSerializer = BsonSerializer.LookupSerializer(valueType); var value = (TValue)valueSerializer.Deserialize(bsonReader, typeof(TValue), valueType, null); dictionary.Add(key, value); } bsonReader.ReadEndDocument(); return(dictionary); } else if (bsonType == BsonType.Array) { var dictionary = CreateInstance(nominalType); bsonReader.ReadStartArray(); var keyDiscriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(typeof(TKey)); var valueDiscriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(typeof(TValue)); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { bsonReader.ReadStartArray(); bsonReader.ReadBsonType(); var keyType = keyDiscriminatorConvention.GetActualType(bsonReader, typeof(TKey)); var keySerializer = BsonSerializer.LookupSerializer(keyType); var key = (TKey)keySerializer.Deserialize(bsonReader, typeof(TKey), keyType, null); bsonReader.ReadBsonType(); var valueType = valueDiscriminatorConvention.GetActualType(bsonReader, typeof(TValue)); var valueSerializer = BsonSerializer.LookupSerializer(valueType); var value = (TValue)valueSerializer.Deserialize(bsonReader, typeof(TValue), valueType, null); bsonReader.ReadEndArray(); dictionary.Add(key, value); } bsonReader.ReadEndArray(); return(dictionary); } else { var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType); throw new FileFormatException(message); } }
// 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) { var arraySerializationOptions = EnsureSerializationOptions <ArraySerializationOptions>(options); var itemSerializationOptions = arraySerializationOptions.ItemSerializationOptions; var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return(null); case BsonType.Array: var instance = CreateInstance(actualType); var itemDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object)); Type lastItemType = null; IBsonSerializer lastItemSerializer = null; bsonReader.ReadStartArray(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var itemType = itemDiscriminatorConvention.GetActualType(bsonReader, typeof(object)); IBsonSerializer itemSerializer; if (itemType == lastItemType) { itemSerializer = lastItemSerializer; } else { itemSerializer = BsonSerializer.LookupSerializer(itemType); lastItemType = itemType; lastItemSerializer = itemSerializer; } var item = itemSerializer.Deserialize(bsonReader, typeof(object), itemType, itemSerializationOptions); AddItem(instance, item); } bsonReader.ReadEndArray(); return(FinalizeResult(instance, actualType)); case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadString("_t"); // skip over discriminator bsonReader.ReadName("_v"); var value = Deserialize(bsonReader, actualType, actualType, options); bsonReader.ReadEndDocument(); return(value); default: var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType); throw new FileFormatException(message); } }
public Money ReadFrom(BsonReader reader) { reader.ReadStartDocument(); var amount = readAmount(reader); var currency = readCurrency(reader); reader.ReadEndDocument(); return(new Money(amount, currency)); }
/// <summary> /// Deserializes an Bitmap from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the Bitmap.</param> /// <param name="actualType">The actual type of the Bitmap.</param> /// <param name="options">The serialization options.</param> /// <returns>A Bitmap.</returns> public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options ) { if (nominalType != typeof(Image) && nominalType != typeof(Bitmap)) { var message = string.Format("Nominal type must be Image or Bitmap, not {0}.", nominalType.FullName); throw new ArgumentException(message, "nominalType"); } if (actualType != typeof(Bitmap)) { var message = string.Format("Actual type must be Bitmap, not {0}.", actualType.FullName); throw new ArgumentException(message, "actualType"); } var bsonType = bsonReader.CurrentBsonType; byte[] bytes; BsonBinarySubType subType; switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return(null); case BsonType.Binary: bsonReader.ReadBinaryData(out bytes, out subType); break; case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadString("_t"); bsonReader.ReadBinaryData("bitmap", out bytes, out subType); bsonReader.ReadEndDocument(); break; default: var message = string.Format("BsonType must be Null, Binary or Document, not {0}.", bsonType); throw new FileFormatException(message); } if (subType != BsonBinarySubType.Binary) { var message = string.Format("Binary sub type must be Binary, not {0}.", subType); throw new FileFormatException(message); } var stream = new MemoryStream(bytes); return(new Bitmap(stream)); }
protected override CurrencyIsoCode readCurrency(BsonReader reader) { reader.ReadStartDocument(); BsonMemberMap currencyMap = _map.GetMemberMap(m => m.CurrencyCode); string currency = reader.ReadString("IsoCode".CapitalizeAs(currencyMap)); reader.ReadEndDocument(); return(Currency.Code.Parse(currency)); }
// public methods #pragma warning disable 618 // about obsolete BsonBinarySubType.OldBinary /// <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(BitArray)); BsonType bsonType = bsonReader.GetCurrentBsonType(); BitArray bitArray; switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return(null); case BsonType.Binary: return(new BitArray(bsonReader.ReadBytes())); case BsonType.Document: bsonReader.ReadStartDocument(); var length = bsonReader.ReadInt32("Length"); var bytes = bsonReader.ReadBytes("Bytes"); bsonReader.ReadEndDocument(); bitArray = new BitArray(bytes); bitArray.Length = length; return(bitArray); case BsonType.String: var s = bsonReader.ReadString(); bitArray = new BitArray(s.Length); for (int i = 0; i < s.Length; i++) { var c = s[i]; switch (c) { case '0': break; case '1': bitArray[i] = true; break; default: throw new FileFormatException("String value is not a valid BitArray."); } } return(bitArray); default: var message = string.Format("Cannot deserialize Byte[] from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
public Type GetActualType(BsonReader bsonReader, System.Type nominalType) { var currentBsonType = bsonReader.GetCurrentBsonType(); if (bsonReader.State == BsonReaderState.Value) { if (currentBsonType == BsonType.Document) { var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); var type = nominalType; if (bsonReader.FindElement(ElementName)) { var discriminator = BsonValue.ReadFrom(bsonReader).AsString; try { if (discriminator == "Typed") { type = typeof(TypedSettings <>); bsonReader.ReturnToBookmark(bookmark); bsonReader.ReadStartDocument(); bsonReader.FindElement("Name"); var stringType = BsonValue.ReadFrom(bsonReader).AsString; type = type.MakeGenericType(Type.GetType(stringType)); } else if (discriminator == "Setting") { type = typeof(Setting); } } catch (Exception ex) { type = typeof(Setting); } } bsonReader.ReturnToBookmark(bookmark); return(type); } } return(nominalType); }
// 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) { if (bsonReader.GetCurrentBsonType() == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { bsonReader.ReadStartDocument(); DeserializeType(bsonReader, "name"); bsonReader.ReadName("properties"); bsonReader.ReadStartDocument(); var name = bsonReader.ReadString("name"); bsonReader.ReadEndDocument(); bsonReader.ReadEndDocument(); return(new GeoJsonNamedCoordinateReferenceSystem(name)); } }
public void TestNestedDocument() { var json = "{ \"a\" : { \"b\" : 1, \"c\" : 2 } }"; using (bsonReader = BsonReader.Create(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.Done, bsonReader.State); } Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(new StringReader(json)).ToJson()); }
public void TestDocumentEmpty() { var json = "{ }"; using (bsonReader = BsonReader.Create(json)) { Assert.AreEqual(BsonType.Document, bsonReader.ReadBsonType()); bsonReader.ReadStartDocument(); Assert.AreEqual(BsonType.EndOfDocument, bsonReader.ReadBsonType()); bsonReader.ReadEndDocument(); Assert.AreEqual(BsonReaderState.Done, bsonReader.State); } Assert.AreEqual(json, BsonSerializer.Deserialize <BsonDocument>(new StringReader(json)).ToJson()); }
public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options) { EvaluationResult er = new EvaluationResult(); bsonReader.ReadStartDocument(); er.Id = bsonReader.ReadObjectId(); er.DurationInSeconds = bsonReader.ReadDouble(); er.startTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime()); er.endTime = BsonUtils.ToDateTimeFromMillisecondsSinceEpoch(bsonReader.ReadDateTime()); er.Result = EvaluationStatus.Parse(bsonReader.ReadString()); er.JSON = bsonReader.ReadString(); bsonReader.ReadEndDocument(); return(er); }
// 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(DateTimeOffset)); var dateTimeSerializationOptions = EnsureSerializationOptions <DateTimeSerializationOptions>(options); var bsonType = bsonReader.GetCurrentBsonType(); DateTimeOffset value; switch (bsonType) { case BsonType.DateTime: // use an intermediate BsonDateTime so MinValue and MaxValue are handled correctly value = BsonDateTime.Create(bsonReader.ReadDateTime()).Value; break; case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadDateTime("DateTimeUTC"); // ignore value (use Ticks instead) value = new DateTime(bsonReader.ReadInt64("Ticks"), DateTimeKind.Utc); bsonReader.ReadEndDocument(); break; case BsonType.Int64: value = new DateTime(bsonReader.ReadInt64(), DateTimeKind.Utc); break; case BsonType.String: // note: we're not using XmlConvert because of bugs in Mono if (dateTimeSerializationOptions.DateOnly) { value = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc); } else { var formats = new string[] { "yyyy-MM-ddK", "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK" }; value = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); } break; default: var message = string.Format("Cannot deserialize DateTimeOffset from BsonType {0}.", bsonType); throw new FormatException(message); } return(value); }
public override IJobDetail Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { BsonReader bsonReader = (BsonReader)context.Reader; Type nominalType = args.NominalType; var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Document) { bsonReader.ReadStartDocument(); BsonSerializer.Deserialize(bsonReader, typeof(JobKey)); bsonReader.ReadString(TYPE); Assembly assembly = Assembly.Load(bsonReader.ReadString(ASSEMBLY)); Type jobType = assembly.GetType(bsonReader.ReadString(CLASS)); string name = bsonReader.ReadString(NAME); string group = bsonReader.ReadString(GROUP); bool requestRecovery = bsonReader.ReadBoolean(REQUEST_RECOVERY); bool durable = bsonReader.ReadBoolean(DURABLE); IJobDetail jobDetail = new JobDetailImpl(name, group, jobType, durable, requestRecovery); bsonReader.ReadBsonType(); JobDataMap map = (JobDataMap)BsonSerializer.Deserialize(bsonReader, typeof(JobDataMap)); /*bsonReader.ReadBsonType(); * string description = (string)BsonSerializer.Deserialize(bsonReader, typeof(string));*/ jobDetail = jobDetail.GetJobBuilder() .UsingJobData(map) /*.WithDescription(description)*/ .Build(); bsonReader.ReadEndDocument(); return(jobDetail); } else if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { var message = string.Format(DESERIALIZE_ERROR_MESSAGE, nominalType.FullName, bsonType); throw new BsonSerializationException(message); } }
public Type GetActualType(BsonReader bsonReader, Type nominalType) { var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); var actualType = nominalType; if (bsonReader.FindElement(ElementName)) { var discriminator = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null); actualType = BsonSerializer.LookupActualType(nominalType, discriminator); } bsonReader.ReturnToBookmark(bookmark); return(actualType); }
public object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { BsonReader bsonReader = (BsonReader)context.Reader; CalendarWrapper item = new CalendarWrapper(); bsonReader.ReadStartDocument(); item.Name = bsonReader.ReadString(ID); var binaryData = bsonReader.ReadBinaryData(CONTENT_STREAM); item.Calendar = (ICalendar) new BinaryFormatter().Deserialize(new MemoryStream(binaryData.Bytes)); bsonReader.ReadEndDocument(); return(item); }
public void TestHelloWorld() { string byteString = @"\x16\x00\x00\x00\x02hello\x00\x06\x00\x00\x00world\x00\x00"; byte[] bytes = DecodeByteString(byteString); MemoryStream stream = new MemoryStream(bytes); using (BsonReader bsonReader = BsonReader.Create(stream)) { bsonReader.ReadStartDocument(); Assert.AreEqual(BsonType.String, bsonReader.ReadBsonType()); Assert.AreEqual("hello", bsonReader.ReadName()); Assert.AreEqual("world", bsonReader.ReadString()); bsonReader.ReadEndDocument(); } }
public Type GetActualType(BsonReader bsonReader, Type nominalType) { BsonReaderBookmark bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); Type actualType = nominalType; if (bsonReader.FindElement("Type")) { BsonValue discriminator = BsonSerializer.Deserialize <BsonValue>(bsonReader); actualType = BsonSerializer.LookupActualType(nominalType, discriminator); } bsonReader.ReturnToBookmark(bookmark); return(actualType); }
// public methods #pragma warning disable 618 // about obsolete BsonBinarySubType.OldBinary /// <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(BitArray)); BsonType bsonType = bsonReader.GetCurrentBsonType(); BitArray bitArray; switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return null; case BsonType.Binary: return new BitArray(bsonReader.ReadBytes()); case BsonType.Document: bsonReader.ReadStartDocument(); var length = bsonReader.ReadInt32("Length"); var bytes = bsonReader.ReadBytes("Bytes"); bsonReader.ReadEndDocument(); bitArray = new BitArray(bytes); bitArray.Length = length; return bitArray; case BsonType.String: var s = bsonReader.ReadString(); bitArray = new BitArray(s.Length); for (int i = 0; i < s.Length; i++) { var c = s[i]; switch (c) { case '0': break; case '1': bitArray[i] = true; break; default: throw new FileFormatException("String value is not a valid BitArray."); } } return bitArray; default: var message = string.Format("Cannot deserialize Byte[] from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
// 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="options">The serialization options.</param> /// <returns>An object.</returns> public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options) { if (nominalType != typeof(object)) { var message = string.Format("ObjectSerializer can only be used with nominal type System.Object, not type {0}.", nominalType.FullName); throw new InvalidOperationException(message); } var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return null; } else if (bsonType == BsonType.Document) { var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); if (bsonReader.ReadBsonType() == BsonType.EndOfDocument) { bsonReader.ReadEndDocument(); return new object(); } else { bsonReader.ReturnToBookmark(bookmark); } } var discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object)); var actualType = discriminatorConvention.GetActualType(bsonReader, typeof(object)); if (actualType == typeof(object)) { var message = string.Format("Unable to determine actual type of object to deserialize. NominalType is System.Object and BsonType is {0}.", bsonType); throw new FileFormatException(message); } var serializer = BsonSerializer.LookupSerializer(actualType); return serializer.Deserialize(bsonReader, nominalType, actualType, options); }
// 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(BsonDocument)); var bsonType = bsonReader.GetCurrentBsonType(); string message; switch (bsonType) { case BsonType.Document: var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions; if (documentSerializationOptions == null) { message = string.Format( "Serialize method of BsonDocument expected serialization options of type {0}, not {1}.", BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)), BsonUtils.GetFriendlyTypeName(options.GetType())); throw new BsonSerializationException(message); } bsonReader.ReadStartDocument(); var document = new BsonDocument(documentSerializationOptions.AllowDuplicateNames); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var name = bsonReader.ReadName(); var value = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null); document.Add(name, value); } bsonReader.ReadEndDocument(); return document; default: message = string.Format("Cannot deserialize BsonDocument from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
// public methods /// <summary> /// Deserializes an object of type System.Drawing.Size 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(System.Drawing.Size)); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Document: bsonReader.ReadStartDocument(); var width = bsonReader.ReadInt32("Width"); var height = bsonReader.ReadInt32("Height"); bsonReader.ReadEndDocument(); return new System.Drawing.Size(width, height); default: var message = string.Format("Cannot deserialize Size from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
// 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) { var dictionarySerializationOptions = EnsureSerializationOptions(options); var dictionaryRepresentation = dictionarySerializationOptions.Representation; var keyValuePairSerializationOptions = dictionarySerializationOptions.KeyValuePairSerializationOptions; var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return null; } else if (bsonType == BsonType.Document) { if (nominalType == typeof(object)) { bsonReader.ReadStartDocument(); bsonReader.ReadString("_t"); // skip over discriminator bsonReader.ReadName("_v"); var value = Deserialize(bsonReader, actualType, options); // recursive call replacing nominalType with actualType bsonReader.ReadEndDocument(); return value; } var dictionary = CreateInstance(actualType); var valueDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object)); bsonReader.ReadStartDocument(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var key = bsonReader.ReadName(); var valueType = valueDiscriminatorConvention.GetActualType(bsonReader, typeof(object)); var valueSerializer = BsonSerializer.LookupSerializer(valueType); var value = valueSerializer.Deserialize(bsonReader, typeof(object), valueType, keyValuePairSerializationOptions.ValueSerializationOptions); dictionary.Add(key, value); } bsonReader.ReadEndDocument(); return dictionary; } else if (bsonType == BsonType.Array) { var dictionary = CreateInstance(actualType); bsonReader.ReadStartArray(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var keyValuePair = (KeyValuePair<object, object>)_keyValuePairSerializer.Deserialize( bsonReader, typeof(KeyValuePair<object, object>), keyValuePairSerializationOptions); dictionary.Add(keyValuePair.Key, keyValuePair.Value); } bsonReader.ReadEndArray(); return dictionary; } else { var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType); throw new FileFormatException(message); } }
// public methods /// <summary> /// Gets the actual type of an object by reading the discriminator from a BsonReader. /// </summary> /// <param name="bsonReader">The reader.</param> /// <param name="nominalType">The nominal type.</param> /// <returns>The actual type.</returns> public Type GetActualType(BsonReader bsonReader, Type nominalType) { // the BsonReader is sitting at the value whose actual type needs to be found var bsonType = bsonReader.GetCurrentBsonType(); if (bsonReader.State == BsonReaderState.Value) { Type primitiveType = null; switch (bsonType) { case BsonType.Boolean: primitiveType = typeof(bool); break; case BsonType.Binary: var bookmark = bsonReader.GetBookmark(); byte[] bytes; BsonBinarySubType subType; bsonReader.ReadBinaryData(out bytes, out subType); if (subType == BsonBinarySubType.UuidStandard || subType == BsonBinarySubType.UuidLegacy) { primitiveType = typeof(Guid); } bsonReader.ReturnToBookmark(bookmark); break; case BsonType.DateTime: primitiveType = typeof(DateTime); break; case BsonType.Double: primitiveType = typeof(double); break; case BsonType.Int32: primitiveType = typeof(int); break; case BsonType.Int64: primitiveType = typeof(long); break; case BsonType.ObjectId: primitiveType = typeof(ObjectId); break; case BsonType.String: primitiveType = typeof(string); break; } // Type.IsAssignableFrom is extremely expensive, always perform a direct type check before calling Type.IsAssignableFrom if (primitiveType != null && (primitiveType == nominalType || nominalType.IsAssignableFrom(primitiveType))) { return primitiveType; } } if (bsonType == BsonType.Document) { // ensure KnownTypes of nominalType are registered (so IsTypeDiscriminated returns correct answer) BsonSerializer.EnsureKnownTypesAreRegistered(nominalType); // we can skip looking for a discriminator if nominalType has no discriminated sub types if (BsonSerializer.IsTypeDiscriminated(nominalType)) { var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); var actualType = nominalType; if (bsonReader.FindElement(_elementName)) { var discriminator = BsonValue.ReadFrom(bsonReader); if (discriminator.IsBsonArray) { discriminator = discriminator.AsBsonArray.Last(); // last item is leaf class discriminator } actualType = BsonSerializer.LookupActualType(nominalType, discriminator); } bsonReader.ReturnToBookmark(bookmark); return actualType; } } return nominalType; }
// public 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(DateTime)); var dateTimeSerializationOptions = EnsureSerializationOptions<DateTimeSerializationOptions>(options); var bsonType = bsonReader.GetCurrentBsonType(); DateTime value; switch (bsonType) { case BsonType.DateTime: // use an intermediate BsonDateTime so MinValue and MaxValue are handled correctly value = new BsonDateTime(bsonReader.ReadDateTime()).ToUniversalTime(); break; case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadDateTime("DateTime"); // ignore value (use Ticks instead) value = new DateTime(bsonReader.ReadInt64("Ticks"), DateTimeKind.Utc); bsonReader.ReadEndDocument(); break; case BsonType.Int64: value = DateTime.SpecifyKind(new DateTime(bsonReader.ReadInt64()), DateTimeKind.Utc); break; case BsonType.String: // note: we're not using XmlConvert because of bugs in Mono if (dateTimeSerializationOptions.DateOnly) { value = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc); } else { var formats = new string[] { "yyyy-MM-ddK", "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK" }; value = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); } break; default: var message = string.Format("Cannot deserialize DateTime from BsonType {0}.", bsonType); throw new FileFormatException(message); } if (dateTimeSerializationOptions.DateOnly) { if (value.TimeOfDay != TimeSpan.Zero) { throw new FileFormatException("TimeOfDay component for DateOnly DateTime value is not zero."); } value = DateTime.SpecifyKind(value, dateTimeSerializationOptions.Kind); // not ToLocalTime or ToUniversalTime! } else { switch (dateTimeSerializationOptions.Kind) { case DateTimeKind.Local: case DateTimeKind.Unspecified: value = DateTime.SpecifyKind(BsonUtils.ToLocalTime(value), dateTimeSerializationOptions.Kind); break; case DateTimeKind.Utc: value = BsonUtils.ToUniversalTime(value); break; } } return 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) { var arraySerializationOptions = EnsureSerializationOptions<ArraySerializationOptions>(options); var itemSerializationOptions = arraySerializationOptions.ItemSerializationOptions; var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return null; case BsonType.Array: var instance = CreateInstance(actualType); var itemDiscriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object)); Type lastItemType = null; IBsonSerializer lastItemSerializer = null; bsonReader.ReadStartArray(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var itemType = itemDiscriminatorConvention.GetActualType(bsonReader, typeof(object)); IBsonSerializer itemSerializer; if (itemType == lastItemType) { itemSerializer = lastItemSerializer; } else { itemSerializer = BsonSerializer.LookupSerializer(itemType); lastItemType = itemType; lastItemSerializer = itemSerializer; } var item = itemSerializer.Deserialize(bsonReader, typeof(object), itemType, itemSerializationOptions); AddItem(instance, item); } bsonReader.ReadEndArray(); return FinalizeResult(instance, actualType); case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadString("_t"); // skip over discriminator bsonReader.ReadName("_v"); var value = Deserialize(bsonReader, actualType, actualType, options); bsonReader.ReadEndDocument(); return value; default: var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType); throw new FileFormatException(message); } }
/// <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 object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { VerifyNominalType(nominalType); var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == Bson.BsonType.Null) { bsonReader.ReadNull(); return null; } else { if (actualType != _classMap.ClassType) { var message = string.Format("BsonClassMapSerializer.Deserialize for type {0} was called with actualType {1}.", BsonUtils.GetFriendlyTypeName(_classMap.ClassType), BsonUtils.GetFriendlyTypeName(actualType)); throw new BsonSerializationException(message); } if (actualType.IsValueType) { var message = string.Format("Value class {0} cannot be deserialized.", actualType.FullName); throw new BsonSerializationException(message); } if (_classMap.IsAnonymous) { throw new InvalidOperationException("An anonymous class cannot be deserialized."); } if (bsonType != BsonType.Document) { var message = string.Format( "Expected a nested document representing the serialized form of a {0} value, but found a value of type {1} instead.", actualType.FullName, bsonType); throw new FileFormatException(message); } Dictionary<string, object> values = null; object obj = null; ISupportInitialize supportsInitialization = null; if (_classMap.HasCreatorMaps) { // for creator-based deserialization we first gather the values in a dictionary and then call a matching creator values = new Dictionary<string, object>(); } else { // for mutable classes we deserialize the values directly into the result object obj = _classMap.CreateInstance(); supportsInitialization = obj as ISupportInitialize; if (supportsInitialization != null) { supportsInitialization.BeginInit(); } } var discriminatorConvention = _classMap.GetDiscriminatorConvention(); var allMemberMaps = _classMap.AllMemberMaps; var extraElementsMemberMapIndex = _classMap.ExtraElementsMemberMapIndex; var memberMapBitArray = FastMemberMapHelper.GetBitArray(allMemberMaps.Count); bsonReader.ReadStartDocument(); var elementTrie = _classMap.ElementTrie; bool memberMapFound; int memberMapIndex; while (bsonReader.ReadBsonType(elementTrie, out memberMapFound, out memberMapIndex) != BsonType.EndOfDocument) { var elementName = bsonReader.ReadName(); if (memberMapFound) { var memberMap = allMemberMaps[memberMapIndex]; if (memberMapIndex != extraElementsMemberMapIndex) { if (obj != null) { if (memberMap.IsReadOnly) { bsonReader.SkipValue(); } else { var value = DeserializeMemberValue(bsonReader, memberMap); memberMap.Setter(obj, value); } } else { var value = DeserializeMemberValue(bsonReader, memberMap); values[elementName] = value; } } else { DeserializeExtraElement(bsonReader, obj, elementName, memberMap); } memberMapBitArray[memberMapIndex >> 5] |= 1U << (memberMapIndex & 31); } else { if (elementName == discriminatorConvention.ElementName) { bsonReader.SkipValue(); // skip over discriminator continue; } if (extraElementsMemberMapIndex >= 0) { DeserializeExtraElement(bsonReader, obj, elementName, _classMap.ExtraElementsMemberMap); memberMapBitArray[extraElementsMemberMapIndex >> 5] |= 1U << (extraElementsMemberMapIndex & 31); } else if (_classMap.IgnoreExtraElements) { bsonReader.SkipValue(); } else { //james.wei 针对/_id属性没有扩展映射的提示。 var message = string.Format("Element '{0}' does not match any field or property of class {1}.",elementName, _classMap.ClassType.FullName); throw new FileFormatException(message); } } } bsonReader.ReadEndDocument(); // check any members left over that we didn't have elements for (in blocks of 32 elements at a time) for (var bitArrayIndex = 0; bitArrayIndex < memberMapBitArray.Length; ++bitArrayIndex) { memberMapIndex = bitArrayIndex << 5; var memberMapBlock = ~memberMapBitArray[bitArrayIndex]; // notice that bits are flipped so 1's are now the missing elements // work through this memberMapBlock of 32 elements while (true) { // examine missing elements (memberMapBlock is shifted right as we work through the block) for (; (memberMapBlock & 1) != 0; ++memberMapIndex, memberMapBlock >>= 1) { var memberMap = allMemberMaps[memberMapIndex]; if (memberMap.IsReadOnly) { continue; } if (memberMap.IsRequired) { var fieldOrProperty = (memberMap.MemberInfo.MemberType == MemberTypes.Field) ? "field" : "property"; var message = string.Format( "Required element '{0}' for {1} '{2}' of class {3} is missing.", memberMap.ElementName, fieldOrProperty, memberMap.MemberName, _classMap.ClassType.FullName); throw new FileFormatException(message); } if (obj != null) { memberMap.ApplyDefaultValue(obj); } else if (memberMap.IsDefaultValueSpecified && !memberMap.IsReadOnly) { values[memberMap.ElementName] = memberMap.DefaultValue; } } if (memberMapBlock == 0) { break; } // skip ahead to the next missing element var leastSignificantBit = FastMemberMapHelper.GetLeastSignificantBit(memberMapBlock); memberMapIndex += leastSignificantBit; memberMapBlock >>= leastSignificantBit; } } if (obj != null) { if (supportsInitialization != null) { supportsInitialization.EndInit(); } return obj; } else { return CreateInstanceUsingCreator(values); } } }
// private methods private bool IsCSharpNullRepresentation(BsonReader bsonReader) { var bookmark = bsonReader.GetBookmark(); bsonReader.ReadStartDocument(); var bsonType = bsonReader.ReadBsonType(); if (bsonType == BsonType.Boolean) { var name = bsonReader.ReadName(); if (name == "_csharpnull" || name == "$csharpnull") { var value = bsonReader.ReadBoolean(); if (value) { bsonType = bsonReader.ReadBsonType(); if (bsonType == BsonType.EndOfDocument) { bsonReader.ReadEndDocument(); return true; } } } } bsonReader.ReturnToBookmark(bookmark); return false; }
// public 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(BsonDateTime)); var dateTimeSerializationOptions = EnsureSerializationOptions<DateTimeSerializationOptions>(options); var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return null; } else { long? millisecondsSinceEpoch = null; long? ticks = null; switch (bsonType) { case BsonType.DateTime: millisecondsSinceEpoch = bsonReader.ReadDateTime(); break; case BsonType.Document: bsonReader.ReadStartDocument(); millisecondsSinceEpoch = bsonReader.ReadDateTime("DateTime"); bsonReader.ReadName("Ticks"); var ticksValue = BsonValue.ReadFrom(bsonReader); if (!ticksValue.IsBsonUndefined) { ticks = ticksValue.ToInt64(); } bsonReader.ReadEndDocument(); break; case BsonType.Int64: ticks = bsonReader.ReadInt64(); break; case BsonType.String: // note: we're not using XmlConvert because of bugs in Mono DateTime dateTime; if (dateTimeSerializationOptions.DateOnly) { dateTime = DateTime.SpecifyKind(DateTime.ParseExact(bsonReader.ReadString(), "yyyy-MM-dd", null), DateTimeKind.Utc); } else { var formats = new string[] { "yyyy-MM-ddK", "yyyy-MM-ddTHH:mm:ssK", "yyyy-MM-ddTHH:mm:ss.FFFFFFFK", }; dateTime = DateTime.ParseExact(bsonReader.ReadString(), formats, null, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal); } ticks = dateTime.Ticks; break; default: var message = string.Format("Cannot deserialize DateTime from BsonType {0}.", bsonType); throw new FileFormatException(message); } BsonDateTime bsonDateTime; if (ticks.HasValue) { bsonDateTime = BsonDateTime.Create(new DateTime(ticks.Value, DateTimeKind.Utc)); } else { bsonDateTime = BsonDateTime.Create(millisecondsSinceEpoch.Value); } if (dateTimeSerializationOptions.DateOnly) { var dateTime = bsonDateTime.Value; if (dateTime.TimeOfDay != TimeSpan.Zero) { throw new FileFormatException("TimeOfDay component for DateOnly DateTime value is not zero."); } bsonDateTime = BsonDateTime.Create(DateTime.SpecifyKind(dateTime, dateTimeSerializationOptions.Kind)); // not ToLocalTime or ToUniversalTime! } else { if (bsonDateTime.IsValidDateTime) { var dateTime = bsonDateTime.Value; switch (dateTimeSerializationOptions.Kind) { case DateTimeKind.Local: case DateTimeKind.Unspecified: dateTime = DateTime.SpecifyKind(BsonUtils.ToLocalTime(dateTime), dateTimeSerializationOptions.Kind); break; case DateTimeKind.Utc: dateTime = BsonUtils.ToUniversalTime(dateTime); break; } bsonDateTime = BsonDateTime.Create(dateTime); } else { if (dateTimeSerializationOptions.Kind != DateTimeKind.Utc) { throw new FileFormatException("BsonDateTime is outside the range of .NET DateTime."); } } } return bsonDateTime; } }
// 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(Version)); BsonType bsonType = bsonReader.GetCurrentBsonType(); string message; switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return null; case BsonType.Document: bsonReader.ReadStartDocument(); int major = -1, minor = -1, build = -1, revision = -1; while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var name = bsonReader.ReadName(); switch (name) { case "Major": major = bsonReader.ReadInt32(); break; case "Minor": minor = bsonReader.ReadInt32(); break; case "Build": build = bsonReader.ReadInt32(); break; case "Revision": revision = bsonReader.ReadInt32(); break; default: message = string.Format("Unrecognized element '{0}' while deserializing a Version value.", name); throw new FileFormatException(message); } } bsonReader.ReadEndDocument(); if (major == -1) { message = string.Format("Version missing Major element."); throw new FileFormatException(message); } else if (minor == -1) { message = string.Format("Version missing Minor element."); throw new FileFormatException(message); } else if (build == -1) { return new Version(major, minor); } else if (revision == -1) { return new Version(major, minor, build); } else { return new Version(major, minor, build, revision); } case BsonType.String: return new Version(bsonReader.ReadString()); default: message = string.Format("Cannot deserialize Version from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
// public methods /// <summary> /// Deserializes an Bitmap from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the Bitmap.</param> /// <param name="actualType">The actual type of the Bitmap.</param> /// <param name="options">The serialization options.</param> /// <returns>A Bitmap.</returns> public override object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { if (nominalType != typeof(Image) && nominalType != typeof(Bitmap)) { var message = string.Format("Nominal type must be Image or Bitmap, not {0}.", nominalType.FullName); throw new ArgumentException(message, "nominalType"); } if (actualType != typeof(Bitmap)) { var message = string.Format("Actual type must be Bitmap, not {0}.", actualType.FullName); throw new ArgumentException(message, "actualType"); } var bsonType = bsonReader.GetCurrentBsonType(); byte[] bytes; BsonBinarySubType subType; switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return null; case BsonType.Binary: bsonReader.ReadBinaryData(out bytes, out subType); break; case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadString("_t"); bsonReader.ReadBinaryData("bitmap", out bytes, out subType); bsonReader.ReadEndDocument(); break; default: var message = string.Format("BsonType must be Null, Binary or Document, not {0}.", bsonType); throw new FileFormatException(message); } if (subType != BsonBinarySubType.Binary) { var message = string.Format("Binary sub type must be Binary, not {0}.", subType); throw new FileFormatException(message); } var stream = new MemoryStream(bytes); return new Bitmap(stream); }
/// <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 object Deserialize( BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { if (actualType != typeof(object)) { var message = string.Format("ObjectSerializer can only be used with actual type System.Object, not type {0}.", actualType.FullName); throw new ArgumentException(message, "actualType"); } var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return null; } else if (bsonType == BsonType.Document) { bsonReader.ReadStartDocument(); if (bsonReader.ReadBsonType() == BsonType.EndOfDocument) { bsonReader.ReadEndDocument(); return new object(); } else { var message = string.Format("A document being deserialized to System.Object must be empty."); throw new FileFormatException(message); } } else { var message = string.Format("Cannot deserialize System.Object from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
// 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) { var arraySerializationOptions = EnsureSerializationOptions<ArraySerializationOptions>(options); var itemSerializationOptions = arraySerializationOptions.ItemSerializationOptions; var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return null; case BsonType.Array: bsonReader.ReadStartArray(); var stack = new Stack(); var discriminatorConvention = BsonSerializer.LookupDiscriminatorConvention(typeof(object)); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var elementType = discriminatorConvention.GetActualType(bsonReader, typeof(object)); var serializer = BsonSerializer.LookupSerializer(elementType); var element = serializer.Deserialize(bsonReader, typeof(object), elementType, itemSerializationOptions); stack.Push(element); } bsonReader.ReadEndArray(); return stack; case BsonType.Document: bsonReader.ReadStartDocument(); bsonReader.ReadString("_t"); // skip over discriminator bsonReader.ReadName("_v"); var value = Deserialize(bsonReader, actualType, actualType, options); bsonReader.ReadEndDocument(); return value; default: var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType); throw new FileFormatException(message); } }
// 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(BsonNull)); var bsonType = bsonReader.GetCurrentBsonType(); string message; switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return BsonNull.Value; case BsonType.Document: bsonReader.ReadStartDocument(); var name = bsonReader.ReadName(); if (name == "_csharpnull" || name == "$csharpnull") { var csharpNull = bsonReader.ReadBoolean(); bsonReader.ReadEndDocument(); return csharpNull ? null : BsonNull.Value; } else { message = string.Format("Unexpected element name while deserializing a BsonNull: {0}.", name); throw new FileFormatException(message); } default: message = string.Format("Cannot deserialize BsonNull from BsonType {0}.", bsonType); throw new FileFormatException(message); } }