Line data Source code
1 : using System;
2 : using System.Collections.Generic;
3 : using System.Linq;
4 : using System.Reflection;
5 : using MongoDB.Bson;
6 : using MongoDB.Bson.IO;
7 : using MongoDB.Bson.Serialization;
8 : using MongoDB.Bson.Serialization.Serializers;
9 :
10 : namespace Cqrs.MongoDB.Serialisers
11 : {
12 : public class BasicStructSerialiser<TStruct> : StructSerializerBase<TStruct>
13 : where TStruct : struct
14 0 : {
15 0 : public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TStruct value)
16 : {
17 : Type nominalType = args.NominalType;
18 : FieldInfo[] fields = nominalType.GetFields(BindingFlags.Instance | BindingFlags.Public);
19 : PropertyInfo[] propsAll = nominalType.GetProperties(BindingFlags.Instance | BindingFlags.Public);
20 :
21 : IEnumerable<PropertyInfo> props = propsAll.Where(prop => prop.CanWrite).ToList();
22 :
23 : IBsonWriter bsonWriter = context.Writer;
24 :
25 : bsonWriter.WriteStartDocument();
26 :
27 : foreach (FieldInfo field in fields)
28 : {
29 : bsonWriter.WriteName(field.Name);
30 : BsonSerializer.Serialize(bsonWriter, field.FieldType, field.GetValue(value));
31 : }
32 : foreach (PropertyInfo prop in props)
33 : {
34 : bsonWriter.WriteName(prop.Name);
35 : BsonSerializer.Serialize(bsonWriter, prop.PropertyType, prop.GetValue(value, null));
36 : }
37 :
38 : bsonWriter.WriteEndDocument();
39 : }
40 :
41 0 : public override TStruct Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
42 : {
43 : //boxing is required for SetValue to work
44 : var obj = (object)(new TStruct());
45 : Type actualType = args.NominalType;
46 : IBsonReader bsonReader = context.Reader;
47 :
48 : bsonReader.ReadStartDocument();
49 :
50 : while (bsonReader.ReadBsonType() != BsonType.EndOfDocument)
51 : {
52 : var name = bsonReader.ReadName();
53 :
54 : var field = actualType.GetField(name);
55 : if (field != null)
56 : {
57 : var value = BsonSerializer.Deserialize(bsonReader, field.FieldType);
58 : field.SetValue(obj, value);
59 : }
60 :
61 : var prop = actualType.GetProperty(name);
62 : if (prop != null)
63 : {
64 : var value = BsonSerializer.Deserialize(bsonReader, prop.PropertyType);
65 : prop.SetValue(obj, value, null);
66 : }
67 : }
68 :
69 : bsonReader.ReadEndDocument();
70 :
71 : return (TStruct)obj;
72 : }
73 : }
74 : }
|