Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4068 was 4068, checked in by swagner, 13 years ago

Sorted usings and removed unused usings in entire solution (#1094)

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