Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4857 was 4806, checked in by swagner, 14 years ago

Added storable constructors in HeuristicLab.Persistence plugin (#922)

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