Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/DictionaryDecomposer.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.0 KB
Line 
1using System;
2using System.Collections;
3using HeuristicLab.Persistence.Core;
4using HeuristicLab.Persistence.Interfaces;
5using System.Collections.Generic;
6using HeuristicLab.Persistence.Default.Decomposers.Storable;
7
8namespace HeuristicLab.Persistence.Default.Decomposers {
9
10  [EmptyStorableClass]
11  public class DictionaryDecomposer : IDecomposer {
12
13    public int Priority {
14      get { return 100; }
15    }
16
17
18    public bool CanDecompose(Type type) {
19      return type.GetInterface(typeof(IDictionary).FullName) != null;
20    }
21
22    public IEnumerable<Tag> CreateMetaInfo(object o) {
23      return new Tag[] { };
24    }
25
26    public IEnumerable<Tag> Decompose(object o) {
27      IDictionary dict = (IDictionary)o;
28      foreach (DictionaryEntry entry in dict) {
29        yield return new Tag("key", entry.Key);
30        yield return new Tag("value", entry.Value);
31      }
32    }
33
34    public object CreateInstance(Type t, IEnumerable<Tag> metaInfo) {
35      return Activator.CreateInstance(t, true);
36    }
37
38    public void Populate(object instance, IEnumerable<Tag> o, Type t) {
39      IDictionary dict = (IDictionary)instance;
40      IEnumerator<Tag> iter = o.GetEnumerator();
41      try {
42        while (iter.MoveNext()) {
43          Tag key = iter.Current;
44          iter.MoveNext();
45          Tag value = iter.Current;
46          dict.Add(key.Value, value.Value);
47        }
48      } catch (InvalidOperationException e) {
49        throw new PersistenceException("Dictionaries must contain an even number of elements (key+value).", e);
50      } catch (NotSupportedException e) {
51        throw new PersistenceException("The serialized dictionary type was read-only or had a fixed size and cannot be deserialized.", e);
52      } catch (ArgumentNullException e) {
53        throw new PersistenceException("Dictionary key was null.", e);
54      } catch (ArgumentException e) {
55        throw new PersistenceException("Duplicate dictionary key.", e);
56      }     
57    }
58  }
59
60}
Note: See TracBrowser for help on using the repository browser.