Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Storable/StorableSerializer.cs @ 3577

Last change on this file since 3577 was 3577, checked in by epitzer, 14 years ago

throw Exception if class is marked [Storable] but cannot be serialized with the StorableSerializer (#548)

File size: 9.2 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using HeuristicLab.Persistence.Interfaces;
5using HeuristicLab.Persistence.Core;
6using System.Reflection;
7using HeuristicLab.Persistence.Auxiliary;
8using System.Text;
9using System.Reflection.Emit;
10
11namespace HeuristicLab.Persistence.Default.CompositeSerializers.Storable {
12
13  /// <summary>
14  /// Intended for serialization of all custom classes. Classes should have the
15  /// <c>[StorableClass]</c> attribute set. The default mode is to serialize
16  /// members with the <c>[Storable]</c> attribute set. Alternatively the
17  /// storable mode can be set to <c>AllFields</c>, <c>AllProperties</c>
18  /// or <c>AllFieldsAndAllProperties</c>.
19  /// </summary>
20  [StorableClass]
21  public sealed class StorableSerializer : ICompositeSerializer {
22
23    #region ICompositeSerializer implementation
24
25    /// <summary>
26    /// Priority 200, one of the first default composite serializers to try.
27    /// </summary>
28    /// <value></value>
29    public int Priority {
30      get { return 200; }
31    }
32
33    /// <summary>
34    /// Determines for every type whether the composite serializer is applicable.
35    /// </summary>
36    /// <param name="type">The type.</param>
37    /// <returns>
38    ///   <c>true</c> if this instance can serialize the specified type; otherwise, <c>false</c>.
39    /// </returns>
40    public bool CanSerialize(Type type) {
41      bool markedStorable = StorableReflection.HasStorableClassAttribute(type);
42      if (GetConstructor(type) == null)
43        if (markedStorable)
44          throw new Exception("[Storable] type has no default constructor and no [StorableConstructor]");
45        else
46          return false;
47      if (!StorableReflection.IsEmptyOrStorableType(type, true))
48        if (markedStorable)
49          throw new Exception("[Storable] type has non emtpy, non [Storable] base classes");
50        else
51          return false;
52      return true;
53    }
54
55    /// <summary>
56    /// Give a reason if possibly why the given type cannot be serialized by this
57    /// ICompositeSerializer.
58    /// </summary>
59    /// <param name="type">The type.</param>
60    /// <returns>
61    /// A string justifying why type cannot be serialized.
62    /// </returns>
63    public string JustifyRejection(Type type) {
64      StringBuilder sb = new StringBuilder();
65      if (GetConstructor(type) == null)
66        sb.Append("class has no default constructor and no [StorableConstructor]");
67      if (!StorableReflection.IsEmptyOrStorableType(type, true))
68        sb.Append("class (or one of its bases) is not empty and not marked [Storable]; ");     
69      return sb.ToString();
70    }
71
72    /// <summary>
73    /// Creates the meta info.
74    /// </summary>
75    /// <param name="o">The object.</param>
76    /// <returns>A list of storable components.</returns>
77    public IEnumerable<Tag> CreateMetaInfo(object o) {
78      InvokeHook(HookType.BeforeSerialization, o);
79      return new Tag[] { };
80    }
81
82    /// <summary>
83    /// Decompose an object into <see cref="Tag"/>s, the tag name can be null,
84    /// the order in which elements are generated is guaranteed to be
85    /// the same as they will be supplied to the Populate method.
86    /// </summary>
87    /// <param name="obj">An object.</param>
88    /// <returns>An enumerable of <see cref="Tag"/>s.</returns>
89    public IEnumerable<Tag> Decompose(object obj) {
90      foreach (var accessor in GetStorableAccessors(obj)) {
91        yield return new Tag(accessor.Name, accessor.Get());
92      }
93    }
94
95    /// <summary>
96    /// Create an instance of the object using the provided meta information.
97    /// </summary>
98    /// <param name="type">A type.</param>
99    /// <param name="metaInfo">The meta information.</param>
100    /// <returns>A fresh instance of the provided type.</returns>
101    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
102      try {
103        return GetConstructor(type)();
104      } catch (TargetInvocationException x) {
105        throw new PersistenceException(
106          "Could not instantiate storable object: Encountered exception during constructor call",
107          x.InnerException);
108      }
109    }
110
111    /// <summary>
112    /// Populates the specified instance.
113    /// </summary>
114    /// <param name="instance">The instance.</param>
115    /// <param name="objects">The objects.</param>
116    /// <param name="type">The type.</param>
117    public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
118      var memberDict = new Dictionary<string, Tag>();
119      IEnumerator<Tag> iter = objects.GetEnumerator();
120      while (iter.MoveNext()) {
121        memberDict.Add(iter.Current.Name, iter.Current);
122      }
123      foreach (var accessor in GetStorableAccessors(instance)) {
124        if (memberDict.ContainsKey(accessor.Name)) {
125          accessor.Set(memberDict[accessor.Name].Value);
126        } else if (accessor.DefaultValue != null) {
127          accessor.Set(accessor.DefaultValue);
128        }
129      }
130      InvokeHook(HookType.AfterDeserialization, instance);
131    }
132
133    #endregion
134
135    #region constants & private data types
136
137    private const BindingFlags ALL_CONSTRUCTORS =
138      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
139
140    private static readonly object[] emptyArgs = new object[] { };
141
142    private sealed class HookDesignator {
143      public Type Type { get; private set; }
144      public HookType HookType { get; private set; }
145      public HookDesignator() { }
146      public HookDesignator(Type type, HookType hookType) {
147        Type = type;
148        HookType = HookType;
149      }
150    }
151
152    private sealed class MemberCache : Dictionary<Type, IEnumerable<StorableMemberInfo>> { }
153
154    #endregion
155
156    #region caches
157
158    private MemberCache storableMemberCache = new MemberCache();
159
160    private delegate object Constructor();
161
162    private Dictionary<Type, Constructor> constructorCache =
163      new Dictionary<Type, Constructor>();
164
165    private Dictionary<HookDesignator, List<StorableReflection.Hook>> hookCache =
166      new Dictionary<HookDesignator, List<StorableReflection.Hook>>();   
167
168    #endregion
169
170    #region attribute access
171
172    private IEnumerable<StorableMemberInfo> GetStorableMembers(Type type) {
173      lock (storableMemberCache) {
174        if (storableMemberCache.ContainsKey(type))
175          return storableMemberCache[type];
176        var storablesMembers = StorableReflection.GenerateStorableMembers(type);
177        storableMemberCache[type] = storablesMembers;
178        return storablesMembers;
179      }
180    }
181
182    private Constructor GetConstructor(Type type) {
183      lock (constructorCache) {
184        if (constructorCache.ContainsKey(type))
185          return constructorCache[type];
186        Constructor c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
187        constructorCache.Add(type, c);
188        return c;
189      }
190    }
191
192    private Constructor GetDefaultConstructor(Type type) {
193      ConstructorInfo ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
194      if (ci == null)
195        return null;
196      DynamicMethod dm = new DynamicMethod("", typeof(object), null, type);
197      ILGenerator ilgen = dm.GetILGenerator();
198      ilgen.Emit(OpCodes.Newobj, ci);
199      ilgen.Emit(OpCodes.Ret);
200      return (Constructor)dm.CreateDelegate(typeof(Constructor));
201    }
202
203    private Constructor FindStorableConstructor(Type type) {
204      foreach (ConstructorInfo ci in type.GetConstructors(ALL_CONSTRUCTORS)) {
205        if (ci.GetCustomAttributes(typeof(StorableConstructorAttribute), false).Length > 0) {
206          if (ci.GetParameters().Length != 1 ||
207              ci.GetParameters()[0].ParameterType != typeof(bool))
208            throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
209          DynamicMethod dm = new DynamicMethod("", typeof(object), null, type);
210          ILGenerator ilgen = dm.GetILGenerator();
211          ilgen.Emit(OpCodes.Ldc_I4_1); // load true
212          ilgen.Emit(OpCodes.Newobj, ci);
213          ilgen.Emit(OpCodes.Ret);
214          return (Constructor)dm.CreateDelegate(typeof(Constructor));
215        }
216      }
217      return null;
218    }
219
220    private IEnumerable<DataMemberAccessor> GetStorableAccessors(object obj) {
221      return GetStorableMembers(obj.GetType())
222        .Select(mi => new DataMemberAccessor(mi.MemberInfo, mi.DisentangledName, mi.DefaultValue, obj));
223    }
224
225    private void InvokeHook(HookType hookType, object obj) {
226      if (obj == null)
227        throw new ArgumentNullException("Cannot invoke hooks on null");
228      foreach (StorableReflection.Hook hook in GetHooks(hookType, obj.GetType())) {
229        hook(obj);
230      }
231    }
232
233    private IEnumerable<StorableReflection.Hook> GetHooks(HookType hookType, Type type) {
234      lock (hookCache) {
235        List<StorableReflection.Hook> hooks;
236        var designator = new HookDesignator(type, hookType);
237        hookCache.TryGetValue(designator, out hooks);
238        if (hooks != null)
239          return hooks;
240        hooks = new List<StorableReflection.Hook>(StorableReflection.CollectHooks(hookType, type));
241        hookCache.Add(designator, hooks);
242        return hooks;
243      }
244    }
245
246    #endregion
247
248
249
250  }
251
252}
Note: See TracBrowser for help on using the repository browser.