Free cookie consent management tool by TermsFeed Policy Generator

Changeset 1564 for trunk


Ignore:
Timestamp:
04/16/09 12:40:41 (15 years ago)
Author:
epitzer
Message:

Stronger typing for formatters with the help of generics. Separate format and serial data type. (#548)

Location:
trunk/sources/HeuristicLab.Persistence/3.3
Files:
4 added
22 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Persistence/3.3/Core/Configuration.cs

    r1542 r1564  
    99    [Storable]
    1010    private readonly Dictionary<Type, IFormatter> formatters;
     11
    1112    [Storable]
    1213    private readonly List<IDecomposer> decomposers;
    1314    private readonly Dictionary<Type, IDecomposer> decomposerCache;
    14     [Storable]
    15     public IFormat Format { get; set; }
     15
     16    [Storable]   
     17    public IFormat Format { get; private set; }
    1618
    1719    private Configuration() {
     
    1921    }
    2022
    21     public Configuration(Dictionary<Type, IFormatter> formatters, IEnumerable<IDecomposer> decomposers) {     
     23    public Configuration(IFormat format, Dictionary<Type, IFormatter> formatters, IEnumerable<IDecomposer> decomposers) {
     24      this.Format = format;
    2225      this.formatters = new Dictionary<Type, IFormatter>();
    2326      foreach ( var pair in formatters ) {
    24         if (Format == null) {
    25           Format = pair.Value.Format;
    26         } else if (pair.Value.Format != Format ) {
     27        if (pair.Value.SerialDataType != format.SerialDataType ) {
    2728          throw new ArgumentException("All formatters must have the same IFormat.");
    2829        }
  • trunk/sources/HeuristicLab.Persistence/3.3/Core/ConfigurationService.cs

    r1556 r1564  
    1515    private static ConfigurationService instance;
    1616    private readonly Dictionary<IFormat, Configuration> customConfigurations;
    17     public Dictionary<IFormat, List<IFormatter>> Formatters { get; private set; }
     17    public Dictionary<Type, List<IFormatter>> Formatters { get; private set; }
    1818    public List<IDecomposer> Decomposers { get; private set; }
     19    public List<IFormat> Formats { get; private set; }
    1920   
    2021    public static ConfigurationService Instance {
     
    2728
    2829    private ConfigurationService() {
    29       Formatters = new Dictionary<IFormat, List<IFormatter>>();
     30      Formatters = new Dictionary<Type, List<IFormatter>>();
    3031      Decomposers = new List<IDecomposer>();
    31       customConfigurations = new Dictionary<IFormat, Configuration>();     
     32      customConfigurations = new Dictionary<IFormat, Configuration>();
     33      Formats = new List<IFormat>();
    3234      Reset();
    3335      LoadSettings();
     
    5961      Serializer serializer = new Serializer(
    6062        customConfigurations,
    61         GetDefaultConfig(XmlFormat.Instance),
     63        GetDefaultConfig(new XmlFormat()),
    6264        "CustomConfigurations");
    6365      XmlGenerator generator = new XmlGenerator();
     
    103105          try {
    104106            IFormatter formatter = (IFormatter) Activator.CreateInstance(t, true);
    105             if ( ! Formatters.ContainsKey(formatter.Format) ) {
    106               Formatters.Add(formatter.Format, new List<IFormatter>());
     107            if ( ! Formatters.ContainsKey(formatter.SerialDataType) ) {
     108              Formatters.Add(formatter.SerialDataType, new List<IFormatter>());
    107109            }
    108             Formatters[formatter.Format].Add(formatter);
    109             Logger.Debug("discovered formatter " + t.VersionInvariantName());
     110            Formatters[formatter.SerialDataType].Add(formatter);
     111            Logger.Debug(String.Format("discovered formatter {0} ({1} -> {2})",
     112              t.VersionInvariantName(),
     113              formatter.SourceType.VersionInvariantName(),
     114              formatter.SerialDataType.VersionInvariantName()));
    110115          } catch (MissingMethodException e) {
    111116            Logger.Warn("Could not instantiate " + t.VersionInvariantName(), e);           
     
    124129          }
    125130        }
     131        if (t.GetInterface(typeof(IFormat).FullName) != null) {
     132          try {
     133            IFormat format = (IFormat)Activator.CreateInstance(t, true);
     134            Formats.Add(format);
     135            Logger.Debug(String.Format("discovered format {0} ({2}) with serial data {1}.",
     136              format.Name,
     137              format.SerialDataType,
     138              t.VersionInvariantName()));             
     139          } catch (MissingMethodException e) {
     140            Logger.Warn("Could not instantiate " + t.VersionInvariantName(), e);         
     141          } catch (ArgumentException e) {
     142            Logger.Warn("Could not instantiate " + t.VersionInvariantName(), e);
     143          }         
     144        }
    126145      }
    127146    }
     
    129148    public Configuration GetDefaultConfig(IFormat format) {
    130149      Dictionary<Type, IFormatter> formatterConfig = new Dictionary<Type, IFormatter>();
    131       foreach ( IFormatter f in Formatters[format] ) {
    132         if ( ! formatterConfig.ContainsKey(f.Type) )
    133           formatterConfig.Add(f.Type, f);
     150      foreach ( IFormatter f in Formatters[format.SerialDataType] ) {
     151        if ( ! formatterConfig.ContainsKey(f.SourceType) )
     152          formatterConfig.Add(f.SourceType, f);
    134153      }
    135       return new Configuration(formatterConfig, Decomposers);
     154      return new Configuration(format, formatterConfig, Decomposers);
    136155    }
    137156
     
    142161    }
    143162
    144     public void DefineConfiguration(IFormat format, Configuration configuration) {
    145       customConfigurations[format] = configuration;
     163    public void DefineConfiguration(Configuration configuration) {     
     164      customConfigurations[configuration.Format] = configuration;
    146165      SaveSettings();
    147166    }
  • trunk/sources/HeuristicLab.Persistence/3.3/Core/FormatBase.cs

    r1556 r1564  
    33namespace HeuristicLab.Persistence.Interfaces {
    44
    5   public abstract class FormatBase : IFormat {
    6     public abstract string Name { get;  }
     5  public abstract class FormatBase<SerialDataFormat> : IFormat<SerialDataFormat> where SerialDataFormat : ISerialData {
     6
     7    public abstract string Name { get; }
     8
     9    public Type SerialDataType { get { return typeof(SerialDataFormat); } }
     10
     11    public bool Equals(FormatBase<SerialDataFormat> f) {
     12      if (f == null)
     13        return false;
     14      return f.Name == this.Name;
     15    }
     16
    717    public override bool Equals(object obj) {
    8       if (obj as IFormat == null)
    9         return false;
    10       return this.Equals((FormatBase)obj);     
     18      FormatBase<SerialDataFormat> f = obj as FormatBase<SerialDataFormat>;     
     19      return Equals(f);
    1120    }
    12     public bool Equals(FormatBase f) {
    13       return Name.Equals(f.Name);
    14     }
    15     public override int GetHashCode() {
    16       return Name.GetHashCode();
    17     }
     21   
    1822  }
     23
    1924}
  • trunk/sources/HeuristicLab.Persistence/3.3/Core/Serializer.cs

    r1556 r1564  
    6969      IFormatter formatter = configuration.GetFormatter(value.GetType());
    7070      if (formatter != null)
    71         return PrimitiveEnumerator(accessor.Name, typeId, formatter.DoFormat(value), id);
     71        return PrimitiveEnumerator(accessor.Name, typeId, formatter.Format(value), id);
    7272      IDecomposer decomposer = configuration.GetDecomposer(value.GetType());
    7373      if (decomposer != null)
     
    8888
    8989    private IEnumerator<ISerializationToken> PrimitiveEnumerator(string name,
    90         int typeId, object serializedValue, int? id) {
     90        int typeId, ISerialData serializedValue, int? id) {
    9191      yield return new PrimitiveToken(name, typeId, id, serializedValue);
    9292    }
  • trunk/sources/HeuristicLab.Persistence/3.3/Core/Tokens/PrimitiveToken.cs

    r1556 r1564  
    66    public readonly int TypeId;
    77    public readonly int? Id;
    8     public readonly object SerialData;
    9     public PrimitiveToken(string name, int typeId, int? id, object serialData)
     8    public readonly ISerialData SerialData;
     9    public PrimitiveToken(string name, int typeId, int? id, ISerialData serialData)
    1010      : base(name) {
    1111      TypeId = typeId;
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/ViewOnly/ViewOnlyFormat.cs

    r1556 r1564  
    99namespace HeuristicLab.Persistence.Default.ViewOnly {
    1010
    11   public class ViewOnlyFormat : FormatBase {
    12     public override string Name { get { return "ViewOnly"; } }
    13     public static ViewOnlyFormat Instance = new ViewOnlyFormat();
     11  public class String : ISerialData {
     12    public string Data { get; set; }
     13    public String(string s) {
     14      Data = s;
     15    }
    1416  }
    1517
    16   public abstract class ValueType2ViewFormatter : IFormatter {
    17     public abstract Type Type { get; }
    18     public IFormat Format { get { return ViewOnlyFormat.Instance; } }
    19     public object DoFormat(object o) { return o; }
    20     public object Parse(object o) {
     18  public class ViewOnlyFormat : FormatBase<String> {
     19    public override string Name { get { return "ViewOnly"; } }   
     20  }
     21
     22  public abstract class ValueType2ViewFormatterBase<T> : FormatterBase<T, String> {
     23    public override String Format(T o) { return new String(o.ToString()); }
     24    public override T Parse(String s) {
    2125      throw new NotImplementedException();
    2226    }
    2327  }
    2428
    25   public class String2ViewFormatter : ValueType2ViewFormatter {
    26     public override Type Type { get { return typeof(string); } }
    27   }
     29  [EmptyStorableClass]
     30  public class String2ViewFormatter : ValueType2ViewFormatterBase<string> { }
    2831
    29   public class Bool2ViewFormatter : ValueType2ViewFormatter {
    30     public override Type Type { get { return typeof(bool); } }
    31   }
     32  [EmptyStorableClass]
     33  public class Bool2ViewFormatter : ValueType2ViewFormatterBase<bool> { }
    3234
    33   public class Int2ViewFormatter : ValueType2ViewFormatter {
    34     public override Type Type { get { return typeof(int); } }
    35   }
     35  [EmptyStorableClass]
     36  public class Int2ViewFormatter : ValueType2ViewFormatterBase<int> { }
    3637
    37   public class Double2ViewFormatter : ValueType2ViewFormatter {
    38     public override Type Type { get { return typeof(double); } }
    39   }
     38  [EmptyStorableClass]
     39  public class Double2ViewFormatter : ValueType2ViewFormatterBase<double> { }
    4040
    41   public class DateTime2ViewFormatter : ValueType2ViewFormatter {
    42     public override Type Type { get { return typeof(DateTime); } }
    43   }
     41  [EmptyStorableClass]
     42  public class DateTime2ViewFormatter : ValueType2ViewFormatterBase<DateTime> { }
    4443
    45   public class Type2ViewFormatter : ValueType2ViewFormatter {
    46     public override Type Type { get { return typeof(Type); } }
    47   }
     44  [EmptyStorableClass]
     45  public class Type2ViewFormatter : ValueType2ViewFormatterBase<Type> { }
    4846
    49   public class Float2ViewFormatter : ValueType2ViewFormatter {
    50     public override Type Type { get { return typeof(float); } }
    51   }
    52 
    53   public class ViewOnlyGenerator : Generator<string> {
     47  [EmptyStorableClass]
     48  public class Float2ViewFormatter : ValueType2ViewFormatterBase<float> { }
     49   
     50  public class ViewOnlyGenerator : GeneratorBase<string> {
    5451
    5552    private bool isSepReq;
     
    9895        sb.Append('=');
    9996      }
    100       sb.Append(primitiveToken.SerialData);
     97      sb.Append(((String)primitiveToken.SerialData).Data);
    10198      isSepReq = true;     
    10299      return sb.ToString(); 
     
    140137
    141138    public static string Serialize(object o) {
    142       return Serialize(o, ConfigurationService.Instance.GetDefaultConfig(ViewOnlyFormat.Instance));
     139      return Serialize(o, ConfigurationService.Instance.GetDefaultConfig(new ViewOnlyFormat()));
    143140    }
    144141
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/DoubleArray2XmlFormatters.cs

    r1542 r1564  
    44
    55namespace HeuristicLab.Persistence.Default.Xml.Compact {
    6 
    7   [EmptyStorableClass]
    8   public class DoubleArray2XmlFormatter : NumberArray2XmlFormatterBase {
    9 
    10     public override Type Type {
    11       get {
    12         return typeof(double[]);
    13       }
    14     }
    15 
     6 
     7  public abstract class DoubleArray2XmlFormatterBase<T> : NumberArray2XmlFormatterBase<T> {
     8   
    169    protected override string FormatValue(object o) {
    1710      return ((double)o).ToString("r", CultureInfo.InvariantCulture);
     
    2417
    2518  [EmptyStorableClass]
    26   public class Double2DArray2XmlFormatter : DoubleArray2XmlFormatter {
    27     public override Type Type {
    28       get {
    29         return typeof(double[,]);
    30       }
    31     }
    32   }
     19  public class Double1DArray2XmlFormatter : DoubleArray2XmlFormatterBase<double[]> { }
     20
    3321
    3422  [EmptyStorableClass]
    35   public class Double3DArray2XmlFormatter : DoubleArray2XmlFormatter {
    36     public override Type Type {
    37       get {
    38         return typeof(double[, ,]);
    39       }
    40     }
    41   }
     23  public class Double2DArray2XmlFormatter : DoubleArray2XmlFormatterBase<double[,]> { }
     24
     25  [EmptyStorableClass]
     26  public class Double3DArray2XmlFormatter : DoubleArray2XmlFormatterBase<double[,,]> { }
    4227 
    4328}
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/DoubleList2XmlFormatter.cs

    r1542 r1564  
    88
    99  [EmptyStorableClass]
    10   public class DoubleList2XmlFormatter : NumberEnumeration2XmlFormatterBase {
    11 
    12     public override Type Type {
    13       get {
    14         return typeof(List<double>);
    15       }
    16     }
     10  public class DoubleList2XmlFormatter : NumberEnumeration2XmlFormatterBase<List<double>> {   
    1711
    1812    protected override void Add(IEnumerable enumeration, object o) {
     
    2014    }
    2115
    22     protected override object Instantiate() {
     16    protected override IEnumerable Instantiate() {
    2317      return new List<double>();
    2418    }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/IntArray2XmlFormatters.cs

    r1542 r1564  
    33
    44namespace HeuristicLab.Persistence.Default.Xml.Compact {
    5 
    6   [EmptyStorableClass]
    7   public class IntArray2XmlFormatter : NumberArray2XmlFormatterBase {
    8 
    9     public override Type Type {
    10       get {
    11         return typeof(int[]);
    12       }
    13     }
     5 
     6  public abstract class IntArray2XmlFormatterBase<T> : NumberArray2XmlFormatterBase<T> {   
    147
    158    protected override string FormatValue(object o) {
     
    2215  }
    2316
     17  [EmptyStorableClass]
     18  public class Int1DArray2XmlFormatter : IntArray2XmlFormatterBase<int[]> { }
    2419
    2520  [EmptyStorableClass]
    26   public class Int2DArray2XmlFormatter : IntArray2XmlFormatter {
    27     public override Type Type {
    28       get {
    29         return typeof(int[,]);
    30       }
    31     }
    32   }
    33 
     21  public class Int2DArray2XmlFormatter : IntArray2XmlFormatterBase<int[,]> { }
    3422
    3523  [EmptyStorableClass]
    36   public class Int3DArray2XmlFormatter : IntArray2XmlFormatter {
    37     public override Type Type {
    38       get {
    39         return typeof(int[, ,]);
    40       }
    41     }
    42   }
     24  public class Int3DArray2XmlFormatter : IntArray2XmlFormatterBase<int[,,]> { }
    4325 
    4426}
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/IntList2XmlFormatter.cs

    r1542 r1564  
    77
    88  [EmptyStorableClass]
    9   public class IntList2XmlFormatter : NumberEnumeration2XmlFormatterBase {
    10 
    11     public override Type Type {
    12       get {
    13         return typeof(List<int>);
    14       }
    15     }
    16 
     9  public class IntList2XmlFormatter : NumberEnumeration2XmlFormatterBase<List<int>> {
     10   
    1711    protected override void Add(IEnumerable enumeration, object o) {
    1812      ((List<int>)enumeration).Add((int)o);
    1913    }
    2014
    21     protected override object Instantiate() {
     15    protected override IEnumerable Instantiate() {
    2216      return new List<int>();
    2317    }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/NumberArray2XmlFormatterBase.cs

    r1542 r1564  
    66namespace HeuristicLab.Persistence.Default.Xml.Compact {
    77                                                             
    8   public abstract class NumberArray2XmlFormatterBase : IFormatter {
     8  public abstract class NumberArray2XmlFormatterBase<T> : FormatterBase<T, XmlString> {
    99
    10     public abstract Type Type { get; }
    11     public IFormat Format { get { return XmlFormat.Instance; } }
    1210    protected virtual string Separator { get { return ";"; } }
    1311    protected abstract string FormatValue(object o);
    1412    protected abstract object ParseValue(string o);
    1513
    16     public object DoFormat(object obj) {
    17       Array a = (Array)obj;
     14    public override XmlString Format(T t) {
     15      object o = (object)t;
     16      Array a = (Array)o;
    1817      int[] lengths = new int[a.Rank];
    1918      int[] lowerBounds = new int[a.Rank];
     
    4443        }
    4544      }     
    46       return sb.ToString();
     45      return new XmlString(sb.ToString());
    4746    }
    4847
    49     public object Parse(object o) {
     48    public override T Parse(XmlString x) {
    5049      IEnumerator values =
    51         ((string)o)
    52         .Split(new[] { Separator },
     50        x.Data.Split(new[] { Separator },
    5351        StringSplitOptions.RemoveEmptyEntries).GetEnumerator();
    5452      values.MoveNext();
     
    6462        lowerBounds[i] = int.Parse((string)values.Current);
    6563      }
    66       Array a = Array.CreateInstance(this.Type.GetElementType(), lengths, lowerBounds);
     64      Array a = Array.CreateInstance(this.SourceType.GetElementType(), lengths, lowerBounds);
    6765      int[] positions = new int[rank];
    6866      while (values.MoveNext()) {
     
    7876        }
    7977      }
    80       return a;
     78      object o = a;
     79      return (T)o;
    8180    }
    8281  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/NumberEnumeration2XmlFormatterBase.cs

    r1542 r1564  
    66namespace HeuristicLab.Persistence.Default.Xml.Compact {
    77 
    8   public abstract class NumberEnumeration2XmlFormatterBase : IFormatter {
     8  public abstract class NumberEnumeration2XmlFormatterBase<T> : FormatterBase<T, XmlString> where T : IEnumerable {
    99
    10     public abstract Type Type { get; }
    11     public IFormat Format { get { return XmlFormat.Instance; } }
    1210    protected virtual string Separator { get { return ";"; } }
    1311    protected abstract void Add(IEnumerable enumeration, object o);
    14     protected abstract object Instantiate();
     12    protected abstract IEnumerable Instantiate();
    1513    protected abstract string FormatValue(object o);
    1614    protected abstract object ParseValue(string o);
    1715
    18     public object DoFormat(object o) {
     16    public override XmlString Format(T t) {
    1917      StringBuilder sb = new StringBuilder();
    20       foreach (var value in (IEnumerable)o) {
     18      foreach (var value in (IEnumerable)t) {
    2119        sb.Append(FormatValue(value));
    2220        sb.Append(Separator);
    2321      }
    24       return sb.ToString();
     22      return new XmlString(sb.ToString());
    2523    }
    2624
    27     public object Parse(object o) {
    28       IEnumerable enumeration = (IEnumerable)Instantiate();
    29       string[] values = ((string)o).Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
     25    public override T Parse(XmlString x) {
     26      IEnumerable enumeration = Instantiate();
     27      string[] values = x.Data.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
    3028      foreach (var value in values) {
    3129        Add(enumeration, ParseValue(value));
    3230      }
    33       return enumeration;
     31      return (T)enumeration;
    3432    }
    3533  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/DateTime2XmlFormatter.cs

    r1454 r1564  
    66
    77  [EmptyStorableClass]
    8   public class DateTime2XmlFormatter : IFormatter {   
    9 
    10     public Type Type { get { return typeof(DateTime); } }
    11     public IFormat Format { get { return XmlFormat.Instance; } } 
    12 
    13     public object DoFormat(object o) {
    14       return ((DateTime)o).Ticks.ToString();     
     8  public class DateTime2XmlFormatter : FormatterBase<DateTime, XmlString> {   
     9   
     10    public override XmlString Format(DateTime dt) {
     11      return new XmlString(dt.Ticks.ToString());     
    1512    }
    1613
    17     public object Parse(object o) {
    18       return new DateTime(long.Parse((string)o));
     14    public override DateTime Parse(XmlString x) {
     15      return new DateTime(long.Parse(x.Data));
    1916    }
    2017
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/DecimalNumber2XmlFormatterBase.cs

    r1554 r1564  
    77namespace HeuristicLab.Persistence.Default.Xml.Primitive { 
    88 
    9   public abstract class DecimalNumber2XmlFormatterBase<T> : IFormatter {
    10 
    11     public Type Type { get { return typeof(T); } }
    12 
    13     public IFormat Format { get { return XmlFormat.Instance; } }
    14 
     9  public abstract class DecimalNumber2XmlFormatterBase<T> : FormatterBase<T, XmlString> {
     10   
    1511    private static MethodInfo ToStringMethod = typeof(T)
    1612      .GetMethod(
     
    3127        null);
    3228
    33     public object DoFormat(object o) {
    34       return ToStringMethod.Invoke(o, new object[] { "r", CultureInfo.InvariantCulture });
     29    public override XmlString Format(T t) {
     30      return new XmlString((string)ToStringMethod.Invoke(t, new object[] { "r", CultureInfo.InvariantCulture }));
    3531    }
    36     public object Parse(object o) {     
    37       return ParseMethod.Invoke(null, new[] { o, CultureInfo.InvariantCulture });
     32    public override T Parse(XmlString x) {     
     33      return (T)ParseMethod.Invoke(null, new object[] { x.Data, CultureInfo.InvariantCulture });
    3834    }
    3935  } 
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/SimpleNumber2XmlFormatterBase.cs

    r1554 r1564  
    77namespace HeuristicLab.Persistence.Default.Xml.Primitive { 
    88
    9   public abstract class SimpleNumber2XmlFormatterBase<T> : IFormatter {
    10 
    11     public Type Type { get { return typeof(T); } }
    12 
    13     public IFormat Format { get { return XmlFormat.Instance; } }
     9  public abstract class SimpleNumber2XmlFormatterBase<T> : FormatterBase<T, XmlString> {
    1410
    1511    private static MethodInfo ParseMethod = typeof(T)
     
    2218        null);
    2319
    24     public object DoFormat(object o) {
    25       return ((T)o).ToString();
     20    public override XmlString Format(T t) {
     21      return new XmlString(t.ToString());
    2622    }
    27     public object Parse(object o) {
    28       return ParseMethod.Invoke(null, new[] { o });     
     23    public override T Parse(XmlString x) {
     24      return (T)ParseMethod.Invoke(null, new[] { x.Data });     
    2925    }
    3026  } 
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/String2XmlFormatter.cs

    r1542 r1564  
    88
    99  [EmptyStorableClass]
    10   public class String2XmlFormatter : IFormatter {
    11 
    12     public Type Type { get { return typeof(string); } }
    13     public IFormat Format { get { return XmlFormat.Instance;  } }
    14 
    15     public object DoFormat(object o) {     
    16       return "<![CDATA[" +
    17         ((string)o).Replace("]]>", "]]]]><![CDATA[>") +
    18         "]]>";
     10  public class String2XmlFormatter : FormatterBase<string, XmlString> {
     11   
     12    public override XmlString Format(string s) {
     13      StringBuilder sb = new StringBuilder();
     14      sb.Append("<![CDATA[");
     15      sb.Append(s.Replace("]]>", "]]]]><![CDATA[>"));
     16      sb.Append("]]>");
     17      return new XmlString(sb.ToString()); 
    1918    }
    2019
    21     public object Parse(object o) {
     20    private static readonly string[] separators = new string[] { "<![CDATA[", "]]>" };
     21
     22    public override string Parse(XmlString x) {
    2223      StringBuilder sb = new StringBuilder();
    23       foreach (string s in ((string)o).Split(
    24         new[] { "<![CDATA[", "]]>" },
     24      foreach (string s in x.Data.Split(separators,       
    2525        StringSplitOptions.RemoveEmptyEntries)) {
    2626        sb.Append(s);
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/XmlFormat.cs

    r1542 r1564  
    55
    66  [EmptyStorableClass]
    7   public class XmlFormat : FormatBase {
    8     public override string Name { get { return "XML"; } }
    9     public static readonly XmlFormat Instance = new XmlFormat();
    10     private XmlFormat() { }
     7  public class XmlFormat : FormatBase<XmlString> {
     8    public override string Name { get { return "XML"; } }   
    119  }
    1210
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/XmlGenerator.cs

    r1556 r1564  
    2121    public const string METAINFO = "METAINFO";
    2222  }
    23 
    24   public abstract class Generator<T> {
    25     public T Format(ISerializationToken token) {
    26       Type type = token.GetType();
    27       if (type == typeof(BeginToken))
    28         return Format((BeginToken)token);
    29       if (type == typeof(EndToken))
    30         return Format((EndToken)token);
    31       if (type == typeof(PrimitiveToken))
    32         return Format((PrimitiveToken)token);
    33       if (type == typeof(ReferenceToken))
    34         return Format((ReferenceToken)token);
    35       if (type == typeof(NullReferenceToken))
    36         return Format((NullReferenceToken)token);
    37       if (type == typeof(MetaInfoBeginToken))
    38         return Format((MetaInfoBeginToken)token);
    39       if (type == typeof(MetaInfoEndToken))
    40         return Format((MetaInfoEndToken)token);
    41       throw new ApplicationException("Invalid token of type " + type.FullName);
    42     }
    43     protected abstract T Format(BeginToken beginToken);
    44     protected abstract T Format(EndToken endToken);
    45     protected abstract T Format(PrimitiveToken primitiveToken);
    46     protected abstract T Format(ReferenceToken referenceToken);
    47     protected abstract T Format(NullReferenceToken nullReferenceToken);
    48     protected abstract T Format(MetaInfoBeginToken metaInfoBeginToken);
    49     protected abstract T Format(MetaInfoEndToken metaInfoEndToken);
    50   }
    51 
    52   public class XmlGenerator : Generator<string> {
     23 
     24  public class XmlGenerator : GeneratorBase<string> {
    5325   
    5426    private int depth;
     
    11789      return Prefix +
    11890        FormatNode(XmlStrings.PRIMITIVE, attributes, NodeType.Start) +
    119         dataToken.SerialData + "</" + XmlStrings.PRIMITIVE + ">\r\n";     
     91        ((XmlString)dataToken.SerialData).Data + "</" + XmlStrings.PRIMITIVE + ">\r\n";     
    12092    }
    12193
     
    134106
    135107    protected override string Format(MetaInfoBeginToken metaInfoBeginToken) {
    136       string result = Prefix + "<" + XmlStrings.METAINFO + ">";
     108      string result = Prefix + "<" + XmlStrings.METAINFO + ">\r\n";
    137109      depth += 1;
    138110      return result;
     
    141113    protected override string Format(MetaInfoEndToken metaInfoEndToken) {
    142114      depth -= 1;
    143       return Prefix + "</" + XmlStrings.METAINFO + ">";
     115      return Prefix + "</" + XmlStrings.METAINFO + ">\r\n";
    144116    }
    145117
     
    156128
    157129    public static void Serialize(object o, string filename) {     
    158       Serialize(o, filename, ConfigurationService.Instance.GetDefaultConfig(XmlFormat.Instance));
     130      Serialize(o, filename, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
    159131    }
    160132
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/XmlParser.cs

    r1556 r1564  
    6262        int.Parse(reader.GetAttribute("typeId")),
    6363        id,
    64         reader.ReadString());       
     64        new XmlString(reader.ReadString()));
    6565    }
    6666
     
    6969      string idString = reader.GetAttribute("id");
    7070      int? id = null;
    71       int? typeId = null;
    7271      if (idString != null)
    7372        id = int.Parse(idString);
    74         typeId = int.Parse(reader.GetAttribute("typeId"));
     73      int typeId = int.Parse(reader.GetAttribute("typeId"));
    7574      yield return new BeginToken(name, typeId, id);
    7675      IEnumerator<ISerializationToken> iterator = GetEnumerator();
  • trunk/sources/HeuristicLab.Persistence/3.3/HeuristicLab.Persistence-3.3.csproj

    r1556 r1564  
    9595    <Compile Include="Core\Configuration.cs" />
    9696    <Compile Include="Core\EmptyStorableClassAttribute.cs" />
     97    <Compile Include="Core\FormatBase.cs" />
     98    <Compile Include="Core\FormatterBase.cs" />
    9799    <Compile Include="Core\TypeExtensions.cs" />
    98100    <Compile Include="Core\TypeMapping.cs" />
    99101    <Compile Include="Core\TypeStringBuilder.cs" />
     102    <Compile Include="Core\GeneratorBase.cs" />
    100103    <Compile Include="Default\Decomposers\ArrayDecomposer.cs" />
    101104    <Compile Include="Default\Decomposers\EnumerableDecomposer.cs" />
     
    106109    <Compile Include="Default\Decomposers\TypeDecomposer.cs" />
    107110    <Compile Include="Default\Decomposers\X2StringDecomposer.cs" />
    108     <Compile Include="Default\ViewOnly\ViewOnlyFormat.cs" />
     111    <Compile Include="Default\ViewOnly\ViewOnlyFormat.cs">
     112      <SubType>Code</SubType>
     113    </Compile>
    109114    <Compile Include="Default\Xml\Compact\IntArray2XmlFormatters.cs" />
    110115    <Compile Include="Default\Xml\Compact\DoubleArray2XmlFormatters.cs" />
     
    114119    <Compile Include="Core\DataMemberAccessor.cs" />
    115120    <Compile Include="Default\Xml\Compact\IntList2XmlFormatter.cs" />
     121    <Compile Include="Default\Xml\XmlString.cs" />
    116122    <Compile Include="Default\Xml\Primitive\Double2XmlFormatter.cs" />
    117123    <Compile Include="Default\Xml\Primitive\Decimal2XmlFormatter.cs" />
     
    134140    <Compile Include="Core\Deserializer.cs" />
    135141    <Compile Include="Core\Tag.cs" />
     142    <Compile Include="Interfaces\ISerialData.cs" />
    136143    <Compile Include="Interfaces\IFormat.cs" />
    137     <Compile Include="Core\FormatBase.cs" />
    138144    <Compile Include="Interfaces\IDecomposer.cs" />
    139145    <Compile Include="Interfaces\IFormatter.cs" />
  • trunk/sources/HeuristicLab.Persistence/3.3/Interfaces/IFormat.cs

    r1542 r1564  
    33namespace HeuristicLab.Persistence.Interfaces {
    44
     5  /// <summary>
     6  /// Interface of a new serialization output format. Instead of implementing this
     7  /// interface, derive from FormatBase.
     8  /// </summary>
    59  public interface IFormat {
    610    string Name { get; }
     11    Type SerialDataType { get; }
     12  }
     13
     14  /// <summary>
     15  /// Marker interface for new serialization output format.  Instead of implementing this
     16  /// interface, derive from FormatBase.
     17  /// </summary> 
     18  public interface IFormat<SerialDataFormat> : IFormat where SerialDataFormat : ISerialData {
    719  }
    820
  • trunk/sources/HeuristicLab.Persistence/3.3/Interfaces/IFormatter.cs

    r1542 r1564  
    33namespace HeuristicLab.Persistence.Interfaces {
    44
     5  /// <summary>
     6  /// Marker interface of serial data formatters. Transform data of type SourceType
     7  /// into the serialization format SerialDataType. Derive from FormatterBase instead
     8  /// of implementing this interface.
     9  /// </summary>
    510  public interface IFormatter {
    6     Type Type { get; }
    7     IFormat Format { get; }
    8     object DoFormat(object o);
    9     object Parse(object o);
     11    Type SerialDataType { get; }
     12    Type SourceType { get; }
     13    ISerialData Format(object o);
     14    object Parse(ISerialData o); 
    1015  }
    1116
     17  /// <summary>
     18  /// Marker interface of serial data formatters. Transform data of type Source
     19  /// into the serialization format SerialData. Derive from FormatterBase instead
     20  /// of implementing this interface.
     21  /// </summary> 
     22  public interface IFormatter<Source, SerialData> : IFormatter where SerialData : ISerialData {
     23    SerialData Format(Source o);
     24    Source Parse(SerialData t);
     25  } 
     26     
    1227}
Note: See TracChangeset for help on using the changeset viewer.