Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Persistence/4.0/Transformers/StorableClassTransformer.cs @ 15035

Last change on this file since 15035 was 15035, checked in by gkronber, 7 years ago

#2520: made some changes related to renaming of storable members

File size: 6.8 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2012 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;
26
27namespace HeuristicLab.Persistence {
28  [Transformer("78556C88-0FEE-4602-95C7-A469B2DDB468", 100)]
29  [StorableType("3a578289-43ca-40f8-9f1e-2bdd255cb8fb")]
30  internal sealed class StorableClassBoxTransformer : BoxTransformer<object> {
31    public override bool CanTransformType(Type type) {
32      return StorableTypeAttribute.IsStorableType(type) && !type.IsValueType && !type.IsEnum || // don't transform structs or enums
33        type.BaseType != null && CanTransformType(type.BaseType);
34    }
35
36    protected override void Populate(Box.Builder box, object value, Mapper mapper) {
37      var b = StorableClassBox.CreateBuilder();
38      var type = value.GetType();
39      var typeInfo = Mapper.StaticCache.GetTypeInfo(type);
40
41      var emptyArgs = new object[0];
42      foreach (var hook in typeInfo.BeforeSerializationHooks) {
43        hook.Invoke(value, emptyArgs);
44      }
45
46      var components = new Dictionary<uint, uint>();
47      foreach (var componentInfo in typeInfo.Fields) {
48        var field = (FieldInfo)componentInfo.MemberInfo;
49        var component = mapper.GetBoxId(field.GetValue(value));
50        components.Add(mapper.GetStringId(componentInfo.Name), component);
51      }
52
53      foreach (var componentInfo in typeInfo.Properties.Where(x => x.Readable)) {
54        var property = (PropertyInfo)componentInfo.MemberInfo;
55        var component = mapper.GetBoxId(property.GetValue(value, null));
56        components.Add(mapper.GetStringId(componentInfo.Name), component);
57      }
58
59      b.AddRangeKeyIds(components.Keys);
60      b.AddRangeValueIds(components.Values);
61
62      box.SetExtension(StorableClassBox.StorableClass, b.Build());
63    }
64
65    protected override object Extract(Box box, Type type, Mapper mapper) {
66      return mapper.CreateInstance(type);
67    }
68    public override void FillFromBox(object obj, Box box, Mapper mapper) {
69      var data = box.GetExtension(StorableClassBox.StorableClass);
70      var type = obj.GetType();
71      var typeInfo = Mapper.StaticCache.GetTypeInfo(type);
72      var typeBox = mapper.GetBox(box.TypeId).GetExtension(TypeBox.Type);
73      var version = typeBox.HasVersion ? typeBox.Version : 1;
74      var typeGuid = typeInfo.StorableTypeAttribute.Guid;
75
76      var components = new Dictionary<uint, uint>();
77      for (int i = 0; i < data.KeyIdsList.Count; i++) {
78        components.Add(data.KeyIdsList[i], data.ValueIdsList[i]);
79      }
80
81      var conversionMethods =
82        type.Assembly.GetTypes().SelectMany(t =>
83          t.GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
84          .Where(StorableConversionAttribute.IsStorableConversionMethod)
85          .Where(mi => StorableConversionAttribute.GetGuid(mi) == typeGuid &&
86                       StorableConversionAttribute.GetVersion(mi) >= version))
87          .OrderBy(StorableConversionAttribute.GetVersion)
88          .ToArray();
89
90      // put all objects into dictionary for conversion
91      var dict = new Dictionary<string, object>();
92      foreach (var component in components) {
93        dict.Add(mapper.GetString(component.Key), mapper.GetObject(component.Value));
94      }
95
96      Dictionary<string, object> lastDict = new Dictionary<string, object>();
97      foreach (var convMeth in conversionMethods) {
98        if (StorableConversionAttribute.GetVersion(convMeth) != version)
99          throw new PersistenceException(string.Format("No conversion method defined for type {0} version {1}", typeGuid, version));
100        lastDict = (Dictionary<string, object>)convMeth.Invoke(null, new object[] { dict });
101        foreach (var kvp in lastDict) {
102          dict[kvp.Key] = kvp.Value;
103        }
104        version++;
105      }
106      if (version != typeInfo.StorableTypeAttribute.Version)
107        throw new PersistenceException(string.Format("Missing one or more conversion methods for type {0} version {1}",
108          typeGuid, typeInfo.StorableTypeAttribute.Version));
109
110      // set default values for all fields and properties
111      foreach (var componentInfo in typeInfo.Fields) {
112        var field = (FieldInfo)componentInfo.MemberInfo;
113        if (componentInfo.StorableAttribute != null && componentInfo.StorableAttribute.DefaultValue != null)
114          field.SetValue(obj, componentInfo.StorableAttribute.DefaultValue);
115      }
116      foreach (var componentInfo in typeInfo.Properties.Where(x => x.Writeable)) {
117        var property = (PropertyInfo)componentInfo.MemberInfo;
118        if (componentInfo.StorableAttribute != null && componentInfo.StorableAttribute.DefaultValue != null)
119          property.SetValue(obj, componentInfo.StorableAttribute.DefaultValue, null);
120      }
121
122      // set all members as generated by conversion method chain
123      foreach (var kvp in dict) {
124        var key = kvp.Key;
125        var val = kvp.Value;
126        var fieldInfo = typeInfo.Fields.FirstOrDefault(fi => fi.Name == key);
127        if (fieldInfo != null) {
128          var field = (FieldInfo)fieldInfo.MemberInfo;
129          field.SetValue(obj, val);
130          lastDict.Remove(fieldInfo.Name); // only for consistency check
131          continue;
132        }
133        var propInfo = typeInfo.Properties.Where(x => x.Writeable).FirstOrDefault(pi => pi.Name == key);
134        if (propInfo != null) {
135          var prop = (PropertyInfo)propInfo.MemberInfo;
136          prop.SetValue(obj, val, null);
137          lastDict.Remove(propInfo.Name);    // only for consistency check
138          continue;
139        }
140      }
141
142      if (lastDict.Any())
143        throw new PersistenceException(string.Format("Invalid conversion method. The following members are undefined in type {0} version {1}: {2}",
144          typeGuid, typeInfo.StorableTypeAttribute.Version,
145          string.Join(", ", lastDict.Keys)));
146
147      var emptyArgs = new object[0];
148      foreach (var hook in typeInfo.AfterDeserializationHooks) {
149        hook.Invoke(obj, emptyArgs);
150      }
151    }
152  }
153}
Note: See TracBrowser for help on using the repository browser.