Free cookie consent management tool by TermsFeed Policy Generator

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

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

Disable visibility checks for dynamic methods. (#1376)

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      } catch (TargetInvocationException x) {
134        throw new PersistenceException(
135          "Could not instantiate storable object: Encountered exception during constructor call",
136          x.InnerException);
137      }
138    }
139
140    /// <summary>
141    /// Populates the specified instance.
142    /// </summary>
143    /// <param name="instance">The instance.</param>
144    /// <param name="objects">The objects.</param>
145    /// <param name="type">The type.</param>
146    public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
147      var memberDict = new Dictionary<string, Tag>();
148      IEnumerator<Tag> iter = objects.GetEnumerator();
149      while (iter.MoveNext()) {
150        memberDict.Add(iter.Current.Name, iter.Current);
151      }
152      foreach (var accessor in GetStorableAccessors(instance.GetType())) {
153        if (memberDict.ContainsKey(accessor.Name)) {
154          accessor.Set(instance, memberDict[accessor.Name].Value);
155        } else if (accessor.DefaultValue != null) {
156          accessor.Set(instance, accessor.DefaultValue);
157        }
158      }
159      InvokeHook(HookType.AfterDeserialization, instance);
160    }
161
162    #endregion
163
164    #region constants & private data types
165
166    private const BindingFlags ALL_CONSTRUCTORS =
167      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
168
169    private static readonly object[] emptyArgs = new object[] { };
170    private static readonly object[] trueArgs = new object[] { true };
171
172    private sealed class HookDesignator {
173      public Type Type { get; private set; }
174      public HookType HookType { get; private set; }
175      public HookDesignator() { }
176      public HookDesignator(Type type, HookType hookType) {
177        Type = type;
178        HookType = HookType;
179      }
180    }
181
182    private sealed class AccessorListCache : Dictionary<Type, IEnumerable<DataMemberAccessor>> { }
183    private sealed class AccessorCache : Dictionary<MemberInfo, DataMemberAccessor> { }
184    private delegate object Constructor();
185
186    #endregion
187
188    #region caches
189
190    private AccessorListCache accessorListCache;
191    private AccessorCache accessorCache;
192    private Dictionary<Type, Constructor> constructorCache;
193    private Dictionary<HookDesignator, List<StorableReflection.Hook>> hookCache;
194
195    #endregion
196
197    #region attribute access
198
199    private IEnumerable<DataMemberAccessor> GetStorableAccessors(Type type) {
200      lock (accessorListCache) {
201        if (accessorListCache.ContainsKey(type))
202          return accessorListCache[type];
203        var storableMembers = StorableReflection
204          .GenerateStorableMembers(type)
205          .Select(mi => GetMemberAccessor(mi));
206        accessorListCache[type] = storableMembers;
207        return storableMembers;
208      }
209    }
210
211    private DataMemberAccessor GetMemberAccessor(StorableMemberInfo mi) {
212      lock (accessorCache) {
213        if (accessorCache.ContainsKey(mi.MemberInfo))
214          return new DataMemberAccessor(accessorCache[mi.MemberInfo], mi.DisentangledName, mi.DefaultValue);
215        DataMemberAccessor dma = new DataMemberAccessor(mi.MemberInfo, mi.DisentangledName, mi.DefaultValue);
216        accessorCache[mi.MemberInfo] = dma;
217        return dma;
218      }
219    }
220
221    private Constructor GetConstructor(Type type) {
222      lock (constructorCache) {
223        if (constructorCache.ContainsKey(type))
224          return constructorCache[type];
225        Constructor c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
226        constructorCache.Add(type, c);
227        return c;
228      }
229    }
230
231    private Constructor GetDefaultConstructor(Type type) {
232      ConstructorInfo ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
233      if (ci == null)
234        return null;
235      DynamicMethod dm = new DynamicMethod("", typeof(object), null, type, true);
236      ILGenerator ilgen = dm.GetILGenerator();
237      ilgen.Emit(OpCodes.Newobj, ci);
238      ilgen.Emit(OpCodes.Ret);
239      return (Constructor)dm.CreateDelegate(typeof(Constructor));
240    }
241
242    private Constructor FindStorableConstructor(Type type) {
243      foreach (ConstructorInfo ci in type.GetConstructors(ALL_CONSTRUCTORS)) {
244        if (ci.GetCustomAttributes(typeof(StorableConstructorAttribute), false).Length > 0) {
245          if (ci.GetParameters().Length != 1 ||
246              ci.GetParameters()[0].ParameterType != typeof(bool))
247            throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
248          DynamicMethod dm = new DynamicMethod("", typeof(object), null, type, true);
249          ILGenerator ilgen = dm.GetILGenerator();
250          ilgen.Emit(OpCodes.Ldc_I4_1); // load true
251          ilgen.Emit(OpCodes.Newobj, ci);
252          ilgen.Emit(OpCodes.Ret);
253          return (Constructor)dm.CreateDelegate(typeof(Constructor));
254        }
255      }
256      return null;
257    }
258
259    private void InvokeHook(HookType hookType, object obj) {
260      if (obj == null)
261        throw new ArgumentNullException("Cannot invoke hooks on null");
262      foreach (StorableReflection.Hook hook in GetHooks(hookType, obj.GetType())) {
263        hook(obj);
264      }
265    }
266
267    private IEnumerable<StorableReflection.Hook> GetHooks(HookType hookType, Type type) {
268      lock (hookCache) {
269        List<StorableReflection.Hook> hooks;
270        var designator = new HookDesignator(type, hookType);
271        hookCache.TryGetValue(designator, out hooks);
272        if (hooks != null)
273          return hooks;
274        hooks = new List<StorableReflection.Hook>(StorableReflection.CollectHooks(hookType, type));
275        hookCache.Add(designator, hooks);
276        return hooks;
277      }
278    }
279
280    #endregion
281
282
283
284  }
285
286}
Note: See TracBrowser for help on using the repository browser.