Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
04/23/09 14:22:29 (16 years ago)
Author:
epitzer
Message:

Added PersistenceException used consistently for all error conditions in the persistence framework (#548)

Location:
trunk/sources/HeuristicLab.Persistence/3.3/Default
Files:
1 deleted
20 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/ArrayDecomposer.cs

    r1623 r1625  
    5454    }
    5555
    56     public object CreateInstance(Type t, IEnumerable<Tag> metaInfo) {
    57       IEnumerator<Tag> e = metaInfo.GetEnumerator();
    58       e.MoveNext();
    59       int rank = (int)e.Current.Value;
    60       int[] lengths = new int[rank];
    61       for (int i = 0; i < rank; i++) {
     56    public object CreateInstance(Type t, IEnumerable<Tag> metaInfo) {     
     57      try {
     58        IEnumerator<Tag> e = metaInfo.GetEnumerator();
    6259        e.MoveNext();
    63         lengths[i] = (int)e.Current.Value;
    64       }
    65       int[] lowerBounds = new int[rank];
    66       for (int i = 0; i < rank; i++) {
    67         e.MoveNext();
    68         lowerBounds[i] = (int)e.Current.Value;
    69       }
    70       return Array.CreateInstance(t.GetElementType(), lengths, lowerBounds);
     60        int rank = (int)e.Current.Value;
     61        int[] lengths = new int[rank];
     62        for (int i = 0; i < rank; i++) {
     63          e.MoveNext();
     64          lengths[i] = (int)e.Current.Value;
     65        }
     66        int[] lowerBounds = new int[rank];
     67        for (int i = 0; i < rank; i++) {
     68          e.MoveNext();
     69          lowerBounds[i] = (int)e.Current.Value;
     70        }
     71        return Array.CreateInstance(t.GetElementType(), lengths, lowerBounds);
     72      } catch (InvalidOperationException x) {
     73        throw new PersistenceException("Insufficient meta information to construct array instance.", x);
     74      } catch (InvalidCastException x) {
     75        throw new PersistenceException("Invalid format of array metainfo.", x);
     76      }     
    7177    }
    7278
     
    8389      int[] positions = (int[])lowerBounds.Clone();
    8490      IEnumerator<Tag> e = elements.GetEnumerator();
    85       while (e.MoveNext()) {
    86         int[] currentPositions = positions;
    87         a.SetValue(e.Current.Value, currentPositions);
    88         positions[0] += 1;
    89         for (int i = 0; i < a.Rank - 1; i++) {
    90           if (positions[i] >= lengths[i] + lowerBounds[i]) {
    91             positions[i] = lowerBounds[i];
    92             positions[i + 1] += 1;
    93           } else {
    94             break;
     91      try {
     92        while (e.MoveNext()) {
     93          int[] currentPositions = positions;
     94          a.SetValue(e.Current.Value, currentPositions);
     95          positions[0] += 1;
     96          for (int i = 0; i < a.Rank - 1; i++) {
     97            if (positions[i] >= lengths[i] + lowerBounds[i]) {
     98              positions[i] = lowerBounds[i];
     99              positions[i + 1] += 1;
     100            } else {
     101              break;
     102            }
    95103          }
    96104        }
     105      } catch (InvalidOperationException x) {
     106        throw new PersistenceException("Insufficient data to fill array instance", x);
     107      } catch (InvalidCastException x) {
     108        throw new PersistenceException("Invalid element data. Cannot fill array", x);
     109      } catch (IndexOutOfRangeException x) {
     110        throw new PersistenceException("Too many elements during array deserialization", x);
    97111      }
    98112    }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/CompactNumberArray2StringDecomposer.cs

    r1623 r1625  
    6161
    6262    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
    63       var tagIter = metaInfo.GetEnumerator();
    64       tagIter.MoveNext();
    65       var valueIter = ((string)tagIter.Current.Value)
    66         .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
    67         .GetEnumerator();
    68       valueIter.MoveNext();
    69       int rank = int.Parse((string)valueIter.Current);
    70       int[] lengths = new int[rank];
    71       int[] lowerBounds = new int[rank];
    72       for (int i = 0; i < rank; i++) {
     63      try {
     64        var tagIter = metaInfo.GetEnumerator();
     65        tagIter.MoveNext();     
     66        var valueIter = ((string)tagIter.Current.Value)
     67          .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
     68          .GetEnumerator();
    7369        valueIter.MoveNext();
    74         lengths[i] = int.Parse((string)valueIter.Current);
    75       }
    76       for (int i = 0; i < rank; i++) {
    77         valueIter.MoveNext();
    78         lowerBounds[i] = int.Parse((string)valueIter.Current);
    79       }
    80       Type elementType = type.GetElementType();
    81       Array a = Array.CreateInstance(elementType, lengths, lowerBounds);
    82       int[] positions = (int[])lowerBounds.Clone();
    83       while (valueIter.MoveNext()) {
    84         a.SetValue(
    85           numberConverter.Parse((string)valueIter.Current, elementType),
    86           positions);
    87         positions[0] += 1;
    88         for (int i = 0; i < rank - 1; i++) {
    89           if (positions[i] >= lengths[i] + lowerBounds[i]) {
    90             positions[i + 1] += 1;
    91             positions[i] = lowerBounds[i];
    92           } else {
    93             break;
     70        int rank = int.Parse((string)valueIter.Current);
     71        int[] lengths = new int[rank];
     72        int[] lowerBounds = new int[rank];
     73        for (int i = 0; i < rank; i++) {
     74          valueIter.MoveNext();
     75          lengths[i] = int.Parse((string)valueIter.Current);
     76        }
     77        for (int i = 0; i < rank; i++) {
     78          valueIter.MoveNext();
     79          lowerBounds[i] = int.Parse((string)valueIter.Current);
     80        }
     81        Type elementType = type.GetElementType();
     82        Array a = Array.CreateInstance(elementType, lengths, lowerBounds);
     83        int[] positions = (int[])lowerBounds.Clone();
     84        while (valueIter.MoveNext()) {
     85          a.SetValue(
     86            numberConverter.Parse((string)valueIter.Current, elementType),
     87            positions);
     88          positions[0] += 1;
     89          for (int i = 0; i < rank - 1; i++) {
     90            if (positions[i] >= lengths[i] + lowerBounds[i]) {
     91              positions[i + 1] += 1;
     92              positions[i] = lowerBounds[i];
     93            } else {
     94              break;
     95            }
    9496          }
    9597        }
    96       }
    97       return a;
     98        return a;
     99      } catch (InvalidOperationException e) {
     100        throw new PersistenceException("Insufficient data to deserialize compact array", e);
     101      } catch (InvalidCastException e) {
     102        throw new PersistenceException("Invalid element data during compact array deserialization", e);
     103      }     
    98104    }
    99105
    100106    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
     107      // Nothing to do: Compact arrays are already populated during instance creation.
    101108    }
    102109
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/DictionaryDecomposer.cs

    r1623 r1625  
    3939      IDictionary dict = (IDictionary)instance;
    4040      IEnumerator<Tag> iter = o.GetEnumerator();
    41       while (iter.MoveNext()) {
    42         Tag key = iter.Current;
    43         iter.MoveNext();
    44         Tag value = iter.Current;
    45         dict.Add(key.Value, value.Value);
    46       }
     41      try {
     42        while (iter.MoveNext()) {
     43          Tag key = iter.Current;
     44          iter.MoveNext();
     45          Tag value = iter.Current;
     46          dict.Add(key.Value, value.Value);
     47        }
     48      } catch (InvalidOperationException e) {
     49        throw new PersistenceException("Dictionaries must contain an even number of elements (key+value).", e);
     50      } catch (NotSupportedException e) {
     51        throw new PersistenceException("The serialized dictionary type was read-only or had a fixed size and cannot be deserialized.", e);
     52      } catch (ArgumentNullException e) {
     53        throw new PersistenceException("Dictionary key was null.", e);
     54      } catch (ArgumentException e) {
     55        throw new PersistenceException("Duplicate dictionary key.", e);
     56      }     
    4757    }
    4858  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/EnumDecomposer.cs

    r1623 r1625  
    2828    public object CreateInstance(Type t, IEnumerable<Tag> metaInfo) {
    2929      IEnumerator<Tag> it = metaInfo.GetEnumerator();
    30       it.MoveNext();
    31       return Enum.Parse(t, (string)it.Current.Value);
     30      try {
     31        it.MoveNext();
     32        return Enum.Parse(t, (string)it.Current.Value);
     33      } catch (InvalidOperationException e) {
     34        throw new PersistenceException("not enough meta information to recstruct enum", e);
     35      } catch (InvalidCastException e) {
     36        throw new PersistenceException("invalid meta information found while trying to reconstruct enum", e);
     37      }
    3238    }
    3339
    3440    public void Populate(object instance, IEnumerable<Tag> elements, Type t) {
     41      // Enums are already populated during instance creation.
    3542    }
    3643  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/EnumerableDecomposer.cs

    r1623 r1625  
    4545    public void Populate(object instance, IEnumerable<Tag> tags, Type type) {
    4646      MethodInfo addMethod = type.GetMethod("Add");
    47       foreach (var tag in tags)
    48         addMethod.Invoke(instance, new[] { tag.Value });
     47      try {
     48        foreach (var tag in tags)
     49          addMethod.Invoke(instance, new[] { tag.Value });
     50      } catch (Exception e) {
     51        throw new PersistenceException("Exception caught while trying to populate enumerable.", e);
     52      }
    4953    }
    5054  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/KeyValuePairDecomposer.cs

    r1623 r1625  
    2929    public IEnumerable<Tag> Decompose(object o) {
    3030      Type t = o.GetType();
    31       yield return new Tag("key", t.GetProperty("Key").GetValue(o, null));
    32       yield return new Tag("value", t.GetProperty("Value").GetValue(o, null));
     31      Tag key, value;
     32      try {
     33        key = new Tag("key", t.GetProperty("Key").GetValue(o, null));       
     34      } catch (Exception e) {
     35        throw new PersistenceException("Exception caught during KeyValuePair decomposition", e);
     36      }
     37      yield return key;
     38      try {
     39        value = new Tag("value", t.GetProperty("Value").GetValue(o, null));
     40      } catch (Exception e) {
     41        throw new PersistenceException("Exception caught during KeyValuePair decomposition", e);
     42      }
     43      yield return value;
    3344    }
    3445
     
    3950    public void Populate(object instance, IEnumerable<Tag> o, Type t) {
    4051      IEnumerator<Tag> iter = o.GetEnumerator();
    41       iter.MoveNext();
    42       t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
    43         .Single(fi => fi.Name == "key").SetValue(instance, iter.Current.Value);
    44       iter.MoveNext();
    45       t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
    46         .Single(fi => fi.Name == "value").SetValue(instance, iter.Current.Value);
     52      try {
     53        iter.MoveNext();
     54        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
     55          .Single(fi => fi.Name == "key").SetValue(instance, iter.Current.Value);
     56        iter.MoveNext();
     57        t.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)
     58          .Single(fi => fi.Name == "value").SetValue(instance, iter.Current.Value);
     59      } catch (InvalidOperationException e) {
     60        throw new PersistenceException("Not enough components to populate KeyValuePair instance", e);
     61      } catch (Exception e) {
     62        throw new PersistenceException("Exception caught during KeyValuePair reconstruction", e);
     63      }
    4764    }
    4865  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/Number2StringConverter.cs

    r1567 r1625  
    5353
    5454    public object Parse(string stringValue, Type type) {
    55       return numberParsers[type]
    56         .Invoke(null,
    57             BindingFlags.Static | BindingFlags.PutRefDispProperty,
    58                   null, new[] { stringValue }, CultureInfo.InvariantCulture);
     55      try {       
     56        return numberParsers[type]
     57          .Invoke(null,
     58              BindingFlags.Static | BindingFlags.PutRefDispProperty,
     59                    null, new[] { stringValue }, CultureInfo.InvariantCulture);
     60      } catch (FormatException e) {
     61        throw new PersistenceException("Invalid element data during number parsing.", e);
     62      } catch (OverflowException e) {
     63        throw new PersistenceException("Overflow during number parsing.", e);
     64      }
    5965    }
    6066
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/NumberEnumerable2StringDecomposer.cs

    r1623 r1625  
    9191      Type elementType = enumerable.GetGenericArguments()[0];
    9292      MethodInfo addMethod = type.GetMethod("Add");
    93       var tagEnumerator = tags.GetEnumerator();
    94       tagEnumerator.MoveNext();
    95       string[] stringValues = ((string)tagEnumerator.Current.Value)
    96         .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
    97       foreach (var value in stringValues) {
    98         addMethod.Invoke(instance, new[] { numberConverter.Parse(value, elementType) });
     93      try {
     94        var tagEnumerator = tags.GetEnumerator();
     95        tagEnumerator.MoveNext();
     96        string[] stringValues = ((string)tagEnumerator.Current.Value)
     97          .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
     98        foreach (var value in stringValues) {
     99          addMethod.Invoke(instance, new[] { numberConverter.Parse(value, elementType) });
     100        }
     101      } catch (InvalidOperationException e) {
     102        throw new PersistenceException("Insufficient element data to reconstruct number enumerable", e);
     103      } catch (InvalidCastException e) {
     104        throw new PersistenceException("Invalid element data during reconstruction of number enumerable", e);
    99105      }
    100106    }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/Storable/DataMemberAccessor.cs

    r1623 r1625  
    11using System;
    22using System.Reflection;
     3using HeuristicLab.Persistence.Core;
    34
    45namespace HeuristicLab.Persistence.Default.Decomposers.Storable {
     
    2223        PropertyInfo propertyInfo = (PropertyInfo)memberInfo;
    2324        if (!propertyInfo.CanRead || !propertyInfo.CanWrite) {
    24           throw new NotSupportedException(
     25          throw new PersistenceException(
    2526            "Storable properties must implement both a Get and a Set Accessor. ");
    2627        }
     
    2829        Set = value => propertyInfo.SetValue(obj, value, null);
    2930      } else {
    30         throw new NotSupportedException(
     31        throw new PersistenceException(
    3132          "The Storable attribute can only be applied to fields and properties.");
    3233      }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Decomposers/TypeDecomposer.cs

    r1623 r1625  
    2828
    2929    public object CreateInstance(Type type, IEnumerable<Tag> metaInfo) {
    30       foreach (var typeName in metaInfo) {
    31         return Type.GetType((string)typeName.Value);
     30      IEnumerator<Tag> it = metaInfo.GetEnumerator();
     31      try {
     32        it.MoveNext();
     33      } catch (InvalidOperationException e) {
     34        throw new PersistenceException("Insufficient meta information to instantiate Type object", e);
    3235      }
    33       return null;
     36      try {
     37        return Type.GetType((string)it.Current.Value, true);
     38      } catch (InvalidCastException e) {
     39        throw new PersistenceException("Invalid meta information during reconstruction of Type object", e);
     40      } catch (TypeLoadException e) {
     41        throw new PersistenceException(String.Format(
     42          "Cannot load Type {0}, make sure all required assemblies are available.",
     43          (string)it.Current.Value), e);
     44      }
    3445    }
    3546
    3647    public void Populate(object instance, IEnumerable<Tag> objects, Type type) {
     48      // Type ojects are populated during instance creation.
    3749    }
    3850  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/DoubleArray2XmlFormatters.cs

    r1612 r1625  
    22using HeuristicLab.Persistence.Core;
    33using System.Globalization;
     4using HeuristicLab.Persistence.Default.Decomposers.Storable;
    45
    56namespace HeuristicLab.Persistence.Default.Xml.Compact {
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/IntArray2XmlFormatters.cs

    r1612 r1625  
    11using System;
    22using HeuristicLab.Persistence.Core;
     3using HeuristicLab.Persistence.Default.Decomposers.Storable;
    34
    45namespace HeuristicLab.Persistence.Default.Xml.Compact {
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/NumberArray2XmlFormatterBase.cs

    r1612 r1625  
    33using HeuristicLab.Persistence.Interfaces;
    44using System;
     5using HeuristicLab.Persistence.Core;
    56
    67namespace HeuristicLab.Persistence.Default.Xml.Compact {
     
    4647
    4748    public override T Parse(XmlString x) {
    48       IEnumerator values =
    49         x.Data.Split(new[] { Separator },
    50         StringSplitOptions.RemoveEmptyEntries).GetEnumerator();
    51       values.MoveNext();
    52       int rank = int.Parse((string)values.Current);
    53       int[] lengths = new int[rank];
    54       for (int i = 0; i < rank; i++) {
     49      try {
     50        IEnumerator values =
     51          x.Data.Split(new[] { Separator },
     52          StringSplitOptions.RemoveEmptyEntries).GetEnumerator();
    5553        values.MoveNext();
    56         lengths[i] = int.Parse((string)values.Current);
    57       }
    58       int[] lowerBounds = new int[rank];
    59       for (int i = 0; i < rank; i++) {
    60         values.MoveNext();
    61         lowerBounds[i] = int.Parse((string)values.Current);
    62       }
    63       Array a = Array.CreateInstance(this.SourceType.GetElementType(), lengths, lowerBounds);
    64       int[] positions = new int[rank];
    65       while (values.MoveNext()) {
    66         a.SetValue(ParseValue((string)values.Current), positions);
    67         positions[0] += 1;
    68         for (int i = 0; i < rank - 1; i++) {
    69           if (positions[i] >= lengths[i]) {
    70             positions[i] = 0;
    71             positions[i + 1] += 1;
    72           } else {
    73             break;
     54        int rank = int.Parse((string)values.Current);
     55        int[] lengths = new int[rank];
     56        for (int i = 0; i < rank; i++) {
     57          values.MoveNext();
     58          lengths[i] = int.Parse((string)values.Current);
     59        }
     60        int[] lowerBounds = new int[rank];
     61        for (int i = 0; i < rank; i++) {
     62          values.MoveNext();
     63          lowerBounds[i] = int.Parse((string)values.Current);
     64        }
     65        Array a = Array.CreateInstance(this.SourceType.GetElementType(), lengths, lowerBounds);
     66        int[] positions = (int[])lowerBounds.Clone();
     67        while (values.MoveNext()) {
     68          a.SetValue(ParseValue((string)values.Current), positions);
     69          positions[0] += 1;
     70          for (int i = 0; i < rank - 1; i++) {
     71            if (positions[i] >= lengths[i]) {
     72              positions[i] = 0;
     73              positions[i + 1] += 1;
     74            } else {
     75              break;
     76            }
    7477          }
    7578        }
    76       }     
    77       return (T)(object)a;
     79        if (positions[rank - 1] != lowerBounds[rank - 1] + lengths[rank - 1])
     80          throw new PersistenceException("Insufficient number of elements while trying to fill number array.");
     81        return (T)(object)a;
     82      } catch (InvalidOperationException e) {
     83        throw new PersistenceException("Insufficient information to rebuild number array.", e);
     84      } catch (InvalidCastException e) {
     85        throw new PersistenceException("Invalid element data or meta data to reconstruct number array.", e);
     86      } catch (OverflowException e) {
     87        throw new PersistenceException("Overflow during element parsing while trying to reconstruct number array.", e);
     88      }
    7889    }
    7990  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Compact/NumberEnumeration2XmlFormatterBase.cs

    r1566 r1625  
    33using HeuristicLab.Persistence.Interfaces;
    44using System;
     5using HeuristicLab.Persistence.Core;
    56
    67namespace HeuristicLab.Persistence.Default.Xml.Compact {
     
    2425
    2526    public override T Parse(XmlString x) {
    26       IEnumerable enumeration = Instantiate();
    27       string[] values = x.Data.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
    28       foreach (var value in values) {
    29         Add(enumeration, ParseValue(value));
    30       }
    31       return (T)enumeration;
     27      try {
     28        IEnumerable enumeration = Instantiate();
     29        string[] values = x.Data.Split(new[] { Separator }, StringSplitOptions.RemoveEmptyEntries);
     30        foreach (var value in values) {
     31          Add(enumeration, ParseValue(value));
     32        }
     33        return (T)enumeration;
     34      } catch (InvalidCastException e) {
     35        throw new PersistenceException("Invalid element data during reconstruction of number enumerable.", e);
     36      } catch (OverflowException e) {
     37        throw new PersistenceException("Overflow during element parsing while trying to reconstruct number enumerable.", e);
     38      }       
    3239    }
    3340  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/DateTime2XmlFormatter.cs

    r1623 r1625  
    1414
    1515    public override DateTime Parse(XmlString x) {
    16       return new DateTime(long.Parse(x.Data));
     16      try {
     17        return new DateTime(long.Parse(x.Data));
     18      } catch (Exception e) {
     19        throw new PersistenceException("Exception caugth while trying to reconstruct DateTime object.", e);
     20      }
    1721    }
    1822
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/DecimalNumber2XmlFormatterBase.cs

    r1566 r1625  
    3131    }
    3232    public override T Parse(XmlString x) {
    33       return (T)ParseMethod.Invoke(null, new object[] { x.Data, CultureInfo.InvariantCulture });
     33      try {
     34        return (T)ParseMethod.Invoke(null, new object[] { x.Data, CultureInfo.InvariantCulture });
     35      } catch (Exception e) {
     36        throw new PersistenceException("Could not parse decimal number.", e);
     37      }
    3438    }
    3539  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/SimpleNumber2XmlFormatterBase.cs

    r1566 r1625  
    2222    }
    2323    public override T Parse(XmlString x) {
    24       return (T)ParseMethod.Invoke(null, new[] { x.Data });
     24      try {
     25        return (T)ParseMethod.Invoke(null, new[] { x.Data });
     26      } catch (Exception e) {
     27        throw new PersistenceException("Could not parse simple number.", e);
     28      }
    2529    }
    2630  }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/Primitive/String2XmlFormatter.cs

    r1623 r1625  
    2626        sb.Append(m.Groups[1]);
    2727      }
     28      string result = sb.ToString();
     29      if (result.Length == 0 && x.Data.Length > 0 && !x.Data.Equals("<![CDATA[]]>"))
     30        throw new PersistenceException("Invalid CDATA section during string parsing.");
    2831      return sb.ToString();
    2932    }
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/XmlGenerator.cs

    r1615 r1625  
    161161
    162162    public static void Serialize(object obj, string filename, Configuration config) {
    163       Serializer serializer = new Serializer(obj, config);
    164       XmlGenerator generator = new XmlGenerator();
    165       ZipOutputStream zipStream = new ZipOutputStream(File.Create(filename));
    166       zipStream.SetLevel(9);
    167       zipStream.PutNextEntry(new ZipEntry("data.xml"));
    168       StreamWriter writer = new StreamWriter(zipStream);
    169       ILog logger = Logger.GetDefaultLogger();
    170       foreach (ISerializationToken token in serializer) {
    171         string line = generator.Format(token);
    172         writer.Write(line);
    173         logger.Debug(line.TrimEnd());
     163      try {
     164        Serializer serializer = new Serializer(obj, config);
     165        XmlGenerator generator = new XmlGenerator();
     166        ZipOutputStream zipStream = new ZipOutputStream(File.Create(filename));
     167        zipStream.SetLevel(9);
     168        zipStream.PutNextEntry(new ZipEntry("data.xml"));
     169        StreamWriter writer = new StreamWriter(zipStream);
     170        ILog logger = Logger.GetDefaultLogger();
     171        foreach (ISerializationToken token in serializer) {
     172          string line = generator.Format(token);
     173          writer.Write(line);
     174          logger.Debug(line.TrimEnd());
     175        }
     176        writer.Flush();
     177        zipStream.PutNextEntry(new ZipEntry("typecache.xml"));
     178        writer = new StreamWriter(zipStream);
     179        foreach (string line in generator.Format(serializer.TypeCache)) {
     180          writer.Write(line);
     181          logger.Debug(line.TrimEnd());
     182        }
     183        writer.Flush();
     184        zipStream.Close();
     185      } catch (PersistenceException e) {
     186        throw;
     187      } catch (Exception e) {
     188        throw new PersistenceException("Unexpected exception during Serialization.", e);
    174189      }
    175       writer.Flush();
    176       zipStream.PutNextEntry(new ZipEntry("typecache.xml"));
    177       writer = new StreamWriter(zipStream);
    178       foreach (string line in generator.Format(serializer.TypeCache)) {
    179         writer.Write(line);
    180         logger.Debug(line.TrimEnd());
    181       }
    182       writer.Flush();
    183       zipStream.Close();
    184190    }
    185 
    186191  }
    187192}
  • trunk/sources/HeuristicLab.Persistence/3.3/Default/Xml/XmlParser.cs

    r1616 r1625  
    4242          iterator = handlers[reader.Name].Invoke();
    4343        } catch (KeyNotFoundException) {
    44           throw new InvalidOperationException(String.Format(
    45             "No handler for XML tag \"{0}\" installed",
     44          throw new PersistenceException(String.Format(
     45            "Invalid XML tag \"{0}\" in persistence file.",
    4646            reader.Name));
    4747        }
     
    103103
    104104    public static List<TypeMapping> ParseTypeCache(TextReader reader) {
    105       var typeCache = new List<TypeMapping>();
    106       XmlReader xmlReader = XmlReader.Create(reader);
    107       while (xmlReader.Read()) {
    108         if (xmlReader.Name == XmlStringConstants.TYPE) {
    109           typeCache.Add(new TypeMapping(
    110             int.Parse(xmlReader.GetAttribute("id")),
    111             xmlReader.GetAttribute("typeName"),
    112             xmlReader.GetAttribute("serializer")));
     105      try {
     106        var typeCache = new List<TypeMapping>();
     107        XmlReader xmlReader = XmlReader.Create(reader);
     108        while (xmlReader.Read()) {
     109          if (xmlReader.Name == XmlStringConstants.TYPE) {
     110            typeCache.Add(new TypeMapping(
     111              int.Parse(xmlReader.GetAttribute("id")),
     112              xmlReader.GetAttribute("typeName"),
     113              xmlReader.GetAttribute("serializer")));
     114          }
    113115        }
     116        return typeCache;
     117      } catch (PersistenceException e) {
     118        throw;
     119      } catch (Exception e) {
     120        throw new PersistenceException("Unexpected exception during type cache parsing.", e);
    114121      }
    115       return typeCache;
    116122    }
    117123
    118124    public static object DeSerialize(string filename) {
    119       ZipFile zipFile = new ZipFile(filename);
    120       Deserializer deSerializer = new Deserializer(
    121         ParseTypeCache(
    122         new StreamReader(
    123           zipFile.GetInputStream(zipFile.GetEntry("typecache.xml")))));
    124       XmlParser parser = new XmlParser(
    125         new StreamReader(zipFile.GetInputStream(zipFile.GetEntry("data.xml"))));
    126       object result = deSerializer.Deserialize(parser);
    127       zipFile.Close();
    128       return result;
     125      try {
     126        ZipFile zipFile = new ZipFile(filename);
     127        Deserializer deSerializer = new Deserializer(
     128          ParseTypeCache(
     129          new StreamReader(
     130            zipFile.GetInputStream(zipFile.GetEntry("typecache.xml")))));
     131        XmlParser parser = new XmlParser(
     132          new StreamReader(zipFile.GetInputStream(zipFile.GetEntry("data.xml"))));
     133        object result = deSerializer.Deserialize(parser);
     134        zipFile.Close();
     135        return result;
     136      } catch (PersistenceException e) {
     137        throw;
     138      } catch (Exception e) {
     139        throw new PersistenceException("Unexpected exception during deserialization", e);
     140      }
    129141    }
    130142  }
Note: See TracChangeset for help on using the changeset viewer.