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, 14 years ago

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

File size: 10.5 KB
RevLine 
[3742]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;
[1623]23using System.Collections.Generic;
24using System.Linq;
[1705]25using System.Reflection;
[4068]26using System.Reflection.Emit;
[3025]27using System.Text;
[4068]28using HeuristicLab.Persistence.Core;
29using HeuristicLab.Persistence.Interfaces;
[1623]30
[1823]31namespace HeuristicLab.Persistence.Default.CompositeSerializers.Storable {
[1623]32
[2994]33  /// <summary>
34  /// Intended for serialization of all custom classes. Classes should have the
[3029]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>.
[2994]39  /// </summary>
[3029]40  [StorableClass]
[3036]41  public sealed class StorableSerializer : ICompositeSerializer {
[1623]42
[3025]43    #region ICompositeSerializer implementation
44
[3036]45    /// <summary>
46    /// Priority 200, one of the first default composite serializers to try.
47    /// </summary>
48    /// <value></value>
[1623]49    public int Priority {
50      get { return 200; }
51    }
52
[3036]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>
[1823]60    public bool CanSerialize(Type type) {
[3577]61      bool markedStorable = StorableReflection.HasStorableClassAttribute(type);
[3553]62      if (GetConstructor(type) == null)
[3577]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;
[1623]73    }
74
[3036]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>
[2993]83    public string JustifyRejection(Type type) {
[3577]84      StringBuilder sb = new StringBuilder();
[3553]85      if (GetConstructor(type) == null)
[3577]86        sb.Append("class has no default constructor and no [StorableConstructor]");
[3029]87      if (!StorableReflection.IsEmptyOrStorableType(type, true))
[4068]88        sb.Append("class (or one of its bases) is not empty and not marked [Storable]; ");
[3577]89      return sb.ToString();
[2993]90    }
91
[3036]92    /// <summary>
93    /// Creates the meta info.
94    /// </summary>
95    /// <param name="o">The object.</param>
96    /// <returns>A list of storable components.</returns>
[1623]97    public IEnumerable<Tag> CreateMetaInfo(object o) {
[3031]98      InvokeHook(HookType.BeforeSerialization, o);
[1623]99      return new Tag[] { };
100    }
101
[3036]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>
[1623]109    public IEnumerable<Tag> Decompose(object obj) {
[3913]110      foreach (var accessor in GetStorableAccessors(obj.GetType())) {
111        yield return new Tag(accessor.Name, accessor.Get(obj));
[1623]112      }
113    }
114
[3036]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>
[1623]121    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
[2990]122      try {
[3553]123        return GetConstructor(type)();
[4068]124      }
125      catch (TargetInvocationException x) {
[2990]126        throw new PersistenceException(
127          "Could not instantiate storable object: Encountered exception during constructor call",
128          x.InnerException);
129      }
[1623]130    }
131
[3036]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>
[1623]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);
[3029]143      }
[3913]144      foreach (var accessor in GetStorableAccessors(instance.GetType())) {
[1960]145        if (memberDict.ContainsKey(accessor.Name)) {
[3913]146          accessor.Set(instance, memberDict[accessor.Name].Value);
[1960]147        } else if (accessor.DefaultValue != null) {
[3913]148          accessor.Set(instance, accessor.DefaultValue);
[1623]149        }
150      }
[3031]151      InvokeHook(HookType.AfterDeserialization, instance);
[1623]152    }
[3025]153
154    #endregion
155
[3029]156    #region constants & private data types
[3025]157
158    private const BindingFlags ALL_CONSTRUCTORS =
159      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
160
[3031]161    private static readonly object[] emptyArgs = new object[] { };
[3913]162    private static readonly object[] trueArgs = new object[] { true };
[3031]163
[3553]164    private sealed class HookDesignator {
[3025]165      public Type Type { get; private set; }
[3553]166      public HookType HookType { get; private set; }
[3031]167      public HookDesignator() { }
168      public HookDesignator(Type type, HookType hookType) {
169        Type = type;
170        HookType = HookType;
171      }
172    }
173
[3913]174    private sealed class AccessorListCache : Dictionary<Type, IEnumerable<DataMemberAccessor>> { }
175    private sealed class AccessorCache : Dictionary<MemberInfo, DataMemberAccessor> { }
[3025]176
177    #endregion
178
179    #region caches
180
[3913]181    private AccessorListCache accessorListCache = new AccessorListCache();
182    private AccessorCache accessorCache = new AccessorCache();
[3025]183
[3553]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 =
[4068]190      new Dictionary<HookDesignator, List<StorableReflection.Hook>>();
[3553]191
[3025]192    #endregion
193
[3029]194    #region attribute access
[3025]195
[3913]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;
[4068]205      }
[3913]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;
[3025]215      }
[3553]216    }
[3025]217
[3553]218    private Constructor GetConstructor(Type type) {
[3025]219      lock (constructorCache) {
220        if (constructorCache.ContainsKey(type))
221          return constructorCache[type];
[3553]222        Constructor c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
223        constructorCache.Add(type, c);
224        return c;
225      }
[4068]226    }
[3553]227
228    private Constructor GetDefaultConstructor(Type type) {
229      ConstructorInfo ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
230      if (ci == null)
[4068]231        return null;
[3553]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))
[4068]244            throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
[3553]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));
[3025]251        }
252      }
[3553]253      return null;
[4068]254    }
[3025]255
[3031]256    private void InvokeHook(HookType hookType, object obj) {
257      if (obj == null)
258        throw new ArgumentNullException("Cannot invoke hooks on null");
[3553]259      foreach (StorableReflection.Hook hook in GetHooks(hookType, obj.GetType())) {
260        hook(obj);
[3031]261      }
262    }
263
[3553]264    private IEnumerable<StorableReflection.Hook> GetHooks(HookType hookType, Type type) {
[3031]265      lock (hookCache) {
[3553]266        List<StorableReflection.Hook> hooks;
[3031]267        var designator = new HookDesignator(type, hookType);
268        hookCache.TryGetValue(designator, out hooks);
269        if (hooks != null)
270          return hooks;
[3553]271        hooks = new List<StorableReflection.Hook>(StorableReflection.CollectHooks(hookType, type));
[3031]272        hookCache.Add(designator, hooks);
273        return hooks;
274      }
275    }
276
[3025]277    #endregion
[3031]278
[3553]279
280
[1623]281  }
[3553]282
[2980]283}
Note: See TracBrowser for help on using the repository browser.