Line data Source code
1 : #region Copyright
2 : // // -----------------------------------------------------------------------
3 : // // <copyright company="Chinchilla Software Limited">
4 : // // Copyright Chinchilla Software Limited. All rights reserved.
5 : // // </copyright>
6 : // // -----------------------------------------------------------------------
7 : #endregion
8 :
9 : using System;
10 : using MongoDB.Bson;
11 : using MongoDB.Bson.IO;
12 : using MongoDB.Bson.Serialization;
13 :
14 : namespace Cqrs.Mongo.Serialisers
15 : {
16 : /// <summary>
17 : /// A <see cref="IBsonSerializer"/> that stores <see cref="Type"/> information as well.
18 : /// </summary>
19 : public class TypeSerialiser : IBsonSerializer
20 1 : {
21 : /// <summary>
22 : /// Deserialises a <see cref="Type"/> value, first reading the <see cref="Type"/> information from the provide <paramref name="reader"/>.
23 : /// </summary>
24 1 : public object Deserialize(BsonReader reader, Type nominalType, IBsonSerializationOptions options)
25 : {
26 : var actualType = nominalType;
27 : return Deserialize(reader, nominalType, actualType, options);
28 : }
29 :
30 : /// <summary>
31 : /// Deserialises a <see cref="Type"/> value, first reading the <see cref="Type"/> information from the provide <paramref name="reader"/>.
32 : /// </summary>
33 1 : public object Deserialize(BsonReader reader, Type nominalType, Type actualType, IBsonSerializationOptions options)
34 : {
35 : if (reader.CurrentBsonType == BsonType.Null)
36 : {
37 : return null;
38 : }
39 : string assemblyQualifiedName = reader.ReadString();
40 : return Type.GetType(assemblyQualifiedName);
41 : }
42 :
43 : /// <summary>
44 : /// Gets the default serialization options for this serializer.
45 : /// </summary>
46 : /// <returns>
47 : /// The default serialization options for this serializer.
48 : /// </returns>
49 1 : public IBsonSerializationOptions GetDefaultSerializationOptions()
50 : {
51 : return null;
52 : }
53 :
54 : /// <summary>
55 : /// Serialises a <see cref="Type"/> value.
56 : /// </summary>
57 1 : public void Serialize(BsonWriter writer, Type nominalType, object value, IBsonSerializationOptions options)
58 : {
59 : if (value == null)
60 : {
61 : writer.WriteNull();
62 : }
63 : else
64 : {
65 : writer.WriteString(((Type)value).AssemblyQualifiedName);
66 : }
67 : }
68 : }
69 : }
|