Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 4068 was 4068, checked in by swagner, 14 years ago

Sorted usings and removed unused usings in entire solution (#1094)

File size: 10.0 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2010 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.IO;
25using System.Linq;
26using System.Reflection;
27using System.Text;
28using HeuristicLab.Persistence.Default.Xml;
29using HeuristicLab.Persistence.Interfaces;
30using HeuristicLab.Tracing;
31
32namespace HeuristicLab.Persistence.Core {
33
34  /// <summary>
35  /// Provides a persistable configuration of primitive and composite serializers for
36  /// all registered serial formats. Custom formats can be defined and will be saved
37  /// for future sessions. A default configuration can be generated through reflection.
38  ///
39  /// This class has only a single instance.
40  /// </summary>
41  public class ConfigurationService {
42
43    private static ConfigurationService instance;
44    private readonly Dictionary<IFormat, Configuration> customConfigurations;
45
46    /// <summary>
47    /// List of all available primitive serializers.
48    /// </summary>
49    public Dictionary<Type, List<IPrimitiveSerializer>> PrimitiveSerializers { get; private set; }
50
51    /// <summary>
52    /// List of all available composite serializers (discovered through reflection).
53    /// </summary>
54    public List<ICompositeSerializer> CompositeSerializers { get; private set; }
55
56    /// <summary>
57    /// List of all available formats (discovered through reflection).   
58    /// </summary>
59    public List<IFormat> Formats { get; private set; }
60
61    /// <summary>
62    /// Gets the singleton instance.
63    /// </summary>
64    /// <value>The singleton instance.</value>
65    public static ConfigurationService Instance {
66      get {
67        if (instance == null)
68          instance = new ConfigurationService();
69        return instance;
70      }
71    }
72
73    private ConfigurationService() {
74      PrimitiveSerializers = new Dictionary<Type, List<IPrimitiveSerializer>>();
75      CompositeSerializers = new List<ICompositeSerializer>();
76      customConfigurations = new Dictionary<IFormat, Configuration>();
77      Formats = new List<IFormat>();
78      Reset();
79      LoadSettings();
80    }
81
82    /// <summary>
83    /// Loads the settings.
84    /// </summary>
85    public void LoadSettings() {
86      LoadSettings(false);
87    }
88
89    /// <summary>
90    /// Loads the settings.
91    /// </summary>
92    /// <param name="throwOnError">if set to <c>true</c> throw on error.</param>
93    public void LoadSettings(bool throwOnError) {
94      try {
95        TryLoadSettings();
96      }
97      catch (Exception e) {
98        if (throwOnError) {
99          throw new PersistenceException("Could not load persistence settings.", e);
100        } else {
101          Logger.Warn("Could not load settings.", e);
102        }
103      }
104    }
105
106    /// <summary>
107    /// Tries to load the settings (i.e custom configurations).
108    /// </summary>
109    protected void TryLoadSettings() {
110      if (String.IsNullOrEmpty(Properties.Settings.Default.CustomConfigurations) ||
111          String.IsNullOrEmpty(Properties.Settings.Default.CustomConfigurationsTypeCache))
112        return;
113      Deserializer deSerializer = new Deserializer(
114        XmlParser.ParseTypeCache(
115        new StringReader(
116          Properties.Settings.Default.CustomConfigurationsTypeCache)));
117      XmlParser parser = new XmlParser(
118        new StringReader(
119          Properties.Settings.Default.CustomConfigurations));
120      var newCustomConfigurations = (Dictionary<IFormat, Configuration>)
121        deSerializer.Deserialize(parser);
122      foreach (var config in newCustomConfigurations) {
123        customConfigurations[config.Key] = config.Value;
124      }
125    }
126
127    /// <summary>
128    /// Saves the settings (i.e custom configurations).
129    /// </summary>
130    protected void SaveSettings() {
131      Serializer serializer = new Serializer(
132        customConfigurations,
133        GetDefaultConfig(new XmlFormat()),
134        "CustomConfigurations");
135      XmlGenerator generator = new XmlGenerator();
136      StringBuilder configurationString = new StringBuilder();
137      foreach (ISerializationToken token in serializer) {
138        configurationString.Append(generator.Format(token));
139      }
140      StringBuilder configurationTypeCacheString = new StringBuilder();
141      foreach (string s in generator.Format(serializer.TypeCache))
142        configurationTypeCacheString.Append(s);
143      Properties.Settings.Default.CustomConfigurations =
144        configurationString.ToString();
145      Properties.Settings.Default.CustomConfigurationsTypeCache =
146        configurationTypeCacheString.ToString();
147      Properties.Settings.Default.Save();
148    }
149
150
151    /// <summary>
152    /// Rediscover available serializers and discard all custom configurations.
153    /// </summary>
154    public void Reset() {
155      customConfigurations.Clear();
156      PrimitiveSerializers.Clear();
157      CompositeSerializers.Clear();
158      Assembly defaultAssembly = Assembly.GetExecutingAssembly();
159      DiscoverFrom(defaultAssembly);
160      try {
161        foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
162          if (a != defaultAssembly)
163            DiscoverFrom(a);
164      }
165      catch (AppDomainUnloadedException x) {
166        Logger.Warn("could not get list of assemblies, AppDomain has already been unloaded", x);
167      }
168      SortCompositeSerializers();
169    }
170
171    private class PriortiySorter : IComparer<ICompositeSerializer> {
172      public int Compare(ICompositeSerializer x, ICompositeSerializer y) {
173        return y.Priority - x.Priority;
174      }
175    }
176
177    /// <summary>
178    /// Sorts the composite serializers according to their priority.
179    /// </summary>
180    protected void SortCompositeSerializers() {
181      CompositeSerializers.Sort(new PriortiySorter());
182    }
183
184    /// <summary>
185    /// Discovers serializers from an assembly.
186    /// </summary>
187    /// <param name="a">An Assembly.</param>
188    protected void DiscoverFrom(Assembly a) {
189      try {
190        foreach (Type t in a.GetTypes()) {
191          if (t.GetInterface(typeof(IPrimitiveSerializer).FullName) != null &&
192              !t.IsAbstract && t.GetConstructor(Type.EmptyTypes) != null && !t.ContainsGenericParameters) {
193            IPrimitiveSerializer primitiveSerializer =
194              (IPrimitiveSerializer)Activator.CreateInstance(t, true);
195            if (!PrimitiveSerializers.ContainsKey(primitiveSerializer.SerialDataType))
196              PrimitiveSerializers.Add(primitiveSerializer.SerialDataType, new List<IPrimitiveSerializer>());
197            PrimitiveSerializers[primitiveSerializer.SerialDataType].Add(primitiveSerializer);
198          }
199          if (t.GetInterface(typeof(ICompositeSerializer).FullName) != null &&
200              !t.IsAbstract && t.GetConstructor(Type.EmptyTypes) != null && !t.ContainsGenericParameters) {
201            CompositeSerializers.Add((ICompositeSerializer)Activator.CreateInstance(t, true));
202          }
203          if (t.GetInterface(typeof(IFormat).FullName) != null &&
204             !t.IsAbstract && t.GetConstructor(Type.EmptyTypes) != null && !t.ContainsGenericParameters) {
205            IFormat format = (IFormat)Activator.CreateInstance(t, true);
206            Formats.Add(format);
207          }
208        }
209      }
210      catch (ReflectionTypeLoadException e) {
211        Logger.Warn("could not analyse assembly: " + a.FullName, e);
212      }
213    }
214
215    /// <summary>
216    /// Get the default (automatically discovered) configuration for a certain format.
217    /// </summary>
218    /// <param name="format">The format.</param>
219    /// <returns>The default (auto discovered) configuration.</returns>
220    public Configuration GetDefaultConfig(IFormat format) {
221      Dictionary<Type, IPrimitiveSerializer> primitiveConfig = new Dictionary<Type, IPrimitiveSerializer>();
222      if (PrimitiveSerializers.ContainsKey(format.SerialDataType)) {
223        foreach (IPrimitiveSerializer f in PrimitiveSerializers[format.SerialDataType]) {
224          if (!primitiveConfig.ContainsKey(f.SourceType))
225            primitiveConfig.Add(f.SourceType, f);
226        }
227      } else {
228        Logger.Warn(String.Format(
229          "No primitive serializers found for format {0} with serial data type {1}",
230          format.GetType().AssemblyQualifiedName,
231          format.SerialDataType.AssemblyQualifiedName));
232      }
233      return new Configuration(
234        format,
235        primitiveConfig.Values,
236        CompositeSerializers.Where((d) => d.Priority > 0));
237    }
238
239
240    /// <summary>
241    /// Get a configuration for a certain format. This returns a fresh copy of a custom configuration,
242    /// if defined, otherwise returns the default (automatically discovered) configuration.
243    /// </summary>
244    /// <param name="format">The format.</param>
245    /// <returns>A Configuration</returns>
246    public Configuration GetConfiguration(IFormat format) {
247      if (customConfigurations.ContainsKey(format))
248        return customConfigurations[format].Copy();
249      return GetDefaultConfig(format);
250    }
251
252    /// <summary>
253    /// Define a new custom configuration for a ceratin format.
254    /// </summary>
255    /// <param name="configuration">The new configuration.</param>
256    public void DefineConfiguration(Configuration configuration) {
257      customConfigurations[configuration.Format] = configuration.Copy();
258      SaveSettings();
259    }
260
261  }
262
263}
Note: See TracBrowser for help on using the repository browser.