Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Persistence/3.3/Core/ConfigurationService.cs @ 1644

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

support for default disabled decomposers, re-activate number2string decomposer with negative priority. (#548)

File size: 6.9 KB
Line 
1using System;
2using System.IO;
3using System.Linq;
4using System.Collections.Generic;
5using System.Reflection;
6using System.Text;
7using HeuristicLab.Persistence.Default.Xml;
8using HeuristicLab.Persistence.Interfaces;
9using HeuristicLab.Tracing;
10using HeuristicLab.Persistence.Core.Tokens;
11
12namespace HeuristicLab.Persistence.Core {
13
14  public class ConfigurationService {
15
16    private static ConfigurationService instance;
17    private readonly Dictionary<IFormat, Configuration> customConfigurations;
18    public Dictionary<Type, List<IFormatter>> Formatters { get; private set; }
19    public List<IDecomposer> Decomposers { get; private set; }
20    public List<IFormat> Formats { get; private set; }
21
22    public static ConfigurationService Instance {
23      get {
24        if (instance == null)
25          instance = new ConfigurationService();
26        return instance;
27      }
28    }
29
30    private ConfigurationService() {
31      Formatters = new Dictionary<Type, List<IFormatter>>();
32      Decomposers = new List<IDecomposer>();
33      customConfigurations = new Dictionary<IFormat, Configuration>();
34      Formats = new List<IFormat>();
35      Reset();
36      LoadSettings();
37    }
38
39    protected void LoadSettings() {
40      try {
41        if (String.IsNullOrEmpty(Properties.Settings.Default.CustomConfigurations) ||
42          String.IsNullOrEmpty(Properties.Settings.Default.CustomConfigurationsTypeCache))
43          return;
44        Deserializer deSerializer = new Deserializer(
45          XmlParser.ParseTypeCache(
46          new StringReader(
47            Properties.Settings.Default.CustomConfigurationsTypeCache)));
48        XmlParser parser = new XmlParser(
49          new StringReader(
50            Properties.Settings.Default.CustomConfigurations));
51        var newCustomConfigurations = (Dictionary<IFormat, Configuration>)
52          deSerializer.Deserialize(parser);
53        foreach (var config in newCustomConfigurations) {
54          customConfigurations[config.Key] = config.Value;
55        }
56      } catch (Exception e) {
57        Logger.Warn("Could not load settings.", e);
58      }
59    }
60
61    protected void SaveSettings() {
62      Serializer serializer = new Serializer(
63        customConfigurations,
64        GetDefaultConfig(new XmlFormat()),
65        "CustomConfigurations");
66      XmlGenerator generator = new XmlGenerator();
67      StringBuilder configurationString = new StringBuilder();
68      foreach (ISerializationToken token in serializer) {
69        configurationString.Append(generator.Format(token));
70      }
71      StringBuilder configurationTypeCacheString = new StringBuilder();
72      foreach (string s in generator.Format(serializer.TypeCache))
73        configurationTypeCacheString.Append(s);
74      Properties.Settings.Default.CustomConfigurations =
75        configurationString.ToString();
76      Properties.Settings.Default.CustomConfigurationsTypeCache =
77        configurationTypeCacheString.ToString();
78      Properties.Settings.Default.Save();
79    }
80
81    public void Reset() {
82      customConfigurations.Clear();
83      Formatters.Clear();
84      Decomposers.Clear();
85      Assembly defaultAssembly = Assembly.GetExecutingAssembly();
86      DiscoverFrom(defaultAssembly);
87      foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
88        if (a != defaultAssembly)
89          DiscoverFrom(a);
90      SortDecomposers();
91    }
92
93    class PriortiySorter : IComparer<IDecomposer> {
94      public int Compare(IDecomposer x, IDecomposer y) {
95        return y.Priority - x.Priority;
96      }
97    }
98
99    protected void SortDecomposers() {
100      Decomposers.Sort(new PriortiySorter());
101    }
102
103    protected void DiscoverFrom(Assembly a) {
104      foreach (Type t in a.GetTypes()) {
105        if (t.GetInterface(typeof(IFormatter).FullName) != null) {
106          try {
107            IFormatter formatter = (IFormatter)Activator.CreateInstance(t, true);
108            if (!Formatters.ContainsKey(formatter.SerialDataType)) {
109              Formatters.Add(formatter.SerialDataType, new List<IFormatter>());
110            }
111            Formatters[formatter.SerialDataType].Add(formatter);
112            Logger.Debug(String.Format("discovered formatter {0} ({1} -> {2})",
113              t.VersionInvariantName(),
114              formatter.SourceType.VersionInvariantName(),
115              formatter.SerialDataType.VersionInvariantName()));
116          } catch (MissingMethodException e) {
117            Logger.Warn("Could not instantiate " + t.VersionInvariantName(), e);
118          } catch (ArgumentException e) {
119            Logger.Warn("Could not instantiate " + t.VersionInvariantName(), e);
120          }
121        }
122        if (t.GetInterface(typeof(IDecomposer).FullName) != null) {
123          try {
124            Decomposers.Add((IDecomposer)Activator.CreateInstance(t, true));
125            Logger.Debug("discovered decomposer " + t.VersionInvariantName());
126          } catch (MissingMethodException e) {
127            Logger.Warn("Could not instantiate " + t.VersionInvariantName(), e);
128          } catch (ArgumentException e) {
129            Logger.Warn("Could not instantiate " + t.VersionInvariantName(), e);
130          }
131        }
132        if (t.GetInterface(typeof(IFormat).FullName) != null) {
133          try {
134            IFormat format = (IFormat)Activator.CreateInstance(t, true);
135            Formats.Add(format);
136            Logger.Debug(String.Format("discovered format {0} ({2}) with serial data {1}.",
137              format.Name,
138              format.SerialDataType,
139              t.VersionInvariantName()));
140          } catch (MissingMethodException e) {
141            Logger.Warn("Could not instantiate " + t.VersionInvariantName(), e);
142          } catch (ArgumentException e) {
143            Logger.Warn("Could not instantiate " + t.VersionInvariantName(), e);
144          }
145        }
146      }
147    }
148
149    public Configuration GetDefaultConfig(IFormat format) {
150      Dictionary<Type, IFormatter> formatterConfig = new Dictionary<Type, IFormatter>();
151      if (Formatters.ContainsKey(format.SerialDataType)) {
152        foreach (IFormatter f in Formatters[format.SerialDataType]) {
153          if (!formatterConfig.ContainsKey(f.SourceType))
154            formatterConfig.Add(f.SourceType, f);
155        }
156      } else {
157        Logger.Warn(String.Format(
158          "No formatters found for format {0} with serial data type {1}",
159          format.GetType().VersionInvariantName(),
160          format.SerialDataType.VersionInvariantName()));
161      }
162      return new Configuration(format, formatterConfig, Decomposers.Where((d) => d.Priority > 0));
163    }
164
165    public Configuration GetConfiguration(IFormat format) {
166      if (customConfigurations.ContainsKey(format))
167        return customConfigurations[format];
168      return GetDefaultConfig(format);
169    }
170
171    public void DefineConfiguration(Configuration configuration) {
172      customConfigurations[configuration.Format] = configuration;
173      SaveSettings();
174    }
175
176  }
177
178}
Note: See TracBrowser for help on using the repository browser.