Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/KeyValuePairDecomposer.cs @ 1625

Last change on this file since 1625 was 1625, checked in by epitzer, 15 years ago

Added PersistenceException used consistently for all error conditions in the persistence framework (#548)

File size: 2.3 KB
Line 
1using System;
2using System.Linq;
3using System.Collections.Generic;
4using HeuristicLab.Persistence.Core;
5using HeuristicLab.Persistence.Interfaces;
6using System.Reflection;
7using HeuristicLab.Persistence.Default.Decomposers.Storable;
8
9namespace HeuristicLab.Persistence.Default.Decomposers {
10
11  [EmptyStorableClass]
12  public class KeyValuePairDecomposer : IDecomposer {
13
14    public int Priority {
15      get { return 100; }
16    }
17
18
19    public bool CanDecompose(Type type) {
20      return type.IsGenericType &&
21             type.GetGenericTypeDefinition() ==
22             typeof(KeyValuePair<int, int>).GetGenericTypeDefinition();
23    }
24
25    public IEnumerable<Tag> CreateMetaInfo(object o) {
26      return new Tag[] { };
27    }
28
29    public IEnumerable<Tag> Decompose(object o) {
30      Type t = o.GetType();
31      Tag key, value;
32      try {
33        key = new Tag("key", t.GetProperty("Key").GetValue(o, null));       
34      } catch (Exception e) {
35        throw new PersistenceException("Exception caught during KeyValuePair decomposition", e);
36      }
37      yield return key;
38      try {
39        value = new Tag("value", t.GetProperty("Value").GetValue(o, null));
40      } catch (Exception e) {
41        throw new PersistenceException("Exception caught during KeyValuePair decomposition", e);
42      }
43      yield return value;
44    }
45
46    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
47      return Activator.CreateInstance(type, true);
48    }
49
50    public void Populate(object instance, IEnumerable<Tag> o, Type t) {
51      IEnumerator<Tag> iter = o.GetEnumerator();
52      try {
53        iter.MoveNext();
54        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
55          .Single(fi => fi.Name == "key").SetValue(instance, iter.Current.Value);
56        iter.MoveNext();
57        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
58          .Single(fi => fi.Name == "value").SetValue(instance, iter.Current.Value);
59      } catch (InvalidOperationException e) {
60        throw new PersistenceException("Not enough components to populate KeyValuePair instance", e);
61      } catch (Exception e) {
62        throw new PersistenceException("Exception caught during KeyValuePair reconstruction", e);
63      }
64    }
65  }
66}
Note: See TracBrowser for help on using the repository browser.