Free cookie consent management tool by TermsFeed Policy Generator

source: branches/DataPreprocessing/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Storable/StorableSerializer.cs @ 10085

Last change on this file since 10085 was 9456, checked in by swagner, 12 years ago

Updated copyright year and added some missing license headers (#1889)

File size: 10.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2013 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        if (accessor.Get != null)
121          yield return new Tag(accessor.Name, accessor.Get(obj));
122      }
123    }
124
125    /// <summary>
126    /// Create an instance of the object using the provided meta information.
127    /// </summary>
128    /// <param name="type">A type.</param>
129    /// <param name="metaInfo">The meta information.</param>
130    /// <returns>A fresh instance of the provided type.</returns>
131    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
132      try {
133        return GetConstructor(type)();
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 (accessor.Set != null) {
155          if (memberDict.ContainsKey(accessor.Name)) {
156            accessor.Set(instance, memberDict[accessor.Name].Value);
157          } else if (accessor.DefaultValue != null) {
158            accessor.Set(instance, accessor.DefaultValue);
159          }
160        }
161      }
162      InvokeHook(HookType.AfterDeserialization, instance);
163    }
164
165    #endregion
166
167    #region constants & private data types
168
169    private const BindingFlags ALL_CONSTRUCTORS =
170      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
171
172    private static readonly object[] emptyArgs = new object[] { };
173    private static readonly object[] trueArgs = new object[] { true };
174
175    private sealed class HookDesignator {
176      public Type Type { get; private set; }
177      public HookType HookType { get; private set; }
178      public HookDesignator() { }
179      public HookDesignator(Type type, HookType hookType) {
180        Type = type;
181        HookType = HookType;
182      }
183    }
184
185    private sealed class AccessorListCache : Dictionary<Type, IEnumerable<DataMemberAccessor>> { }
186    private sealed class AccessorCache : Dictionary<MemberInfo, DataMemberAccessor> { }
187    private delegate object Constructor();
188
189    #endregion
190
191    #region caches
192
193    private AccessorListCache accessorListCache;
194    private AccessorCache accessorCache;
195    private Dictionary<Type, Constructor> constructorCache;
196    private Dictionary<HookDesignator, List<StorableReflection.Hook>> hookCache;
197
198    #endregion
199
200    #region attribute access
201
202    private IEnumerable<DataMemberAccessor> GetStorableAccessors(Type type) {
203      lock (accessorListCache) {
204        if (accessorListCache.ContainsKey(type))
205          return accessorListCache[type];
206        var storableMembers = StorableReflection
207          .GenerateStorableMembers(type)
208          .Select(mi => GetMemberAccessor(mi));
209        accessorListCache[type] = storableMembers;
210        return storableMembers;
211      }
212    }
213
214    private DataMemberAccessor GetMemberAccessor(StorableMemberInfo mi) {
215      lock (accessorCache) {
216        if (accessorCache.ContainsKey(mi.MemberInfo))
217          return new DataMemberAccessor(accessorCache[mi.MemberInfo], mi.DisentangledName, mi.DefaultValue);
218        DataMemberAccessor dma = new DataMemberAccessor(mi.MemberInfo, mi.DisentangledName, mi.DefaultValue);
219        accessorCache[mi.MemberInfo] = dma;
220        return dma;
221      }
222    }
223
224    private Constructor GetConstructor(Type type) {
225      lock (constructorCache) {
226        if (constructorCache.ContainsKey(type))
227          return constructorCache[type];
228        Constructor c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
229        constructorCache.Add(type, c);
230        return c;
231      }
232    }
233
234    private Constructor GetDefaultConstructor(Type type) {
235      ConstructorInfo ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
236      if (ci == null)
237        return null;
238      DynamicMethod dm = new DynamicMethod("", typeof(object), null, type, true);
239      ILGenerator ilgen = dm.GetILGenerator();
240      ilgen.Emit(OpCodes.Newobj, ci);
241      ilgen.Emit(OpCodes.Ret);
242      return (Constructor)dm.CreateDelegate(typeof(Constructor));
243    }
244
245    private Constructor FindStorableConstructor(Type type) {
246      foreach (ConstructorInfo ci in type.GetConstructors(ALL_CONSTRUCTORS)) {
247        if (ci.GetCustomAttributes(typeof(StorableConstructorAttribute), false).Length > 0) {
248          if (ci.GetParameters().Length != 1 ||
249              ci.GetParameters()[0].ParameterType != typeof(bool))
250            throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
251          DynamicMethod dm = new DynamicMethod("", typeof(object), null, type, true);
252          ILGenerator ilgen = dm.GetILGenerator();
253          ilgen.Emit(OpCodes.Ldc_I4_1); // load true
254          ilgen.Emit(OpCodes.Newobj, ci);
255          ilgen.Emit(OpCodes.Ret);
256          return (Constructor)dm.CreateDelegate(typeof(Constructor));
257        }
258      }
259      return null;
260    }
261
262    private void InvokeHook(HookType hookType, object obj) {
263      if (obj == null)
264        throw new ArgumentNullException("Cannot invoke hooks on null");
265      foreach (StorableReflection.Hook hook in GetHooks(hookType, obj.GetType())) {
266        hook(obj);
267      }
268    }
269
270    private IEnumerable<StorableReflection.Hook> GetHooks(HookType hookType, Type type) {
271      lock (hookCache) {
272        List<StorableReflection.Hook> hooks;
273        var designator = new HookDesignator(type, hookType);
274        hookCache.TryGetValue(designator, out hooks);
275        if (hooks != null)
276          return hooks;
277        hooks = new List<StorableReflection.Hook>(StorableReflection.CollectHooks(hookType, type));
278        hookCache.Add(designator, hooks);
279        return hooks;
280      }
281    }
282
283    #endregion
284
285
286
287  }
288
289}
Note: See TracBrowser for help on using the repository browser.