Free cookie consent management tool by TermsFeed Policy Generator

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

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

Updated year of copyrights (#1406)

File size: 10.8 KB
RevLine 
[3742]1#region License Information
2/* HeuristicLab
[5445]3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[3742]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
[4175]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    }
[4806]49    [StorableConstructor]
50    private StorableSerializer(bool deserializing) : this() { }
[4175]51
[3025]52    #region ICompositeSerializer implementation
53
[3036]54    /// <summary>
55    /// Priority 200, one of the first default composite serializers to try.
56    /// </summary>
57    /// <value></value>
[1623]58    public int Priority {
59      get { return 200; }
60    }
61
[3036]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>
[1823]69    public bool CanSerialize(Type type) {
[3577]70      bool markedStorable = StorableReflection.HasStorableClassAttribute(type);
[3553]71      if (GetConstructor(type) == null)
[3577]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;
[1623]82    }
83
[3036]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>
[2993]92    public string JustifyRejection(Type type) {
[3577]93      StringBuilder sb = new StringBuilder();
[3553]94      if (GetConstructor(type) == null)
[3577]95        sb.Append("class has no default constructor and no [StorableConstructor]");
[3029]96      if (!StorableReflection.IsEmptyOrStorableType(type, true))
[4068]97        sb.Append("class (or one of its bases) is not empty and not marked [Storable]; ");
[3577]98      return sb.ToString();
[2993]99    }
100
[3036]101    /// <summary>
102    /// Creates the meta info.
103    /// </summary>
104    /// <param name="o">The object.</param>
105    /// <returns>A list of storable components.</returns>
[1623]106    public IEnumerable<Tag> CreateMetaInfo(object o) {
[3031]107      InvokeHook(HookType.BeforeSerialization, o);
[1623]108      return new Tag[] { };
109    }
110
[3036]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>
[1623]118    public IEnumerable<Tag> Decompose(object obj) {
[3913]119      foreach (var accessor in GetStorableAccessors(obj.GetType())) {
[5324]120        if (accessor.Get != null)
121          yield return new Tag(accessor.Name, accessor.Get(obj));
[1623]122      }
123    }
124
[3036]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>
[1623]131    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
[2990]132      try {
[3553]133        return GetConstructor(type)();
[5292]134      } catch (TargetInvocationException x) {
[2990]135        throw new PersistenceException(
136          "Could not instantiate storable object: Encountered exception during constructor call",
137          x.InnerException);
138      }
[1623]139    }
140
[3036]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>
[1623]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);
[3029]152      }
[3913]153      foreach (var accessor in GetStorableAccessors(instance.GetType())) {
[5324]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          }
[1623]160        }
161      }
[3031]162      InvokeHook(HookType.AfterDeserialization, instance);
[1623]163    }
[3025]164
165    #endregion
166
[3029]167    #region constants & private data types
[3025]168
169    private const BindingFlags ALL_CONSTRUCTORS =
170      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
171
[3031]172    private static readonly object[] emptyArgs = new object[] { };
[3913]173    private static readonly object[] trueArgs = new object[] { true };
[3031]174
[3553]175    private sealed class HookDesignator {
[3025]176      public Type Type { get; private set; }
[3553]177      public HookType HookType { get; private set; }
[3031]178      public HookDesignator() { }
179      public HookDesignator(Type type, HookType hookType) {
180        Type = type;
181        HookType = HookType;
182      }
183    }
184
[3913]185    private sealed class AccessorListCache : Dictionary<Type, IEnumerable<DataMemberAccessor>> { }
186    private sealed class AccessorCache : Dictionary<MemberInfo, DataMemberAccessor> { }
[4175]187    private delegate object Constructor();
[3025]188
189    #endregion
190
191    #region caches
192
[4175]193    private AccessorListCache accessorListCache;
194    private AccessorCache accessorCache;
195    private Dictionary<Type, Constructor> constructorCache;
196    private Dictionary<HookDesignator, List<StorableReflection.Hook>> hookCache;
[3025]197
198    #endregion
199
[3029]200    #region attribute access
[3025]201
[3913]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;
[4068]211      }
[3913]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;
[3025]221      }
[3553]222    }
[3025]223
[3553]224    private Constructor GetConstructor(Type type) {
[3025]225      lock (constructorCache) {
226        if (constructorCache.ContainsKey(type))
227          return constructorCache[type];
[3553]228        Constructor c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
229        constructorCache.Add(type, c);
230        return c;
231      }
[4068]232    }
[3553]233
234    private Constructor GetDefaultConstructor(Type type) {
235      ConstructorInfo ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
236      if (ci == null)
[4068]237        return null;
[5292]238      DynamicMethod dm = new DynamicMethod("", typeof(object), null, type, true);
[3553]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))
[4068]250            throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
[5292]251          DynamicMethod dm = new DynamicMethod("", typeof(object), null, type, true);
[3553]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));
[3025]257        }
258      }
[3553]259      return null;
[4068]260    }
[3025]261
[3031]262    private void InvokeHook(HookType hookType, object obj) {
263      if (obj == null)
264        throw new ArgumentNullException("Cannot invoke hooks on null");
[3553]265      foreach (StorableReflection.Hook hook in GetHooks(hookType, obj.GetType())) {
266        hook(obj);
[3031]267      }
268    }
269
[3553]270    private IEnumerable<StorableReflection.Hook> GetHooks(HookType hookType, Type type) {
[3031]271      lock (hookCache) {
[3553]272        List<StorableReflection.Hook> hooks;
[3031]273        var designator = new HookDesignator(type, hookType);
274        hookCache.TryGetValue(designator, out hooks);
275        if (hooks != null)
276          return hooks;
[3553]277        hooks = new List<StorableReflection.Hook>(StorableReflection.CollectHooks(hookType, type));
[3031]278        hookCache.Add(designator, hooks);
279        return hooks;
280      }
281    }
282
[3025]283    #endregion
[3031]284
[3553]285
286
[1623]287  }
[3553]288
[2980]289}
Note: See TracBrowser for help on using the repository browser.