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
RevLine 
[3743]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;
[4068]23using System.Collections.Generic;
[1454]24using System.IO;
[1644]25using System.Linq;
[1454]26using System.Reflection;
27using System.Text;
28using HeuristicLab.Persistence.Default.Xml;
29using HeuristicLab.Persistence.Interfaces;
[1469]30using HeuristicLab.Tracing;
[1454]31
32namespace HeuristicLab.Persistence.Core {
[1566]33
[3004]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>
[1454]41  public class ConfigurationService {
42
43    private static ConfigurationService instance;
44    private readonly Dictionary<IFormat, Configuration> customConfigurations;
[3004]45
46    /// <summary>
47    /// List of all available primitive serializers.
48    /// </summary>
[1823]49    public Dictionary<Type, List<IPrimitiveSerializer>> PrimitiveSerializers { get; private set; }
[3004]50
51    /// <summary>
52    /// List of all available composite serializers (discovered through reflection).
53    /// </summary>
[1823]54    public List<ICompositeSerializer> CompositeSerializers { get; private set; }
[3004]55
56    /// <summary>
57    /// List of all available formats (discovered through reflection).   
58    /// </summary>
[1564]59    public List<IFormat> Formats { get; private set; }
[1566]60
[3016]61    /// <summary>
62    /// Gets the singleton instance.
63    /// </summary>
64    /// <value>The singleton instance.</value>
[1454]65    public static ConfigurationService Instance {
66      get {
67        if (instance == null)
68          instance = new ConfigurationService();
69        return instance;
70      }
71    }
72
[1542]73    private ConfigurationService() {
[1823]74      PrimitiveSerializers = new Dictionary<Type, List<IPrimitiveSerializer>>();
75      CompositeSerializers = new List<ICompositeSerializer>();
[1564]76      customConfigurations = new Dictionary<IFormat, Configuration>();
77      Formats = new List<IFormat>();
[1454]78      Reset();
79      LoadSettings();
80    }
81
[3016]82    /// <summary>
83    /// Loads the settings.
84    /// </summary>
[1660]85    public void LoadSettings() {
86      LoadSettings(false);
87    }
88
[3016]89    /// <summary>
90    /// Loads the settings.
91    /// </summary>
92    /// <param name="throwOnError">if set to <c>true</c> throw on error.</param>
[1660]93    public void LoadSettings(bool throwOnError) {
[1454]94      try {
[1660]95        TryLoadSettings();
[4068]96      }
97      catch (Exception e) {
[1660]98        if (throwOnError) {
99          throw new PersistenceException("Could not load persistence settings.", e);
100        } else {
101          Logger.Warn("Could not load settings.", e);
102        }
[1703]103      }
[1660]104    }
105
[3016]106    /// <summary>
107    /// Tries to load the settings (i.e custom configurations).
108    /// </summary>
[1660]109    protected void TryLoadSettings() {
110      if (String.IsNullOrEmpty(Properties.Settings.Default.CustomConfigurations) ||
[1542]111          String.IsNullOrEmpty(Properties.Settings.Default.CustomConfigurationsTypeCache))
[1660]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;
[1454]124      }
125    }
126
[3016]127    /// <summary>
128    /// Saves the settings (i.e custom configurations).
129    /// </summary>
[1623]130    protected void SaveSettings() {
[1454]131      Serializer serializer = new Serializer(
132        customConfigurations,
[1564]133        GetDefaultConfig(new XmlFormat()),
[1454]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);
[1542]143      Properties.Settings.Default.CustomConfigurations =
[1454]144        configurationString.ToString();
[1542]145      Properties.Settings.Default.CustomConfigurationsTypeCache =
[1454]146        configurationTypeCacheString.ToString();
147      Properties.Settings.Default.Save();
148    }
149
[3004]150
151    /// <summary>
152    /// Rediscover available serializers and discard all custom configurations.
153    /// </summary>
[1566]154    public void Reset() {
[1454]155      customConfigurations.Clear();
[1823]156      PrimitiveSerializers.Clear();
157      CompositeSerializers.Clear();
[1454]158      Assembly defaultAssembly = Assembly.GetExecutingAssembly();
159      DiscoverFrom(defaultAssembly);
[2876]160      try {
161        foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies())
162          if (a != defaultAssembly)
163            DiscoverFrom(a);
[4068]164      }
165      catch (AppDomainUnloadedException x) {
[2876]166        Logger.Warn("could not get list of assemblies, AppDomain has already been unloaded", x);
167      }
[1823]168      SortCompositeSerializers();
[1454]169    }
170
[3004]171    private class PriortiySorter : IComparer<ICompositeSerializer> {
[1823]172      public int Compare(ICompositeSerializer x, ICompositeSerializer y) {
[1539]173        return y.Priority - x.Priority;
174      }
175    }
176
[3016]177    /// <summary>
178    /// Sorts the composite serializers according to their priority.
179    /// </summary>
[1823]180    protected void SortCompositeSerializers() {
181      CompositeSerializers.Sort(new PriortiySorter());
[1539]182    }
183
[3016]184    /// <summary>
185    /// Discovers serializers from an assembly.
186    /// </summary>
187    /// <param name="a">An Assembly.</param>
[1454]188    protected void DiscoverFrom(Assembly a) {
[2876]189      try {
190        foreach (Type t in a.GetTypes()) {
[3037]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);
[1554]198          }
[3037]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));
[1454]202          }
[3037]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);
[1566]207          }
[1564]208        }
[4068]209      }
210      catch (ReflectionTypeLoadException e) {
[2876]211        Logger.Warn("could not analyse assembly: " + a.FullName, e);
[1454]212      }
213    }
214
[3004]215    /// <summary>
216    /// Get the default (automatically discovered) configuration for a certain format.
[3016]217    /// </summary>
218    /// <param name="format">The format.</param>
219    /// <returns>The default (auto discovered) configuration.</returns>
[1454]220    public Configuration GetDefaultConfig(IFormat format) {
[1823]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);
[1625]226        }
227      } else {
228        Logger.Warn(String.Format(
[1823]229          "No primitive serializers found for format {0} with serial data type {1}",
230          format.GetType().AssemblyQualifiedName,
231          format.SerialDataType.AssemblyQualifiedName));
[1454]232      }
[1823]233      return new Configuration(
234        format,
235        primitiveConfig.Values,
236        CompositeSerializers.Where((d) => d.Priority > 0));
[1454]237    }
238
[3004]239
240    /// <summary>
[3030]241    /// Get a configuration for a certain format. This returns a fresh copy of a custom configuration,
[3004]242    /// if defined, otherwise returns the default (automatically discovered) configuration.
[3016]243    /// </summary>
244    /// <param name="format">The format.</param>
245    /// <returns>A Configuration</returns>
[1454]246    public Configuration GetConfiguration(IFormat format) {
247      if (customConfigurations.ContainsKey(format))
[3030]248        return customConfigurations[format].Copy();
[1454]249      return GetDefaultConfig(format);
250    }
251
[3004]252    /// <summary>
253    /// Define a new custom configuration for a ceratin format.
[3016]254    /// </summary>
255    /// <param name="configuration">The new configuration.</param>
[1566]256    public void DefineConfiguration(Configuration configuration) {
[3030]257      customConfigurations[configuration.Format] = configuration.Copy();
[1454]258      SaveSettings();
259    }
260
261  }
[1566]262
[1454]263}
Note: See TracBrowser for help on using the repository browser.