Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
06/12/14 13:26:18 (10 years ago)
Author:
pfleck
Message:
  • Merged trunk into preprocessing branch.
Location:
branches/DataPreprocessing
Files:
7 edited

Legend:

Unmodified
Added
Removed
  • branches/DataPreprocessing

  • branches/DataPreprocessing/HeuristicLab.Persistence

  • branches/DataPreprocessing/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Number2StringSerializer.cs

    r9456 r11009  
    7878    /// </returns>
    7979    public bool CanSerialize(Type type) {
    80       return numberSerializerMap.ContainsKey(type);
     80      return numberSerializerMap.ContainsKey(Nullable.GetUnderlyingType(type) ?? type);
    8181    }
    8282
     
    9090    /// </returns>
    9191    public string JustifyRejection(Type type) {
    92       return string.Format("not a number type (one of {0})",
     92      return string.Format("not a (nullable) number type (one of {0})",
    9393        string.Join(", ", numberSerializers.Select(n => n.SourceType.Name).ToArray()));
    9494    }
     
    100100    /// <returns></returns>
    101101    public string Format(object obj) {
    102       return ((XmlString)numberSerializerMap[obj.GetType()].Format(obj)).Data;
     102      if (obj == null) return "null";
     103      Type type = obj.GetType();
     104      return ((XmlString)numberSerializerMap[Nullable.GetUnderlyingType(type) ?? type].Format(obj)).Data;
    103105    }
    104106
     
    110112    /// <returns></returns>
    111113    public object Parse(string stringValue, Type type) {
     114      if (stringValue == "null") return null;
    112115      try {
    113         return numberSerializerMap[type].Parse(new XmlString(stringValue));
     116        return numberSerializerMap[Nullable.GetUnderlyingType(type) ?? type].Parse(new XmlString(stringValue));
    114117      }
    115118      catch (FormatException e) {
  • branches/DataPreprocessing/HeuristicLab.Persistence/3.3/Default/CompositeSerializers/Storable/StorableSerializer.cs

    r9456 r11009  
    4747      hookCache = new Dictionary<HookDesignator, List<StorableReflection.Hook>>();
    4848    }
     49
    4950    [StorableConstructor]
    5051    private StorableSerializer(bool deserializing) : this() { }
     
    6869    /// </returns>
    6970    public bool CanSerialize(Type type) {
    70       bool markedStorable = StorableReflection.HasStorableClassAttribute(type);
     71      var markedStorable = StorableReflection.HasStorableClassAttribute(type);
    7172      if (GetConstructor(type) == null)
    7273        if (markedStorable)
     
    9192    /// </returns>
    9293    public string JustifyRejection(Type type) {
    93       StringBuilder sb = new StringBuilder();
     94      var sb = new StringBuilder();
    9495      if (GetConstructor(type) == null)
    9596        sb.Append("class has no default constructor and no [StorableConstructor]");
     
    117118    /// <returns>An enumerable of <see cref="Tag"/>s.</returns>
    118119    public IEnumerable<Tag> Decompose(object obj) {
    119       foreach (var accessor in GetStorableAccessors(obj.GetType())) {
    120         if (accessor.Get != null)
    121           yield return new Tag(accessor.Name, accessor.Get(obj));
    122       }
     120      return from accessor in GetStorableAccessors(obj.GetType())
     121             where accessor.Get != null
     122             select new Tag(accessor.Name, accessor.Get(obj));
    123123    }
    124124
     
    147147    public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
    148148      var memberDict = new Dictionary<string, Tag>();
    149       IEnumerator<Tag> iter = objects.GetEnumerator();
     149      var iter = objects.GetEnumerator();
    150150      while (iter.MoveNext()) {
    151151        memberDict.Add(iter.Current.Name, iter.Current);
     
    170170      BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
    171171
    172     private static readonly object[] emptyArgs = new object[] { };
    173     private static readonly object[] trueArgs = new object[] { true };
    174 
    175     private sealed class HookDesignator {
    176       public Type Type { get; private set; }
    177       public HookType HookType { get; private set; }
    178       public HookDesignator() { }
    179       public HookDesignator(Type type, HookType hookType) {
    180         Type = type;
    181         HookType = HookType;
    182       }
     172    private sealed class HookDesignator : Tuple<Type, HookType> {
     173      public HookDesignator(Type type, HookType hookType) : base(type, hookType) { }
    183174    }
    184175
     
    191182    #region caches
    192183
    193     private AccessorListCache accessorListCache;
    194     private AccessorCache accessorCache;
    195     private Dictionary<Type, Constructor> constructorCache;
    196     private Dictionary<HookDesignator, List<StorableReflection.Hook>> hookCache;
     184    private readonly AccessorListCache accessorListCache;
     185    private readonly AccessorCache accessorCache;
     186    private readonly Dictionary<Type, Constructor> constructorCache;
     187    private readonly Dictionary<HookDesignator, List<StorableReflection.Hook>> hookCache;
    197188
    198189    #endregion
     
    206197        var storableMembers = StorableReflection
    207198          .GenerateStorableMembers(type)
    208           .Select(mi => GetMemberAccessor(mi));
     199          .Select(GetMemberAccessor)
     200          .ToList();
    209201        accessorListCache[type] = storableMembers;
    210202        return storableMembers;
     
    216208        if (accessorCache.ContainsKey(mi.MemberInfo))
    217209          return new DataMemberAccessor(accessorCache[mi.MemberInfo], mi.DisentangledName, mi.DefaultValue);
    218         DataMemberAccessor dma = new DataMemberAccessor(mi.MemberInfo, mi.DisentangledName, mi.DefaultValue);
     210        var dma = new DataMemberAccessor(mi.MemberInfo, mi.DisentangledName, mi.DefaultValue);
    219211        accessorCache[mi.MemberInfo] = dma;
    220212        return dma;
     
    226218        if (constructorCache.ContainsKey(type))
    227219          return constructorCache[type];
    228         Constructor c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
     220        var c = FindStorableConstructor(type) ?? GetDefaultConstructor(type);
    229221        constructorCache.Add(type, c);
    230222        return c;
     
    233225
    234226    private Constructor GetDefaultConstructor(Type type) {
    235       ConstructorInfo ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
     227      var ci = type.GetConstructor(ALL_CONSTRUCTORS, null, Type.EmptyTypes, null);
    236228      if (ci == null)
    237229        return null;
    238       DynamicMethod dm = new DynamicMethod("", typeof(object), null, type, true);
    239       ILGenerator ilgen = dm.GetILGenerator();
     230      var dm = new DynamicMethod("", typeof(object), null, type, true);
     231      var ilgen = dm.GetILGenerator();
    240232      ilgen.Emit(OpCodes.Newobj, ci);
    241233      ilgen.Emit(OpCodes.Ret);
     
    244236
    245237    private Constructor FindStorableConstructor(Type type) {
    246       foreach (ConstructorInfo ci in type.GetConstructors(ALL_CONSTRUCTORS)) {
    247         if (ci.GetCustomAttributes(typeof(StorableConstructorAttribute), false).Length > 0) {
    248           if (ci.GetParameters().Length != 1 ||
    249               ci.GetParameters()[0].ParameterType != typeof(bool))
    250             throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
    251           DynamicMethod dm = new DynamicMethod("", typeof(object), null, type, true);
    252           ILGenerator ilgen = dm.GetILGenerator();
    253           ilgen.Emit(OpCodes.Ldc_I4_1); // load true
    254           ilgen.Emit(OpCodes.Newobj, ci);
    255           ilgen.Emit(OpCodes.Ret);
    256           return (Constructor)dm.CreateDelegate(typeof(Constructor));
    257         }
     238      foreach (var ci in type
     239        .GetConstructors(ALL_CONSTRUCTORS)
     240        .Where(ci => ci.GetCustomAttributes(typeof(StorableConstructorAttribute), false).Length > 0)) {
     241        if (ci.GetParameters().Length != 1 ||
     242            ci.GetParameters()[0].ParameterType != typeof(bool))
     243          throw new PersistenceException("StorableConstructor must have exactly one argument of type bool");
     244        var dm = new DynamicMethod("", typeof(object), null, type, true);
     245        var ilgen = dm.GetILGenerator();
     246        ilgen.Emit(OpCodes.Ldc_I4_1); // load true
     247        ilgen.Emit(OpCodes.Newobj, ci);
     248        ilgen.Emit(OpCodes.Ret);
     249        return (Constructor)dm.CreateDelegate(typeof(Constructor));
    258250      }
    259251      return null;
     
    262254    private void InvokeHook(HookType hookType, object obj) {
    263255      if (obj == null)
    264         throw new ArgumentNullException("Cannot invoke hooks on null");
    265       foreach (StorableReflection.Hook hook in GetHooks(hookType, obj.GetType())) {
     256        throw new ArgumentNullException("obj");
     257      foreach (var hook in GetHooks(hookType, obj.GetType())) {
    266258        hook(obj);
    267259      }
  • branches/DataPreprocessing/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/Char2XmlFormatter.cs

    r9456 r11009  
    2020#endregion
    2121
     22using System;
     23using System.Text;
     24using System.Text.RegularExpressions;
    2225using HeuristicLab.Persistence.Core;
    2326using HeuristicLab.Persistence.Interfaces;
     
    2730  internal sealed class Char2XmlSerializer : PrimitiveSerializerBase<char, XmlString> {
    2831
     32    private static readonly Regex base64Regex = new Regex("<Base64>(.+)</Base64>");
     33
     34    private static bool IsSpecial(char c) {
     35      return c <= 0x1F && c != 0x9 && c != 0xA && c != 0xD;
     36    }
     37
     38    private static string ToBase64String(char c) {
     39      return string.Format("<Base64>{0}</Base64>", Convert.ToBase64String(Encoding.ASCII.GetBytes(new[] {c})));
     40    }
     41
    2942    public override XmlString Format(char c) {
    30       return new XmlString(new string(c, 1));
     43      return new XmlString(IsSpecial(c) ? ToBase64String(c) : new string(c, 1));
    3144    }
    3245
    3346    public override char Parse(XmlString x) {
    34       if (x.Data.Length != 1)
    35         throw new PersistenceException("Invalid character format, XML string length != 1");
    36       return x.Data[0];
     47      if (x.Data.Length <= 1) return x.Data[0];
     48      var m = base64Regex.Match(x.Data);
     49      if (m.Success)
     50        return Encoding.ASCII.GetString(Convert.FromBase64String(m.Groups[1].Value))[0];
     51      throw new PersistenceException("Invalid character format, XML string length != 1");
    3752    }
    3853  }
  • branches/DataPreprocessing/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/String2XmlSerializer.cs

    r9456 r11009  
    2020#endregion
    2121
     22using System;
    2223using System.Text;
    2324using System.Text.RegularExpressions;
    2425using HeuristicLab.Persistence.Core;
    25 
    2626
    2727namespace HeuristicLab.Persistence.Default.Xml.Primitive {
     
    4242      sb.Append(s.Replace("]]>", "]]]]><![CDATA[>"));
    4343      sb.Append("]]>");
    44       return new XmlString(sb.ToString());
     44      s = special.Replace(sb.ToString(), m => ToBase64Tag(m.Value));
     45      return new XmlString(s);
    4546    }
    4647
    47     private static Regex re = new Regex(@"<!\[CDATA\[((?:[^]]|\](?!\]>))*)\]\]>", RegexOptions.Singleline);
     48    private static readonly Regex re = new Regex(@"<!\[CDATA\[((?:[^]]|\](?!\]>))*)\]\]>|<Base64>([^<]*)</Base64>", RegexOptions.Singleline);
     49    private static readonly Regex special = new Regex(@"[\x00-\x08\x0b\x0c\x0e-\x1f]+", RegexOptions.Singleline);
     50
     51    private static string ToBase64Tag(string s) {
     52      return new StringBuilder()
     53        .Append("]]><Base64>")
     54        .Append(Convert.ToBase64String(Encoding.ASCII.GetBytes(s)))
     55        .Append("</Base64><![CDATA[")
     56        .ToString();
     57    }
    4858
    4959    /// <summary>
     
    5565      StringBuilder sb = new StringBuilder();
    5666      foreach (Match m in re.Matches(x.Data)) {
    57         sb.Append(m.Groups[1]);
     67        if (m.Groups[1].Success)
     68          sb.Append(m.Groups[1].Value);
     69        else if (m.Groups[2].Success) {
     70          sb.Append(Encoding.ASCII.GetString(Convert.FromBase64String(m.Groups[2].Value)));
     71        }
    5872      }
    5973      string result = sb.ToString();
  • branches/DataPreprocessing/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/System.Drawing/Font2XmlSerializer.cs

    r9988 r11009  
    2828    public override XmlString Format(Font font) {
    2929      return new XmlString(string.Format("{0};{1};{2};{3};{4};{5}",
    30         font.FontFamily.Name,
     30        GetFontFamilyName(font.FontFamily),
    3131        Float2XmlSerializer.FormatG8(font.Size),
    3232        font.Style,
     
    3939      string[] tokens = fontData.Data.Split(';');
    4040      return new Font(
    41         tokens[0],
     41        GetFontFamily(tokens[0]),
    4242        Float2XmlSerializer.ParseG8(tokens[1]),
    4343        (FontStyle)Enum.Parse(typeof(FontStyle), tokens[2]),
     
    4646        bool.Parse(tokens[5]));
    4747    }
     48
     49    public const string GENERIC_MONOSPACE_NAME = "_GenericMonospace";
     50    public const string GENERIC_SANS_SERIF_NAME = "_GenericSansSerif";
     51    public const string GENERIC_SERIF_NAME = "_GenericSerif";
     52
     53    public static FontFamily GetFontFamily(string name) {
     54      if (name == GENERIC_MONOSPACE_NAME) return FontFamily.GenericMonospace;
     55      if (name == GENERIC_SANS_SERIF_NAME) return FontFamily.GenericSansSerif;
     56      if (name == GENERIC_SERIF_NAME) return FontFamily.GenericSerif;
     57      return new FontFamily(name);
     58    }
     59
     60    public static string GetFontFamilyName(FontFamily ff) {
     61      if (ff.Equals(FontFamily.GenericMonospace)) return GENERIC_MONOSPACE_NAME;
     62      if (ff.Equals(FontFamily.GenericSansSerif)) return GENERIC_SANS_SERIF_NAME;
     63      if (ff.Equals(FontFamily.GenericSerif)) return GENERIC_SERIF_NAME;
     64      return ff.Name;
     65    }
     66
    4867  }
    4968}
Note: See TracChangeset for help on using the changeset viewer.