[1623] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
| 3 | using System.Linq;
|
---|
| 4 | using HeuristicLab.Persistence.Interfaces;
|
---|
| 5 | using HeuristicLab.Persistence.Core;
|
---|
[1705] | 6 | using System.Reflection;
|
---|
| 7 | using HeuristicLab.Persistence.Auxiliary;
|
---|
[3025] | 8 | using System.Text;
|
---|
[3553] | 9 | using System.Reflection.Emit;
|
---|
[1623] | 10 |
|
---|
[1823] | 11 | namespace HeuristicLab.Persistence.Default.CompositeSerializers.Storable {
|
---|
[1623] | 12 |
|
---|
[2994] | 13 | /// <summary>
|
---|
| 14 | /// Intended for serialization of all custom classes. Classes should have the
|
---|
[3029] | 15 | /// <c>[StorableClass]</c> attribute set. The default mode is to serialize
|
---|
| 16 | /// members with the <c>[Storable]</c> attribute set. Alternatively the
|
---|
| 17 | /// storable mode can be set to <c>AllFields</c>, <c>AllProperties</c>
|
---|
| 18 | /// or <c>AllFieldsAndAllProperties</c>.
|
---|
[2994] | 19 | /// </summary>
|
---|
[3029] | 20 | [StorableClass]
|
---|
[3036] | 21 | public sealed class StorableSerializer : ICompositeSerializer {
|
---|
[1623] | 22 |
|
---|
[3025] | 23 | #region ICompositeSerializer implementation
|
---|
| 24 |
|
---|
[3036] | 25 | /// <summary>
|
---|
| 26 | /// Priority 200, one of the first default composite serializers to try.
|
---|
| 27 | /// </summary>
|
---|
| 28 | /// <value></value>
|
---|
[1623] | 29 | public int Priority {
|
---|
| 30 | get { return 200; }
|
---|
| 31 | }
|
---|
| 32 |
|
---|
[3036] | 33 | /// <summary>
|
---|
| 34 | /// Determines for every type whether the composite serializer is applicable.
|
---|
| 35 | /// </summary>
|
---|
| 36 | /// <param name="type">The type.</param>
|
---|
| 37 | /// <returns>
|
---|
| 38 | /// <c>true</c> if this instance can serialize the specified type; otherwise, <c>false</c>.
|
---|
| 39 | /// </returns>
|
---|
[1823] | 40 | public bool CanSerialize(Type type) {
|
---|
[3553] | 41 | if (GetConstructor(type) == null)
|
---|
[1852] | 42 | return false;
|
---|
[3029] | 43 | return StorableReflection.IsEmptyOrStorableType(type, true);
|
---|
[1623] | 44 | }
|
---|
| 45 |
|
---|
[3036] | 46 | /// <summary>
|
---|
| 47 | /// Give a reason if possibly why the given type cannot be serialized by this
|
---|
| 48 | /// ICompositeSerializer.
|
---|
| 49 | /// </summary>
|
---|
| 50 | /// <param name="type">The type.</param>
|
---|
| 51 | /// <returns>
|
---|
| 52 | /// A string justifying why type cannot be serialized.
|
---|
| 53 | /// </returns>
|
---|
[2993] | 54 | public string JustifyRejection(Type type) {
|
---|
[3553] | 55 | if (GetConstructor(type) == null)
|
---|
[2993] | 56 | return "no default constructor and no storable constructor";
|
---|
[3029] | 57 | if (!StorableReflection.IsEmptyOrStorableType(type, true))
|
---|
[3025] | 58 | return "class is not marked with the storable class attribute";
|
---|
| 59 | return "no reason";
|
---|
[2993] | 60 | }
|
---|
| 61 |
|
---|
[3036] | 62 | /// <summary>
|
---|
| 63 | /// Creates the meta info.
|
---|
| 64 | /// </summary>
|
---|
| 65 | /// <param name="o">The object.</param>
|
---|
| 66 | /// <returns>A list of storable components.</returns>
|
---|
[1623] | 67 | public IEnumerable<Tag> CreateMetaInfo(object o) {
|
---|
[3031] | 68 | InvokeHook(HookType.BeforeSerialization, o);
|
---|
[1623] | 69 | return new Tag[] { };
|
---|
| 70 | }
|
---|
| 71 |
|
---|
[3036] | 72 | /// <summary>
|
---|
| 73 | /// Decompose an object into <see cref="Tag"/>s, the tag name can be null,
|
---|
| 74 | /// the order in which elements are generated is guaranteed to be
|
---|
| 75 | /// the same as they will be supplied to the Populate method.
|
---|
| 76 | /// </summary>
|
---|
| 77 | /// <param name="obj">An object.</param>
|
---|
| 78 | /// <returns>An enumerable of <see cref="Tag"/>s.</returns>
|
---|
[1623] | 79 | public IEnumerable<Tag> Decompose(object obj) {
|
---|
[3025] | 80 | foreach (var accessor in GetStorableAccessors(obj)) {
|
---|
[1960] | 81 | yield return new Tag(accessor.Name, accessor.Get());
|
---|
[1623] | 82 | }
|
---|
| 83 | }
|
---|
| 84 |
|
---|
[3036] | 85 | /// <summary>
|
---|
| 86 | /// Create an instance of the object using the provided meta information.
|
---|
| 87 | /// </summary>
|
---|
| 88 | /// <param name="type">A type.</param>
|
---|
| 89 | /// <param name="metaInfo">The meta information.</param>
|
---|
| 90 | /// <returns>A fresh instance of the provided type.</returns>
|
---|
[1623] | 91 | public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
|
---|
[2990] | 92 | try {
|
---|
[3553] | 93 | return GetConstructor(type)();
|
---|
[2990] | 94 | } catch (TargetInvocationException x) {
|
---|
| 95 | throw new PersistenceException(
|
---|
| 96 | "Could not instantiate storable object: Encountered exception during constructor call",
|
---|
| 97 | x.InnerException);
|
---|
| 98 | }
|
---|
[1623] | 99 | }
|
---|
| 100 |
|
---|
[3036] | 101 | /// <summary>
|
---|
| 102 | /// Populates the specified instance.
|
---|
| 103 | /// </summary>
|
---|
| 104 | /// <param name="instance">The instance.</param>
|
---|
| 105 | /// <param name="objects">The objects.</param>
|
---|
| 106 | /// <param name="type">The type.</param>
|
---|
[1623] | 107 | public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
|
---|
| 108 | var memberDict = new Dictionary<string, Tag>();
|
---|
| 109 | IEnumerator<Tag> iter = objects.GetEnumerator();
|
---|
| 110 | while (iter.MoveNext()) {
|
---|
| 111 | memberDict.Add(iter.Current.Name, iter.Current);
|
---|
[3029] | 112 | }
|
---|
[3025] | 113 | foreach (var accessor in GetStorableAccessors(instance)) {
|
---|
[1960] | 114 | if (memberDict.ContainsKey(accessor.Name)) {
|
---|
[2980] | 115 | accessor.Set(memberDict[accessor.Name].Value);
|
---|
[1960] | 116 | } else if (accessor.DefaultValue != null) {
|
---|
[2980] | 117 | accessor.Set(accessor.DefaultValue);
|
---|
[1623] | 118 | }
|
---|
| 119 | }
|
---|
[3031] | 120 | InvokeHook(HookType.AfterDeserialization, instance);
|
---|
[1623] | 121 | }
|
---|
[3025] | 122 |
|
---|
| 123 | #endregion
|
---|
| 124 |
|
---|
[3029] | 125 | #region constants & private data types
|
---|
[3025] | 126 |
|
---|
| 127 | private const BindingFlags ALL_CONSTRUCTORS =
|
---|
| 128 | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
|
---|
| 129 |
|
---|
[3031] | 130 | private static readonly object[] emptyArgs = new object[] { };
|
---|
| 131 |
|
---|
[3553] | 132 | private sealed class HookDesignator {
|
---|
[3025] | 133 | public Type Type { get; private set; }
|
---|
[3553] | 134 | public HookType HookType { get; private set; }
|
---|
[3031] | 135 | public HookDesignator() { }
|
---|
| 136 | public HookDesignator(Type type, HookType hookType) {
|
---|
| 137 | Type = type;
|
---|
| 138 | HookType = HookType;
|
---|
| 139 | }
|
---|
| 140 | }
|
---|
| 141 |
|
---|
[3553] | 142 | private sealed class MemberCache : Dictionary<Type, IEnumerable<StorableMemberInfo>> { }
|
---|
[3025] | 143 |
|
---|
| 144 | #endregion
|
---|
| 145 |
|
---|
| 146 | #region caches
|
---|
| 147 |
|
---|
| 148 | private MemberCache storableMemberCache = new MemberCache();
|
---|
| 149 |
|
---|
[3553] | 150 | private delegate object Constructor();
|
---|
| 151 |
|
---|
| 152 | private Dictionary<Type, Constructor> constructorCache =
|
---|
| 153 | new Dictionary<Type, Constructor>();
|
---|
| 154 |
|
---|
| 155 | private Dictionary<HookDesignator, List<StorableReflection.Hook>> hookCache =
|
---|
| 156 | new Dictionary<HookDesignator, List<StorableReflection.Hook>>();
|
---|
| 157 |
|
---|
[3025] | 158 | #endregion
|
---|
| 159 |
|
---|
[3029] | 160 | #region attribute access
|
---|
[3025] | 161 |
|
---|
| 162 | private IEnumerable<StorableMemberInfo> GetStorableMembers(Type type) {
|
---|
| 163 | lock (storableMemberCache) {
|
---|
[3553] | 164 | if (storableMemberCache.ContainsKey(type))
|
---|
| 165 | return storableMemberCache[type];
|
---|
| 166 | var storablesMembers = StorableReflection.GenerateStorableMembers(type);
|
---|
| 167 | storableMemberCache[type] = storablesMembers;
|
---|
[3025] | 168 | return storablesMembers;
|
---|
| 169 | }
|
---|
[3553] | 170 | }
|
---|
[3025] | 171 |
|
---|
[3553] | 172 | private Constructor GetConstructor(Type type) {
|
---|
[3025] | 173 | lock (constructorCache) {
|
---|
| 174 | if (constructorCache.ContainsKey(type))
|
---|
| 175 | return constructorCache[type];
|
---|
[3553] | 176 | Constructor c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
|
---|
| 177 | constructorCache.Add(type, c);
|
---|
| 178 | return c;
|
---|
| 179 | }
|
---|
| 180 | }
|
---|
| 181 |
|
---|
| 182 | private Constructor GetDefaultConstructor(Type type) {
|
---|
| 183 | ConstructorInfo ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
|
---|
| 184 | if (ci == null)
|
---|
| 185 | return null;
|
---|
| 186 | DynamicMethod dm = new DynamicMethod("", typeof(object), null, type);
|
---|
| 187 | ILGenerator ilgen = dm.GetILGenerator();
|
---|
| 188 | ilgen.Emit(OpCodes.Newobj, ci);
|
---|
| 189 | ilgen.Emit(OpCodes.Ret);
|
---|
| 190 | return (Constructor)dm.CreateDelegate(typeof(Constructor));
|
---|
| 191 | }
|
---|
| 192 |
|
---|
| 193 | private Constructor FindStorableConstructor(Type type) {
|
---|
| 194 | foreach (ConstructorInfo ci in type.GetConstructors(ALL_CONSTRUCTORS)) {
|
---|
| 195 | if (ci.GetCustomAttributes(typeof(StorableConstructorAttribute), false).Length > 0) {
|
---|
| 196 | if (ci.GetParameters().Length != 1 ||
|
---|
| 197 | ci.GetParameters()[0].ParameterType != typeof(bool))
|
---|
| 198 | throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
|
---|
| 199 | DynamicMethod dm = new DynamicMethod("", typeof(object), null, type);
|
---|
| 200 | ILGenerator ilgen = dm.GetILGenerator();
|
---|
| 201 | ilgen.Emit(OpCodes.Ldc_I4_1); // load true
|
---|
| 202 | ilgen.Emit(OpCodes.Newobj, ci);
|
---|
| 203 | ilgen.Emit(OpCodes.Ret);
|
---|
| 204 | return (Constructor)dm.CreateDelegate(typeof(Constructor));
|
---|
[3025] | 205 | }
|
---|
| 206 | }
|
---|
[3553] | 207 | return null;
|
---|
[3025] | 208 | }
|
---|
| 209 |
|
---|
[3029] | 210 | private IEnumerable<DataMemberAccessor> GetStorableAccessors(object obj) {
|
---|
| 211 | return GetStorableMembers(obj.GetType())
|
---|
| 212 | .Select(mi => new DataMemberAccessor(mi.MemberInfo, mi.DisentangledName, mi.DefaultValue, obj));
|
---|
| 213 | }
|
---|
| 214 |
|
---|
[3031] | 215 | private void InvokeHook(HookType hookType, object obj) {
|
---|
| 216 | if (obj == null)
|
---|
| 217 | throw new ArgumentNullException("Cannot invoke hooks on null");
|
---|
[3553] | 218 | foreach (StorableReflection.Hook hook in GetHooks(hookType, obj.GetType())) {
|
---|
| 219 | hook(obj);
|
---|
[3031] | 220 | }
|
---|
| 221 | }
|
---|
| 222 |
|
---|
[3553] | 223 | private IEnumerable<StorableReflection.Hook> GetHooks(HookType hookType, Type type) {
|
---|
[3031] | 224 | lock (hookCache) {
|
---|
[3553] | 225 | List<StorableReflection.Hook> hooks;
|
---|
[3031] | 226 | var designator = new HookDesignator(type, hookType);
|
---|
| 227 | hookCache.TryGetValue(designator, out hooks);
|
---|
| 228 | if (hooks != null)
|
---|
| 229 | return hooks;
|
---|
[3553] | 230 | hooks = new List<StorableReflection.Hook>(StorableReflection.CollectHooks(hookType, type));
|
---|
[3031] | 231 | hookCache.Add(designator, hooks);
|
---|
| 232 | return hooks;
|
---|
| 233 | }
|
---|
| 234 | }
|
---|
| 235 |
|
---|
[3025] | 236 | #endregion
|
---|
[3031] | 237 |
|
---|
[3553] | 238 |
|
---|
| 239 |
|
---|
[1623] | 240 | }
|
---|
[3553] | 241 |
|
---|
[2980] | 242 | } |
---|