// 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 queue = new Queue(); 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); queue.Enqueue(element); } bsonReader.ReadEndArray(); return(queue); 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); } }
// private methods private CommandResult RunCommand(MongoConnection connection, string databaseName, IMongoCommand command) { var readerSettings = new BsonBinaryReaderSettings(); var writerSettings = new BsonBinaryWriterSettings(); var resultSerializer = BsonSerializer.LookupSerializer(typeof(CommandResult)); var commandOperation = new CommandOperation <CommandResult>( databaseName, readerSettings, writerSettings, command, QueryFlags.SlaveOk, null, // options null, // readPreference null, // serializationOptions resultSerializer); return(commandOperation.Execute(connection)); }
// 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 {1}.", 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, options)); }
/// <summary> /// Gets the value serializer. /// </summary> /// <param name="actualType">The actual type of the value.</param> /// <returns>The serializer for the value type.</returns> private IBsonSerializer GetValueSerializer(Type actualType) { // return a cached serializer when possible if (actualType == typeof(TValue)) { var serializer = _cachedValueSerializer; if (serializer == null) { // it's possible but harmless for multiple threads to do the initial lookup at the same time serializer = BsonSerializer.LookupSerializer(typeof(TValue)); _cachedValueSerializer = serializer; } return(serializer); } else { return(BsonSerializer.LookupSerializer(actualType)); } }
public void Serialize(BsonSerializationContext context, BsonSerializationArgs args, object value) { var serializer = BsonSerializer.LookupSerializer(typeof(BsonDocument)); var actualType = value?.GetType(); if (actualType == typeof(BsonDocument)) { serializer.Serialize(context, value); return; } var json = (value == null) ? "{}" : ConversionHelper.SerializeObject(value); ////var bsonDocument = BsonDocument.Parse(json); var bsonDocument = BsonSerializer.Deserialize <BsonDocument>(json); // serializer.Serialize(context, bsonDocument.AsBsonValue); }
protected T Deserialize <T>(string input) { IBsonSerializer <T> serializer = BsonSerializer.LookupSerializer <T>(); T result; using (var textReader = new StringReader(input)) using (var reader = new JsonReader(textReader)) { var context = BsonDeserializationContext.CreateRoot(reader); var args = new BsonDeserializationArgs { NominalType = typeof(T) }; result = serializer.Deserialize(context, args); } return(result); }
internal static IEnumerable <object> ReadDocumentsAs(Type documentType, string filePath, FileFormat format) { if (format == FileFormat.Auto) { format = filePath.EndsWith(".json", StringComparison.OrdinalIgnoreCase) ? FileFormat.Json : FileFormat.Bson; } var serializer = BsonSerializer.LookupSerializer(documentType); var args = new BsonDeserializationArgs(); args.NominalType = documentType; if (format == FileFormat.Json) { using (var stream = File.OpenText(filePath)) { using (var reader = new JsonReader(stream)) { var context = BsonDeserializationContext.CreateRoot(reader); while (!reader.IsAtEndOfFile()) { yield return(serializer.Deserialize(context, args)); } } } } else { using (var stream = File.OpenRead(filePath)) { long length = stream.Length; while (stream.Position < length) { using (var reader = new BsonBinaryReader(stream)) { var context = BsonDeserializationContext.CreateRoot(reader); yield return(serializer.Deserialize(context, args)); } } } } }
public void TestCreateWithNominalTypeAndObjectAndIsUpdateDocument() { var c = CreateC(); var wrapper = BsonDocumentWrapper.Create(typeof(C), c, true); Assert.AreEqual(true, wrapper.IsUpdateDocument); Assert.AreSame(BsonSerializer.LookupSerializer(typeof(C)), wrapper.Serializer); Assert.AreSame(c, wrapper.Wrapped); Assert.AreEqual(false, wrapper.IsMaterialized); wrapper = BsonDocumentWrapper.Create(typeof(C), null, true); Assert.AreEqual(true, wrapper.IsUpdateDocument); Assert.AreSame(BsonSerializer.LookupSerializer(typeof(C)), wrapper.Serializer); Assert.AreSame(null, wrapper.Wrapped); Assert.AreEqual(false, wrapper.IsMaterialized); Assert.Throws <ArgumentNullException>(() => BsonDocumentWrapper.Create(null, c, true)); }
public void RegisterSerializer_RegisterSameSerializerTwoTimesForSameType_SerializerRegisteredOnce() { // Arrange var mongoDatabaseBuilder = new MongoDatabaseBuilder(_mongoOptions); var firstSerializer = new DuplicateRegisteredSerializer(); var secondSerializer = new DuplicateRegisteredSerializer(); mongoDatabaseBuilder.RegisterSerializer <DuplicateType>(firstSerializer); mongoDatabaseBuilder.RegisterSerializer <DuplicateType>(secondSerializer); // Act mongoDatabaseBuilder.Build(); // Assert IBsonSerializer <DuplicateType> registeredSerializer = BsonSerializer.LookupSerializer <DuplicateType>(); Assert.True(registeredSerializer is DuplicateRegisteredSerializer); }
// protected methods protected override void SerializeRequest(BsonBinaryWriter bsonWriter, WriteRequest request) { var insertRequest = (InsertRequest)request; var document = insertRequest.Document; if (document == null) { throw new ArgumentException("Batch contains one or more null documents."); } var actualType = document.GetType(); IBsonSerializer serializer; if (actualType == insertRequest.NominalType && insertRequest.Serializer != null) { serializer = insertRequest.Serializer; } else { if (_cachedSerializerType != actualType) { _cachedSerializer = BsonSerializer.LookupSerializer(actualType); _cachedSerializerType = actualType; } serializer = _cachedSerializer; } var serializationOptions = insertRequest.SerializationOptions ?? DocumentSerializationOptions.SerializeIdFirstInstance; var savedCheckElementNames = bsonWriter.CheckElementNames; try { bsonWriter.PushMaxDocumentSize(MaxDocumentSize); bsonWriter.CheckElementNames = _checkElementNames; serializer.Serialize(bsonWriter, insertRequest.NominalType, document, serializationOptions); } finally { bsonWriter.PopMaxDocumentSize(); bsonWriter.CheckElementNames = savedCheckElementNames; } }
private void AddOrUpdate(Type type, IBsonSerializer serializer) { var currentSerializer = BsonSerializer.LookupSerializer(type); if (currentSerializer != null) { // remove exist var cacheFieldInfo = typeof(BsonSerializerRegistry). GetField("_cache", BindingFlags.NonPublic | BindingFlags.Instance); var _cacheTemp = cacheFieldInfo.GetValue(BsonSerializer.SerializerRegistry); var _cache = _cacheTemp as ConcurrentDictionary <Type, IBsonSerializer>; IBsonSerializer removeed; _cache.TryRemove(type, out removeed); // add my owner } BsonSerializer.RegisterSerializer(type, serializer); }
public static object GetDocumentId(object document) { // from CSharpDriver-1.9.1\source\MongoDB.Driver\MongoCollection.cs IBsonSerializer serializer = BsonSerializer.LookupSerializer(document.GetType()); IBsonIdProvider idProvider = serializer as IBsonIdProvider; if (idProvider != null) { object id; Type idNominalType; IIdGenerator idGenerator; bool hasId = idProvider.GetDocumentId(document, out id, out idNominalType, out idGenerator); if (hasId) { return(id); } } return(null); }
public void TestIdMember() { var u = new User { Id = ObjectId.Empty, FriendId = ObjectId.Empty }; var classMap = BsonClassMap.LookupClassMap(typeof(User)); var idMemberMap = classMap.IdMemberMap; Assert.AreEqual("Id", idMemberMap.MemberName); var idProvider = BsonSerializer.LookupSerializer(typeof(User)) as IBsonIdProvider; var idGenerator = BsonSerializer.LookupIdGenerator(typeof(ObjectId)); idProvider.SetDocumentId(u, idGenerator.GenerateId(null, u)); Assert.IsFalse(idGenerator.IsEmpty(u.Id)); Assert.IsTrue(idGenerator.IsEmpty(u.FriendId)); var json = u.ToJson(); }
public override void Serialize(BsonWriter bsonWriter, Type nominalType, object value, IBsonSerializationOptions options) { if (value == null) { bsonWriter.WriteNull(); } else { var actualType = value.GetType(); if (actualType == typeof(TImplementation)) { _lazyImplementationSerializer.Value.Serialize(bsonWriter, nominalType, (TImplementation)value, options); } else { var serializer = BsonSerializer.LookupSerializer(actualType); serializer.Serialize(bsonWriter, nominalType, value, options); } } }
protected string Serialize <T>(T value) { IBsonSerializer <T> serializer = BsonSerializer.LookupSerializer <T>(); string result; using (var textWriter = new StringWriter()) using (var writer = new JsonWriter(textWriter)) { var context = BsonSerializationContext.CreateRoot(writer); var args = new BsonSerializationArgs { NominalType = typeof(T) }; serializer.Serialize(context, args, value); result = textWriter.ToString(); } return(result); }
public bool TryGetMemberSerializationInfo(string memberName, out BsonSerializationInfo serializationInfo) { foreach (var memberMap in this.ValueType.GetProperties()) { if (memberMap.Name == memberName) { if (memberMap == this.CurentTypeModel.IdProperty) { memberName = MongoIdProperty; } var serializer = BsonSerializer.LookupSerializer(memberMap.PropertyType); serializationInfo = new BsonSerializationInfo(memberName, serializer, serializer.ValueType); return(true); } } serializationInfo = null; return(false); }
private static object DeserializeDocument( BsonDeserializationContext context, BsonDeserializationArgs args) { Type currentType = context.Reader .FindDocumentType(args.NominalType); IBsonSerializer serializer = BsonSerializer .LookupSerializer(currentType); BsonDeserializationContext currentContext = BsonDeserializationContext .CreateRoot(context.Reader); return(serializer.Deserialize( currentContext, new BsonDeserializationArgs { NominalType = currentType })); }
public static IEnumerable <T> FastSpool <T>(this MongoCursor <RawBsonDocument> cursor, int threads = 2) { var binaryReaderSettings = new BsonBinaryReaderSettings(); binaryReaderSettings.MaxDocumentSize = int.MaxValue; var serializer = BsonSerializer.LookupSerializer(typeof(T)); return(cursor .AsParallel().AsOrdered() .WithExecutionMode(ParallelExecutionMode.ForceParallelism) .WithDegreeOfParallelism(Math.Max(1, threads)) .Select(doc => { using (doc) { return (T)serializer.Deserialize(new BsonBinaryReader(new BsonBuffer(doc.Slice, false), binaryReaderSettings), typeof(T), null); } })); }
/***************************************************/ public override object Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { // This is where we can call the Version_Engine to return the new type string from the old on if exist BsonReaderBookmark bookmark = context.Reader.GetBookmark(); IBsonSerializer bSerializer = BsonSerializer.LookupSerializer(typeof(BsonDocument)); BsonDocument doc = bSerializer.Deserialize(context, args) as BsonDocument; BsonDocument newDoc = Versioning.Convert.ToNewVersion(doc); if (newDoc == null || newDoc.Equals(doc)) { Engine.Reflection.Compute.RecordWarning("The type " + doc["_t"] + " is unknown -> data returned as custom objects."); context.Reader.ReturnToBookmark(bookmark); IBsonSerializer customSerializer = BsonSerializer.LookupSerializer(typeof(CustomObject)); return(customSerializer.Deserialize(context, args)); } else { return(Convert.FromBson(newDoc)); } }
private void Assert <TDocument>(Expression <Func <TDocument, bool> > expression, int expectedCount, string expectedFilter) { expression = (Expression <Func <TDocument, bool> >)PartialEvaluator.EvaluatePartially(expression); var parameter = expression.Parameters.Single(); var serializer = BsonSerializer.LookupSerializer <TDocument>(); var context = TranslationContext.Create(expression, serializer); var symbol = context.CreateSymbol(parameter, serializer, isCurrent: true); context = context.WithSymbol(symbol); var filterAst = ExpressionToFilterTranslator.Translate(context, expression.Body); var renderedFilter = (BsonDocument)filterAst.Render(); renderedFilter.Should().Be(expectedFilter); var filter = new BsonDocumentFilterDefinition <C>(renderedFilter); var list = __collection.FindSync <TDocument>(filter).ToList(); list.Count.Should().Be(expectedCount); }
public static IQueryable <TEntity> SearchGeoNear <TEntity, TCoordinates>(this IMongoDbSet <TEntity> dbSet, Expression <Func <TEntity, object> > targetField, GeoJsonPoint <TCoordinates> point, Expression <Func <TEntity, object> > distanceResultField = null, double?maxDistance = null, double?minDistance = null) where TEntity : class where TCoordinates : GeoJsonCoordinates { var entitySerializer = BsonSerializer.LookupSerializer <TEntity>(); var keyExpressionField = new ExpressionFieldDefinition <TEntity>(targetField); var keyStringField = keyExpressionField.Render(entitySerializer, BsonSerializer.SerializerRegistry); var distanceFieldName = "Distance"; if (distanceResultField != null) { var distanceResultExpressionField = new ExpressionFieldDefinition <TEntity>(distanceResultField); var distanceResultStringField = distanceResultExpressionField.Render(entitySerializer, BsonSerializer.SerializerRegistry); distanceFieldName = distanceResultStringField.FieldName; } var geoNearSettings = new BsonDocument { { "near", point.ToBsonDocument() }, { "key", keyStringField.FieldName }, { "distanceField", distanceFieldName } }; if (maxDistance.HasValue) { geoNearSettings.Add("maxDistance", maxDistance.Value); } if (minDistance.HasValue) { geoNearSettings.Add("minDistance", minDistance.Value); } var stage = new BsonDocument { { "$geoNear", geoNearSettings } }; var originalProvider = dbSet.Provider as IMongoFrameworkQueryProvider <TEntity>; var provider = new MongoFrameworkQueryProvider <TEntity>(originalProvider, stage); return(new MongoFrameworkQueryable <TEntity>(provider)); }
public static AggregationExpression Translate(TranslationContext context, MemberInitExpression expression) { var classSerializer = BsonSerializer.LookupSerializer(expression.Type); if (classSerializer is IBsonDocumentSerializer documentSerializer) { var computedFields = new List <AstComputedField>(); var newExpression = expression.NewExpression; var constructorParameters = newExpression.Constructor.GetParameters(); var constructorArguments = newExpression.Arguments; for (var i = 0; i < constructorParameters.Length; i++) { var constructorParameter = constructorParameters[i]; var argumentExpression = constructorArguments[i]; var fieldName = GetFieldName(constructorParameter); var argumentTanslation = ExpressionToAggregationExpressionTranslator.Translate(context, argumentExpression); computedFields.Add(AstExpression.ComputedField(fieldName, argumentTanslation.Ast)); } foreach (var binding in expression.Bindings) { var memberAssignment = (MemberAssignment)binding; var member = memberAssignment.Member; if (!(documentSerializer.TryGetMemberSerializationInfo(member.Name, out var memberSerializationInfo))) { throw new ExpressionNotSupportedException(expression); } var elementName = memberSerializationInfo.ElementName; var valueExpression = memberAssignment.Expression; var valueTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, valueExpression); computedFields.Add(AstExpression.ComputedField(elementName, valueTranslation.Ast)); } var ast = AstExpression.ComputedDocument(computedFields); var serializer = context.KnownSerializersRegistry.GetSerializer(expression); return(new AggregationExpression(expression, ast, serializer)); } throw new ExpressionNotSupportedException(expression); }
// 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.GetCurrentBsonType(); switch (bsonType) { case BsonType.Null: bsonReader.ReadNull(); return(null); case BsonType.Array: bsonReader.ReadStartArray(); var list = (nominalType == typeof(List <T>) || nominalType.IsInterface) ? new List <T>() : (ICollection <T>)Activator.CreateInstance(nominalType); var discriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(typeof(T)); while (bsonReader.ReadBsonType() != BsonType.EndOfDocument) { var elementType = discriminatorConvention.GetActualType(bsonReader, typeof(T)); var serializer = BsonSerializer.LookupSerializer(elementType); var element = (T)serializer.Deserialize(bsonReader, typeof(T), elementType, null); list.Add(element); } bsonReader.ReadEndArray(); return(list); 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 static AggregationExpression Translate(TranslationContext context, MethodCallExpression expression) { var method = expression.Method; var arguments = expression.Arguments; if (IsStandardDeviationMethod(method, out var stddevOperator)) { if (arguments.Count == 1 || arguments.Count == 2) { var sourceExpression = arguments[0]; var sourceTranslation = ExpressionToAggregationExpressionTranslator.TranslateEnumerable(context, sourceExpression); if (arguments.Count == 2) { var selectorLambda = (LambdaExpression)arguments[1]; var selectorParameter = selectorLambda.Parameters[0]; var selectorParameterSerializer = ArraySerializerHelper.GetItemSerializer(sourceTranslation.Serializer); var selectorParameterSymbol = context.CreateSymbol(selectorParameter, selectorParameterSerializer); var selectorContext = context.WithSymbol(selectorParameterSymbol); var selectorTranslation = ExpressionToAggregationExpressionTranslator.Translate(selectorContext, selectorLambda.Body); var selectorAst = AstExpression.Map( input: sourceTranslation.Ast, @as: selectorParameterSymbol.Var, @in: selectorTranslation.Ast); var selectorResultSerializer = BsonSerializer.LookupSerializer(selectorLambda.ReturnType); sourceTranslation = new AggregationExpression(selectorLambda, selectorAst, selectorResultSerializer); } var ast = AstExpression.StdDev(stddevOperator, sourceTranslation.Ast); var serializer = BsonSerializer.LookupSerializer(expression.Type); return(new AggregationExpression(expression, ast, serializer)); } } if (SetWindowFieldsMethodToAggregationExpressionTranslator.CanTranslate(expression)) { return(SetWindowFieldsMethodToAggregationExpressionTranslator.Translate(context, expression)); } throw new ExpressionNotSupportedException(expression); }
/// <summary> /// Serializes a value. /// </summary> /// <param name="context">The serialization context.</param> /// <param name="args">The serialization args.</param> /// <param name="value">The value.</param> public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TValue value) { if (value == null) { var bsonWriter = context.Writer; bsonWriter.WriteNull(); } else { var actualType = value.GetType(); if (actualType == typeof(TValue) || args.SerializeAsNominalType) { SerializeValue(context, args, value); } else { var serializer = BsonSerializer.LookupSerializer(actualType); serializer.Serialize(context, value); } } }
public void Deserializer_should_return_expected_result(string json, int expectedX, int expectedY) { var prototype = new { CSharp2643 = true, X = 1, Y = 2 }; // use CSharp2643 as a property name to guarantee a unique anonymous type T deserialize <T>(T dummy, string value) { var serializer = BsonSerializer.LookupSerializer <T>(); using (var reader = new JsonReader(value)) { var context = BsonDeserializationContext.CreateRoot(reader); return(serializer.Deserialize(context)); } } var result = deserialize(prototype, json); result.CSharp2643.Should().BeFalse(); result.X.Should().Be(expectedX); result.Y.Should().Be(expectedY); }
// public methods public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TDocument value) { IBsonSerializer serializer; var actualType = value.GetType(); if (actualType == typeof(TDocument)) { serializer = _documentSerializer; } else { if (_cachedSerializer.ValueType != actualType) { _cachedSerializer = BsonSerializer.LookupSerializer(actualType); } serializer = _cachedSerializer; } serializer.Serialize(context, value); }
public void TestConstructorWithObject() { var c = CreateC(); var wrapper = new BsonDocumentWrapper(c); Assert.AreEqual(false, wrapper.IsUpdateDocument); Assert.AreEqual(null, wrapper.SerializationOptions); Assert.AreSame(BsonSerializer.LookupSerializer(typeof(C)), wrapper.Serializer); Assert.AreSame(typeof(C), wrapper.WrappedNominalType); Assert.AreSame(c, wrapper.WrappedObject); Assert.AreEqual(false, wrapper.IsMaterialized); wrapper = new BsonDocumentWrapper(null); Assert.AreEqual(false, wrapper.IsUpdateDocument); Assert.AreEqual(null, wrapper.SerializationOptions); Assert.AreSame(BsonSerializer.LookupSerializer(typeof(object)), wrapper.Serializer); Assert.AreSame(typeof(object), wrapper.WrappedNominalType); Assert.AreSame(null, wrapper.WrappedObject); Assert.AreEqual(false, wrapper.IsMaterialized); }
public void TestCreateGenericWithObjectAndIsUpdateDocument() { var c = CreateC(); var wrapper = BsonDocumentWrapper.Create <C>(c, true); Assert.AreEqual(true, wrapper.IsUpdateDocument); Assert.AreEqual(null, wrapper.SerializationOptions); Assert.AreSame(BsonSerializer.LookupSerializer(typeof(C)), wrapper.Serializer); Assert.AreSame(typeof(C), wrapper.WrappedNominalType); Assert.AreSame(c, wrapper.WrappedObject); Assert.AreEqual(false, wrapper.IsMaterialized); wrapper = BsonDocumentWrapper.Create <C>(null, true); Assert.AreEqual(true, wrapper.IsUpdateDocument); Assert.AreEqual(null, wrapper.SerializationOptions); Assert.AreSame(BsonSerializer.LookupSerializer(typeof(C)), wrapper.Serializer); Assert.AreSame(typeof(C), wrapper.WrappedNominalType); Assert.AreSame(null, wrapper.WrappedObject); Assert.AreEqual(false, wrapper.IsMaterialized); }
// public methods /// <summary> /// Deserializes an Image from a BsonReader. /// </summary> /// <param name="bsonReader">The BsonReader.</param> /// <param name="nominalType">The nominal type of the Image.</param> /// <param name="options">The serialization options.</param> /// <returns>An Image.</returns> public override object Deserialize(BsonReader bsonReader, Type nominalType, IBsonSerializationOptions options) { if (nominalType != typeof(Image)) { var message = string.Format("Nominal type must be Image, not {0}.", nominalType.FullName); throw new ArgumentException(message, "nominalType"); } var discriminatorConvention = BsonDefaultSerializer.LookupDiscriminatorConvention(typeof(Image)); var actualType = discriminatorConvention.GetActualType(bsonReader, typeof(Image)); if (actualType == typeof(Image)) { var message = string.Format("Unable to determine actual type of Image to deserialize."); throw new FileFormatException(message); } var serializer = BsonSerializer.LookupSerializer(actualType); return(serializer.Deserialize(bsonReader, nominalType, actualType, options)); }