// 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(double)); var representationSerializationOptions = EnsureSerializationOptions<RepresentationSerializationOptions>(options); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Double: return bsonReader.ReadDouble(); case BsonType.Int32: return representationSerializationOptions.ToDouble(bsonReader.ReadInt32()); case BsonType.Int64: return representationSerializationOptions.ToDouble(bsonReader.ReadInt64()); case BsonType.String: return XmlConvert.ToDouble(bsonReader.ReadString()); default: var message = string.Format("Cannot deserialize Double 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(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); } }
// 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(TimeSpan)); // support RepresentationSerializationOptions for backward compatibility var representationSerializationOptions = options as RepresentationSerializationOptions; if (representationSerializationOptions != null) { options = new TimeSpanSerializationOptions(representationSerializationOptions.Representation); } var timeSpanSerializationOptions = EnsureSerializationOptions<TimeSpanSerializationOptions>(options); BsonType bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Double: return FromDouble(bsonReader.ReadDouble(), timeSpanSerializationOptions.Units); case BsonType.Int32: return FromInt32(bsonReader.ReadInt32(), timeSpanSerializationOptions.Units); case BsonType.Int64: return FromInt64(bsonReader.ReadInt64(), timeSpanSerializationOptions.Units); case BsonType.String: return TimeSpan.Parse(bsonReader.ReadString()); // not XmlConvert.ToTimeSpan (we're using .NET's format for TimeSpan) default: var message = string.Format("Cannot deserialize TimeSpan 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, // ignored IBsonSerializationOptions options) { var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Array: return (BsonValue)BsonArraySerializer.Instance.Deserialize(bsonReader, typeof(BsonArray), options); case BsonType.Binary: return (BsonValue)BsonBinaryDataSerializer.Instance.Deserialize(bsonReader, typeof(BsonBinaryData), options); case BsonType.Boolean: return (BsonValue)BsonBooleanSerializer.Instance.Deserialize(bsonReader, typeof(BsonBoolean), options); case BsonType.DateTime: return (BsonValue)BsonDateTimeSerializer.Instance.Deserialize(bsonReader, typeof(BsonDateTime), options); case BsonType.Document: return (BsonValue)BsonDocumentSerializer.Instance.Deserialize(bsonReader, typeof(BsonDocument), options); case BsonType.Double: return (BsonValue)BsonDoubleSerializer.Instance.Deserialize(bsonReader, typeof(BsonDouble), options); case BsonType.Int32: return (BsonValue)BsonInt32Serializer.Instance.Deserialize(bsonReader, typeof(BsonInt32), options); case BsonType.Int64: return (BsonValue)BsonInt64Serializer.Instance.Deserialize(bsonReader, typeof(BsonInt64), options); case BsonType.JavaScript: return (BsonValue)BsonJavaScriptSerializer.Instance.Deserialize(bsonReader, typeof(BsonJavaScript), options); case BsonType.JavaScriptWithScope: return (BsonValue)BsonJavaScriptWithScopeSerializer.Instance.Deserialize(bsonReader, typeof(BsonJavaScriptWithScope), options); case BsonType.MaxKey: return (BsonValue)BsonMaxKeySerializer.Instance.Deserialize(bsonReader, typeof(BsonMaxKey), options); case BsonType.MinKey: return (BsonValue)BsonMinKeySerializer.Instance.Deserialize(bsonReader, typeof(BsonMinKey), options); case BsonType.Null: return (BsonValue)BsonNullSerializer.Instance.Deserialize(bsonReader, typeof(BsonNull), options); case BsonType.ObjectId: return (BsonValue)BsonObjectIdSerializer.Instance.Deserialize(bsonReader, typeof(BsonObjectId), options); case BsonType.RegularExpression: return (BsonValue)BsonRegularExpressionSerializer.Instance.Deserialize(bsonReader, typeof(BsonRegularExpression), options); case BsonType.String: return (BsonValue)BsonStringSerializer.Instance.Deserialize(bsonReader, typeof(BsonString), options); case BsonType.Symbol: return (BsonValue)BsonSymbolSerializer.Instance.Deserialize(bsonReader, typeof(BsonSymbol), options); case BsonType.Timestamp: return (BsonValue)BsonTimestampSerializer.Instance.Deserialize(bsonReader, typeof(BsonTimestamp), options); case BsonType.Undefined: return (BsonValue)BsonUndefinedSerializer.Instance.Deserialize(bsonReader, typeof(BsonUndefined), options); default: var message = string.Format("Invalid BsonType {0}.", bsonType); throw new BsonInternalException(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 Exception(message); } }
public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { int timestamp, machine, increment; short pid; bsonReader.ReadObjectId(out timestamp, out machine, out pid, out increment); return new ObjectId(timestamp, machine, pid, increment).ToString(); }
// 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(decimal)); var representationSerializationOptions = EnsureSerializationOptions<RepresentationSerializationOptions>(options); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Array: var array = (BsonArray)BsonArraySerializer.Instance.Deserialize(bsonReader, typeof(BsonArray), null); var bits = new int[4]; bits[0] = array[0].AsInt32; bits[1] = array[1].AsInt32; bits[2] = array[2].AsInt32; bits[3] = array[3].AsInt32; return new decimal(bits); case BsonType.Double: return representationSerializationOptions.ToDecimal(bsonReader.ReadDouble()); case BsonType.Int32: return representationSerializationOptions.ToDecimal(bsonReader.ReadInt32()); case BsonType.Int64: return representationSerializationOptions.ToDecimal(bsonReader.ReadInt64()); case BsonType.String: return XmlConvert.ToDecimal(bsonReader.ReadString()); default: var message = string.Format("Cannot deserialize Decimal from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { object result = CustomBsonClassMapSerializer.Instance.Deserialize(bsonReader, nominalType, actualType, options); if (result != null) EmbeddedDocumentUtility.UpdateParentReferences(result); return result; }
// 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(bool)); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Boolean: return bsonReader.ReadBoolean(); case BsonType.Double: return bsonReader.ReadDouble() != 0.0; case BsonType.Int32: return bsonReader.ReadInt32() != 0; case BsonType.Int64: return bsonReader.ReadInt64() != 0; case BsonType.Null: bsonReader.ReadNull(); return false; case BsonType.String: return XmlConvert.ToBoolean(bsonReader.ReadString().ToLower()); default: var message = string.Format("Cannot deserialize Boolean 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) { 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); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var lazyBsonArray = (LazyBsonArray)value; var slice = lazyBsonArray.Slice; if (slice == null) { BsonArraySerializer.Instance.Serialize(bsonWriter, typeof(BsonArray), lazyBsonArray, options); } else { using (var clonedSlice = slice.GetSlice(0, slice.Length)) { bsonWriter.WriteRawBsonArray(clonedSlice); } } } }
// 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 bsonType = bsonReader.CurrentBsonType; if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return null; } else if (bsonType == BsonType.Array) { bsonReader.ReadStartArray(); var list = new ArrayList(); var discriminatorConvention = BsonDefaultSerializer.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, null); list.Add(element); } bsonReader.ReadEndArray(); return list; } else { var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType); throw new FileFormatException(message); } }
public object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { object value = null; var valueType = actualType.GetConceptValueType(); if (valueType == typeof(Guid)) { var guidBytes = new byte[16]; BsonBinarySubType subType; bsonReader.ReadBinaryData (out guidBytes, out subType); value = new Guid (guidBytes); } else if (valueType == typeof(double)) value = bsonReader.ReadDouble (); else if (valueType == typeof(float)) value = (float)bsonReader.ReadDouble (); else if (valueType == typeof(Int32)) value = bsonReader.ReadInt32 (); else if (valueType == typeof(Int64)) value = bsonReader.ReadInt64 (); else if (valueType == typeof(bool)) value = bsonReader.ReadBoolean (); else if (valueType == typeof(string)) value = bsonReader.ReadString (); else if (valueType == typeof(decimal)) value = decimal.Parse (bsonReader.ReadString ()); var concept = ConceptFactory.CreateConceptInstance(actualType, value); return concept; }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options ) { if (value == null) { bsonWriter.WriteNull(); return; } var nvc = (NameValueCollection)value; bsonWriter.WriteStartArray(); foreach (var key in nvc.AllKeys) { foreach (var val in nvc.GetValues(key)) { bsonWriter.WriteStartArray(); StringSerializer.Instance.Serialize(bsonWriter, typeof(string), key, options); StringSerializer.Instance.Serialize(bsonWriter, typeof(string), val, options); bsonWriter.WriteEndArray(); } } bsonWriter.WriteEndArray(); }
public object Deserialize(global::MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { if (nominalType != typeof(TriggerKey) || actualType != typeof(TriggerKey)) { var message = string.Format("Can't deserialize a {0} from {1}.", nominalType.FullName, this.GetType().Name); throw new BsonSerializationException(message); } var bsonType = bsonReader.CurrentBsonType; if (bsonType == BsonType.Document) { TriggerKey item; bsonReader.ReadStartDocument(); item = new TriggerKey( bsonReader.ReadString("Name"), bsonReader.ReadString("Group")); bsonReader.ReadEndDocument(); return item; } else if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return null; } else { var message = string.Format("Can't deserialize a {0} from BsonType {1}.", nominalType.FullName, bsonType); throw new BsonSerializationException(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) { VerifyNominalType(nominalType); if (bsonReader.CurrentBsonType == Bson.BsonType.Null) { bsonReader.ReadNull(); return null; } else { var discriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(nominalType); var actualType = discriminatorConvention.GetActualType(bsonReader, nominalType); if (actualType != nominalType) { var serializer = BsonSerializer.LookupSerializer(actualType); if (serializer != this) { // in rare cases a concrete actualType might have a more specialized serializer return serializer.Deserialize(bsonReader, nominalType, actualType, options); } } return Deserialize(bsonReader, nominalType, actualType, options); } }
public override object Deserialize( BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options ) { var bsonType = bsonReader.GetCurrentBsonType(); if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return null; } var nvc = new NameValueCollection(); bsonReader.ReadStartArray(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { bsonReader.ReadStartArray(); var key = (string)StringSerializer.Instance.Deserialize(bsonReader, typeof(string), options); var val = (string)StringSerializer.Instance.Deserialize(bsonReader, typeof(string), options); bsonReader.ReadEndArray(); nvc.Add(key, val); } bsonReader.ReadEndArray(); return nvc; }
// 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(BsonArray)); var bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.Array: bsonReader.ReadStartArray(); var array = new BsonArray(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var value = (BsonValue)BsonValueSerializer.Instance.Deserialize(bsonReader, typeof(BsonValue), null); array.Add(value); } bsonReader.ReadEndArray(); return array; default: var message = string.Format("Cannot deserialize BsonArray from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { throw new ArgumentNullException("value"); } var wrapper = (BsonDocumentWrapper)value; if (wrapper.IsUpdateDocument) { var savedCheckElementNames = bsonWriter.CheckElementNames; var savedCheckUpdateDocument = bsonWriter.CheckUpdateDocument; try { bsonWriter.CheckElementNames = false; bsonWriter.CheckUpdateDocument = true; BsonSerializer.Serialize(bsonWriter, wrapper.WrappedNominalType, wrapper.WrappedObject, null); // TODO: wrap options also? } finally { bsonWriter.CheckElementNames = savedCheckElementNames; bsonWriter.CheckUpdateDocument = savedCheckUpdateDocument; } } else { BsonSerializer.Serialize(bsonWriter, wrapper.WrappedNominalType, wrapper.WrappedObject, null); // TODO: wrap options also? } }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var dateTimeOffset = (DateTimeOffset)value; var representationSerializationOptions = EnsureSerializationOptions<RepresentationSerializationOptions>(options); switch (representationSerializationOptions.Representation) { case BsonType.Array: bsonWriter.WriteStartArray(); bsonWriter.WriteInt64(dateTimeOffset.UtcTicks); bsonWriter.WriteInt32((int)dateTimeOffset.Offset.TotalMinutes); bsonWriter.WriteEndArray(); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", BsonUtils.ToMillisecondsSinceEpoch(dateTimeOffset.UtcDateTime)); bsonWriter.WriteInt64("Ticks", dateTimeOffset.UtcTicks); bsonWriter.WriteInt32("Offset", (int)dateTimeOffset.Offset.TotalMinutes); bsonWriter.WriteEndDocument(); break; default: var message = string.Format("'{0}' is not a valid DateTimeOffset representation.", representationSerializationOptions.Representation); throw new BsonSerializationException(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(ObjectId)); BsonType bsonType = bsonReader.GetCurrentBsonType(); switch (bsonType) { case BsonType.ObjectId: int timestamp; int machine; short pid; int increment; bsonReader.ReadObjectId(out timestamp, out machine, out pid, out increment); return new ObjectId(timestamp, machine, pid, increment); case BsonType.String: return ObjectId.Parse(bsonReader.ReadString()); default: var message = string.Format("Cannot deserialize ObjectId from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { IDictionary<string, object> obj = value as IDictionary<string, object>; if (obj == null) { bsonWriter.WriteNull(); return; } bsonWriter.WriteStartDocument(); foreach (var member in obj) { bsonWriter.WriteName(member.Key); object memberValue = member.Value; if (memberValue == null) { bsonWriter.WriteNull(); } else { nominalType = memberValue.GetType(); var serializer = BsonSerializer.LookupSerializer(nominalType); serializer.Serialize(bsonWriter, nominalType, memberValue, options); } } bsonWriter.WriteEndDocument(); }
public OXmlSimpleFieldElement _Deserialize(BsonReader bsonReader, IBsonSerializationOptions options) { OXmlSimpleFieldElement element = new OXmlSimpleFieldElement(); while (true) { BsonType bsonType = bsonReader.ReadBsonType(); if (bsonType == BsonType.EndOfDocument) break; string name = bsonReader.ReadName(); switch (name.ToLower()) { case "type": if (bsonType != BsonType.String) throw new PBException($"wrong type value {bsonType}"); string type = bsonReader.ReadString(); if (type.ToLower() != "simplefield") throw new PBException($"invalid Type {type} when deserialize OXmlSimpleFieldElement"); break; case "instruction": if (bsonType == BsonType.Null) break; if (bsonType != BsonType.String) throw new PBException($"wrong Instruction value {bsonType}"); element.Instruction = bsonReader.ReadString(); break; default: throw new PBException($"unknow SimpleField value \"{name}\""); } } return element; }
// constructors /// <summary> /// Initializes a new instance of the BsonSerializationInfo class. /// </summary> /// <param name="elementName">The element name.</param> /// <param name="serializer">The serializer.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="serializationOptions">The serialization options.</param> public BsonSerializationInfo(string elementName, IBsonSerializer serializer, Type nominalType, IBsonSerializationOptions serializationOptions) { _elementName = elementName; _serializer = serializer; _nominalType = nominalType; _serializationOptions = serializationOptions; }
/// <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 override object Deserialize( BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options ) { if (nominalType != typeof(object)) { var message = string.Format("ObjectSerializer called for nominal type {0}.", nominalType.FullName); throw new InvalidOperationException(message); } var bsonType = bsonReader.CurrentBsonType; 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 = BsonDefaultSerializer.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, null); }
// 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(IPAddress)); BsonType bsonType = bsonReader.GetCurrentBsonType(); string message; switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return null; case BsonType.String: var stringValue = bsonReader.ReadString(); IPAddress address; if (IPAddress.TryParse(stringValue, out address)) { return address; } message = string.Format("Invalid IPAddress value '{0}'.", stringValue); throw new FileFormatException(message); default: message = string.Format("Cannot deserialize IPAddress from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
public OXmlParagraphElement _Deserialize(BsonReader bsonReader, IBsonSerializationOptions options) { OXmlParagraphElement paragraph = new OXmlParagraphElement(); while (true) { BsonType bsonType = bsonReader.ReadBsonType(); if (bsonType == BsonType.EndOfDocument) break; //if (bsonType != BsonType.String) // throw new PBException("error ZStringArray cannot contain value of type {0}", bsonType); //var value = bsonReader.ReadString(); string name = bsonReader.ReadName(); switch (name.ToLower()) { case "type": if (bsonType != BsonType.String) throw new PBException($"wrong type value {bsonType}"); string type = bsonReader.ReadString(); if (type.ToLower() != "paragraph") throw new PBException($"invalid Type {type} when deserialize OXmlParagraphElement"); break; case "style": if (bsonType == BsonType.Null) break; if (bsonType != BsonType.String) throw new PBException($"wrong style value {bsonType}"); paragraph.Style = bsonReader.ReadString(); break; default: throw new PBException($"unknow Paragraph value \"{name}\""); } } return paragraph; }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); return; } var metaObject = ((IDynamicMetaObjectProvider)value).GetMetaObject(Expression.Constant(value)); var memberNames = metaObject.GetDynamicMemberNames().ToList(); if (memberNames.Count == 0) { bsonWriter.WriteNull(); return; } bsonWriter.WriteStartDocument(); foreach (var memberName in memberNames) { bsonWriter.WriteName(memberName); var memberValue = BinderHelper.GetMemberValue(value, memberName); if (memberValue == null) bsonWriter.WriteNull(); else { var memberType = memberValue.GetType(); var serializer = BsonSerializer.LookupSerializer(memberType); serializer.Serialize(bsonWriter, memberType, memberValue, options); } } bsonWriter.WriteEndDocument(); }
object IBsonSerializable.Deserialize( BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options ) { throw new InvalidOperationException(); }
public override void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options ) { var actualType = value.GetType(); VerifySerializeTypes(nominalType, actualType); var representation = (options == null) ? 0 : ((RepresentationSerializationOptions) options).Representation; switch (representation) { case 0: var underlyingTypeCode = Type.GetTypeCode(Enum.GetUnderlyingType(actualType)); if (underlyingTypeCode == TypeCode.Int64 || underlyingTypeCode == TypeCode.UInt64) { goto case BsonType.Int64; } else { goto case BsonType.Int32; } case BsonType.Int32: bsonWriter.WriteInt32(Convert.ToInt32(value)); break; case BsonType.Int64: bsonWriter.WriteInt64(Convert.ToInt64(value)); break; case BsonType.String: bsonWriter.WriteString(value.ToString()); break; default: throw new BsonInternalException("Unexpected EnumRepresentation"); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var objectId = (ObjectId)value; var representation = (options == null) ? BsonType.ObjectId : ((RepresentationSerializationOptions)options).Representation; switch (representation) { case BsonType.ObjectId: bsonWriter.WriteObjectId(objectId.Timestamp, objectId.Machine, objectId.Pid, objectId.Increment); break; case BsonType.String: bsonWriter.WriteString(objectId.ToString()); break; default: throw new BsonInternalException("Unexpected representation."); } }
public object Deserialize(global::MongoDB.Bson.IO.BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options) { CalendarWrapper item = new CalendarWrapper(); bsonReader.ReadStartDocument(); item.Name = bsonReader.ReadString("_id"); var binaryData = bsonReader.ReadBinaryData("ContentStream"); item.Calendar = (ICalendar) new BinaryFormatter().Deserialize(new MemoryStream(binaryData.Bytes)); bsonReader.ReadEndDocument(); return(item); }
public ProfiledMongoCursor(MongoCollection collection, IMongoQuery query, ReadPreference readPreference, IBsonSerializer serializer, IBsonSerializationOptions serializationOptions) : base(collection, query, readPreference, serializer, serializationOptions) { }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var state = value as State; if (state == null) { bsonWriter.WriteNull(); } else { bsonWriter.WriteString(state.Name); } }
public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { BsonType bsonType = bsonReader.CurrentBsonType; if (bsonType == BsonType.String) { string value = bsonReader.ReadString(); return(_machine.GetState(value)); } string message = string.Format("StateSerializer expects to find a String and it was {0}.", bsonType); throw new BsonSerializationException(message); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var stringValue = (string)value; var representation = (options == null) ? BsonType.String : ((RepresentationSerializationOptions)options).Representation; switch (representation) { case BsonType.ObjectId: var id = ObjectId.Parse(stringValue); bsonWriter.WriteObjectId(id.Timestamp, id.Machine, id.Pid, id.Increment); break; case BsonType.String: bsonWriter.WriteString(stringValue); break; case BsonType.Symbol: bsonWriter.WriteSymbol(stringValue); break; default: throw new BsonInternalException("Unexpected representation."); } } }
// 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(string)); var bsonType = bsonReader.CurrentBsonType; if (bsonType == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { var representation = (options == null) ? BsonType.String : ((RepresentationSerializationOptions)options).Representation; switch (representation) { case BsonType.ObjectId: int timestamp, machine, increment; short pid; bsonReader.ReadObjectId(out timestamp, out machine, out pid, out increment); var objectId = new ObjectId(timestamp, machine, pid, increment); return(objectId.ToString()); case BsonType.String: return(bsonReader.ReadString()); case BsonType.Symbol: return(bsonReader.ReadSymbol()); default: var message = string.Format("Cannot deserialize string from BsonType {0}.", bsonType); throw new FileFormatException(message); } } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var int64Value = (long)value; var representationOptions = (RepresentationSerializationOptions)options ?? defaultRepresentationOptions; switch (representationOptions.Representation) { case BsonType.Double: bsonWriter.WriteDouble(representationOptions.ToDouble(int64Value)); break; case BsonType.Int32: bsonWriter.WriteInt32(representationOptions.ToInt32(int64Value)); break; case BsonType.Int64: bsonWriter.WriteInt64(int64Value); break; case BsonType.String: bsonWriter.WriteString(XmlConvert.ToString(int64Value)); break; default: var message = string.Format("'{0}' is not a valid Int64 value.", representationOptions.Representation); throw new BsonSerializationException(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(bool)); var bsonType = bsonReader.CurrentBsonType; switch (bsonType) { case BsonType.Boolean: return(bsonReader.ReadBoolean()); case BsonType.Double: return(bsonReader.ReadDouble() != 0.0); case BsonType.Int32: return(bsonReader.ReadInt32() != 0); case BsonType.Int64: return(bsonReader.ReadInt64() != 0); case BsonType.Null: bsonReader.ReadNull(); return(false); case BsonType.String: return(XmlConvert.ToBoolean(bsonReader.ReadString().ToLower())); default: var message = string.Format("Cannot deserialize Boolean 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(ObjectId)); BsonType bsonType = bsonReader.CurrentBsonType; switch (bsonType) { case BsonType.ObjectId: int timestamp; int machine; short pid; int increment; bsonReader.ReadObjectId(out timestamp, out machine, out pid, out increment); return(new ObjectId(timestamp, machine, pid, increment)); case BsonType.String: return(ObjectId.Parse(bsonReader.ReadString())); default: var message = string.Format("Cannot deserialize ObjectId 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(Guid)); var bsonType = bsonReader.CurrentBsonType; string message; switch (bsonType) { case BsonType.Binary: byte[] bytes; BsonBinarySubType subType; GuidRepresentation guidRepresentation; bsonReader.ReadBinaryData(out bytes, out subType, out guidRepresentation); if (bytes.Length != 16) { message = string.Format("Expected length to be 16, not {0}.", bytes.Length); throw new FileFormatException(message); } if (subType != BsonBinarySubType.UuidStandard && subType != BsonBinarySubType.UuidLegacy) { message = string.Format("Expected binary sub type to be UuidStandard or UuidLegacy, not {0}.", subType); throw new FileFormatException(message); } if (guidRepresentation == GuidRepresentation.Unspecified) { throw new BsonSerializationException("GuidSerializer cannot deserialize a Guid when GuidRepresentation is Unspecified."); } return(GuidConverter.FromBytes(bytes, guidRepresentation)); case BsonType.String: return(new Guid(bsonReader.ReadString())); default: message = string.Format("Cannot deserialize Guid 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(long)); var representationOptions = (RepresentationSerializationOptions)options ?? defaultRepresentationOptions; var bsonType = bsonReader.CurrentBsonType; switch (bsonType) { case BsonType.Double: return(representationOptions.ToInt64(bsonReader.ReadDouble())); case BsonType.Int32: return(representationOptions.ToInt64(bsonReader.ReadInt32())); case BsonType.Int64: return(bsonReader.ReadInt64()); case BsonType.String: return(XmlConvert.ToInt64(bsonReader.ReadString())); default: var message = string.Format("Cannot deserialize Int64 from BsonType {0}.", bsonType); throw new FileFormatException(message); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var dateTime = (DateTime)value; var dateTimeOptions = (options == null) ? DateTimeSerializationOptions.Defaults : (DateTimeSerializationOptions)options; DateTime utcDateTime; if (dateTimeOptions.DateOnly) { if (dateTime.TimeOfDay != TimeSpan.Zero) { throw new BsonSerializationException("TimeOfDay component is not zero."); } utcDateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Utc); // not ToLocalTime } else { utcDateTime = BsonUtils.ToUniversalTime(dateTime); } var millisecondsSinceEpoch = BsonUtils.ToMillisecondsSinceEpoch(utcDateTime); switch (dateTimeOptions.Representation) { case BsonType.DateTime: bsonWriter.WriteDateTime(millisecondsSinceEpoch); break; case BsonType.Document: bsonWriter.WriteStartDocument(); bsonWriter.WriteDateTime("DateTime", millisecondsSinceEpoch); bsonWriter.WriteInt64("Ticks", utcDateTime.Ticks); bsonWriter.WriteEndDocument(); break; case BsonType.Int64: bsonWriter.WriteInt64(utcDateTime.Ticks); break; case BsonType.String: if (dateTimeOptions.DateOnly) { bsonWriter.WriteString(dateTime.ToString("yyyy-MM-dd")); } else { // we're not using XmlConvert.ToString because of bugs in Mono if (dateTime == DateTime.MinValue || dateTime == DateTime.MaxValue) { // serialize MinValue and MaxValue as Unspecified so we do NOT get the time zone offset dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Unspecified); } else if (dateTime.Kind == DateTimeKind.Unspecified) { // serialize Unspecified as Local se we get the time zone offset dateTime = DateTime.SpecifyKind(dateTime, DateTimeKind.Local); } bsonWriter.WriteString(dateTime.ToString("yyyy-MM-ddTHH:mm:ss.FFFFFFFK")); } break; default: var message = string.Format("'{0}' is not a valid representation for type DateTime.", dateTimeOptions.Representation); throw new BsonSerializationException(message); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var guid = (Guid)value; var representation = (options == null) ? BsonType.Binary : ((RepresentationSerializationOptions)options).Representation; switch (representation) { case BsonType.Binary: var writerGuidRepresentation = bsonWriter.Settings.GuidRepresentation; if (writerGuidRepresentation == GuidRepresentation.Unspecified) { throw new BsonSerializationException("GuidSerializer cannot serialize a Guid when GuidRepresentation is Unspecified."); } var bytes = GuidConverter.ToBytes(guid, writerGuidRepresentation); var subType = (writerGuidRepresentation == GuidRepresentation.Standard) ? BsonBinarySubType.UuidStandard : BsonBinarySubType.UuidLegacy; bsonWriter.WriteBinaryData(bytes, subType, writerGuidRepresentation); break; case BsonType.String: bsonWriter.WriteString(guid.ToString()); break; default: var message = string.Format("'{0}' is not a valid Guid representation.", representation); throw new BsonSerializationException(message); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var boolValue = (bool)value; var representation = (options == null) ? BsonType.Boolean : ((RepresentationSerializationOptions)options).Representation; switch (representation) { case BsonType.Boolean: bsonWriter.WriteBoolean(boolValue); break; case BsonType.Double: bsonWriter.WriteDouble(boolValue ? 1.0 : 0.0); break; case BsonType.Int32: bsonWriter.WriteInt32(boolValue ? 1 : 0); break; case BsonType.Int64: bsonWriter.WriteInt64(boolValue ? 1 : 0); break; case BsonType.String: bsonWriter.WriteString(XmlConvert.ToString(boolValue)); break; default: var message = string.Format("'{0}' is not a valid representation for type Boolean.", representation); throw new BsonSerializationException(message); } }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var doubleValue = (double)value; var representationOptions = (RepresentationSerializationOptions)options ?? defaultRepresentationOptions; switch (representationOptions.Representation) { case BsonType.Double: bsonWriter.WriteDouble(doubleValue); break; case BsonType.Int32: bsonWriter.WriteInt32(representationOptions.ToInt32(doubleValue)); break; case BsonType.Int64: bsonWriter.WriteInt64(representationOptions.ToInt64(doubleValue)); break; case BsonType.String: bsonWriter.WriteString(doubleValue.ToString("R", NumberFormatInfo.InvariantInfo)); break; default: var message = string.Format("'{0}' is not a valid representation for type Double.", representationOptions.Representation); throw new BsonSerializationException(message); } }
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { throw new NotImplementedException(); }
// 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 dateTimeOptions = (options == null) ? DateTimeSerializationOptions.Defaults : (DateTimeSerializationOptions)options; DateTime value; var bsonType = bsonReader.CurrentBsonType; 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("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 (dateTimeOptions.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 (dateTimeOptions.DateOnly) { if (value.TimeOfDay != TimeSpan.Zero) { throw new FileFormatException("TimeOfDay component for DateOnly DateTime value is not zero."); } value = DateTime.SpecifyKind(value, dateTimeOptions.Kind); // not ToLocalTime or ToUniversalTime! } else { switch (dateTimeOptions.Kind) { case DateTimeKind.Local: case DateTimeKind.Unspecified: value = BsonUtils.ToLocalTime(value, dateTimeOptions.Kind); break; case DateTimeKind.Utc: value = BsonUtils.ToUniversalTime(value); break; } } return(value); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var coordinates = (GeoJson2DProjectedCoordinates)value; bsonWriter.WriteStartArray(); bsonWriter.WriteDouble(coordinates.Easting); bsonWriter.WriteDouble(coordinates.Northing); bsonWriter.WriteEndArray(); } }
// 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) { var value = (IBsonSerializable)Activator.CreateInstance(nominalType, true); // private default constructor OK return(value.Deserialize(bsonReader, nominalType, options)); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { // when entry is null, do not throw, just write null if (value == null) { bsonWriter.WriteNull(); return; } if (_failOnSerialize) { throw new InvalidOperationException(); } bsonWriter.WriteString((string)value); }
public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options) { throw new NotImplementedException(); }
// 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(T[, , ])); var bsonType = bsonReader.CurrentBsonType; string message; switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return(null); case BsonType.Array: bsonReader.ReadStartArray(); var outerList = new List <List <List <T> > >(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { bsonReader.ReadStartArray(); var middleList = new List <List <T> >(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { bsonReader.ReadStartArray(); var innerList = new List <T>(); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var element = BsonSerializer.Deserialize <T>(bsonReader); innerList.Add(element); } bsonReader.ReadEndArray(); middleList.Add(innerList); } bsonReader.ReadEndArray(); outerList.Add(middleList); } bsonReader.ReadEndArray(); var length1 = outerList.Count; var length2 = (length1 == 0) ? 0 : outerList[0].Count; var length3 = (length2 == 0) ? 0 : outerList[0][0].Count; var array = new T[length1, length2, length3]; for (int i = 0; i < length1; i++) { var middleList = outerList[i]; if (middleList.Count != length2) { message = string.Format("Middle list {0} is of length {1} but should be of length {2}.", i, middleList.Count, length2); throw new FileFormatException(message); } for (int j = 0; j < length2; j++) { var innerList = middleList[j]; if (innerList.Count != length3) { message = string.Format("Inner list {0} is of length {1} but should be of length {2}.", j, innerList.Count, length3); throw new FileFormatException(message); } for (int k = 0; k < length3; k++) { array[i, j, k] = innerList[k]; } } } return(array); 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: message = string.Format("Can't deserialize a {0} from BsonType {1}.", actualType.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) { if (bsonReader.GetCurrentBsonType() == BsonType.Null) { bsonReader.ReadNull(); return(null); } else { bsonReader.ReadStartArray(); var easting = (double)__doubleSerializer.Deserialize(bsonReader, typeof(double), null); var northing = (double)__doubleSerializer.Deserialize(bsonReader, typeof(double), null); bsonReader.ReadEndArray(); return(new GeoJson2DProjectedCoordinates(easting, northing)); } }
public void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { var timeZoneInfo = (TimeZoneInfo)value; bsonWriter.WriteString(timeZoneInfo.Id); }
public override object Deserialize(BsonReader bsonReader, Type nominalType, Type actualType, IBsonSerializationOptions options) { // when entry is null, do not throw, just read null if (bsonReader.CurrentBsonType == MongoDB.Bson.BsonType.Null) { bsonReader.ReadNull(); return(null); } if (_failOnDeserialize) { throw new InvalidOperationException(); } return(bsonReader.ReadString()); }
/// <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 { 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)); } } }
public object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options) { return(Deserialize(bsonReader)); }
/// <summary> /// Serializes an object to a BsonWriter. /// </summary> /// <param name="bsonWriter">The BsonWriter.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="value">The object.</param> /// <param name="options">The serialization options.</param> public void Serialize( BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { // Nullable types are weird because they get boxed as their underlying value type // we can best handle that by switching the nominalType to the underlying value type // (so VerifyNominalType doesn't fail and we don't get an unnecessary discriminator) if (nominalType.IsGenericType && nominalType.GetGenericTypeDefinition() == typeof(Nullable <>)) { nominalType = nominalType.GetGenericArguments()[0]; } VerifyNominalType(nominalType); var actualType = (value == null) ? nominalType : value.GetType(); if (actualType != _classMap.ClassType) { var message = string.Format("BsonClassMapSerializer.Serialize for type {0} was called with actualType {1}.", BsonUtils.GetFriendlyTypeName(_classMap.ClassType), BsonUtils.GetFriendlyTypeName(actualType)); throw new BsonSerializationException(message); } var documentSerializationOptions = (options ?? DocumentSerializationOptions.Defaults) as DocumentSerializationOptions; if (documentSerializationOptions == null) { var message = string.Format( "Serializer BsonClassMapSerializer expected serialization options of type {0}, not {1}.", BsonUtils.GetFriendlyTypeName(typeof(DocumentSerializationOptions)), BsonUtils.GetFriendlyTypeName(options.GetType())); throw new BsonSerializationException(message); } bsonWriter.WriteStartDocument(); BsonMemberMap idMemberMap = null; if (documentSerializationOptions.SerializeIdFirst) { idMemberMap = _classMap.IdMemberMap; if (idMemberMap != null) { SerializeMember(bsonWriter, value, idMemberMap); } } if (actualType != nominalType || _classMap.DiscriminatorIsRequired || _classMap.HasRootClass) { // never write out a discriminator for an anonymous class if (!_classMap.IsAnonymous) { var discriminatorConvention = _classMap.GetDiscriminatorConvention(); var discriminator = discriminatorConvention.GetDiscriminator(nominalType, actualType); if (discriminator != null) { bsonWriter.WriteName(discriminatorConvention.ElementName); BsonValueSerializer.Instance.Serialize(bsonWriter, typeof(BsonValue), discriminator, null); } } } var allMemberMaps = _classMap.AllMemberMaps; var extraElementsMemberMapIndex = _classMap.ExtraElementsMemberMapIndex; for (var memberMapIndex = 0; memberMapIndex < allMemberMaps.Count; ++memberMapIndex) { var memberMap = allMemberMaps[memberMapIndex]; // note: if serializeIdFirst is false then idMemberMap will be null (so no property will be skipped) if (memberMap != idMemberMap) { if (memberMapIndex != extraElementsMemberMapIndex) { SerializeMember(bsonWriter, value, memberMap); } else { SerializeExtraElements(bsonWriter, value, memberMap); } } } bsonWriter.WriteEndDocument(); } }
// protected /// <summary> /// Serializes the result of the builder to a BsonWriter. /// </summary> /// <param name="bsonWriter">The writer.</param> /// <param name="nominalType">The nominal type.</param> /// <param name="options">The serialization options.</param> protected override void Serialize(BsonWriter bsonWriter, Type nominalType, IBsonSerializationOptions options) { BsonDocumentSerializer.Instance.Serialize(bsonWriter, nominalType, _document, options); }