Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceReintegration/HeuristicLab.Tests/HeuristicLab.Persistence-3.3/UseCasesPersistenceNew.cs @ 15986

Last change on this file since 15986 was 15986, checked in by jkarder, 6 years ago

#2520: worked on new persistence

  • removed type version
  • removed conversions
  • execute AfterDeserialization hooks after all objects have been populated
  • worked on transformers
File size: 97.2 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections;
24using System.Collections.Generic;
25using System.Diagnostics;
26using System.Drawing;
27using System.Globalization;
28using System.IO;
29using System.Linq;
30using System.Reflection;
31using System.Text;
32using System.Threading.Tasks;
33using HeuristicLab.Algorithms.GeneticAlgorithm;
34using HeuristicLab.Core;
35using HeuristicLab.Data;
36using HeuristicLab.Persistence;
37using HeuristicLab.Persistence.Auxiliary;
38using HeuristicLab.Persistence.Core;
39using HeuristicLab.Persistence.Default.DebugString;
40using HeuristicLab.Persistence.Default.Xml;
41using HeuristicLab.Persistence.Tests;
42using HeuristicLab.Tests;
43using Microsoft.VisualStudio.TestTools.UnitTesting;
44
45namespace HeuristicLab.PersistenceNew.Tests {
46  public static class EnumerableTimeSpanExtensions {
47    public static TimeSpan Average(this IEnumerable<TimeSpan> span) {
48      var avg = (long)Math.Round(span.Select(x => x.Ticks).Average());
49      return new TimeSpan(avg);
50    }
51  }
52
53  #region Test Classes
54  [StorableType("7D9672BD-703D-42BB-9080-9929885D4580")]
55  public class NumberTest {
56    [Storable]
57    private bool _bool = true;
58    [Storable]
59    private byte _byte = 0xFF;
60    [Storable]
61    private sbyte _sbyte = 0xF;
62    [Storable]
63    private short _short = -123;
64    [Storable]
65    private ushort _ushort = 123;
66    [Storable]
67    private int _int = -123;
68    [Storable]
69    private uint _uint = 123;
70    [Storable]
71    private long _long = 123456;
72    [Storable]
73    private ulong _ulong = 123456;
74    public override bool Equals(object obj) {
75      NumberTest nt = obj as NumberTest;
76      if (nt == null)
77        throw new NotSupportedException();
78      return
79        nt._bool == _bool &&
80        nt._byte == _byte &&
81        nt._sbyte == _sbyte &&
82        nt._short == _short &&
83        nt._ushort == _ushort &&
84        nt._int == _int &&
85        nt._uint == _uint &&
86        nt._long == _long &&
87        nt._ulong == _ulong;
88    }
89    public override int GetHashCode() {
90      return
91        _bool.GetHashCode() ^
92        _byte.GetHashCode() ^
93        _sbyte.GetHashCode() ^
94        _short.GetHashCode() ^
95        _short.GetHashCode() ^
96        _int.GetHashCode() ^
97        _uint.GetHashCode() ^
98        _long.GetHashCode() ^
99        _ulong.GetHashCode();
100    }
101  }
102
103  [StorableType("EEB19599-D5AC-48ED-A56B-CF213DFAF2E4")]
104  public class NonDefaultConstructorClass {
105    [Storable]
106    int value;
107    public NonDefaultConstructorClass(int value) {
108      this.value = value;
109    }
110  }
111
112  [StorableType("EE43FE7A-6D07-4D52-9338-C21B3485F82A")]
113  public class IntWrapper {
114
115    [Storable]
116    public int Value;
117
118    private IntWrapper() { }
119
120    public IntWrapper(int value) {
121      this.Value = value;
122    }
123
124    public override bool Equals(object obj) {
125      if (obj as IntWrapper == null)
126        return false;
127      return Value.Equals(((IntWrapper)obj).Value);
128    }
129    public override int GetHashCode() {
130      return Value.GetHashCode();
131    }
132
133  }
134
135  [StorableType("00A8E48E-8E8A-443C-A327-9F6ACCBE7E80")]
136  public class PrimitivesTest : NumberTest {
137    [Storable]
138    private char c = 'e';
139    [Storable]
140    private long[,] _long_array =
141      new long[,] { { 123, 456, }, { 789, 123 } };
142    [Storable]
143    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
144    [Storable]
145    private object o = new object();
146    public override bool Equals(object obj) {
147      PrimitivesTest pt = obj as PrimitivesTest;
148      if (pt == null)
149        throw new NotSupportedException();
150      return base.Equals(obj) &&
151        c == pt.c &&
152        _long_array == pt._long_array &&
153        list == pt.list &&
154        o == pt.o;
155    }
156    public override int GetHashCode() {
157      return base.GetHashCode() ^
158        c.GetHashCode() ^
159        _long_array.GetHashCode() ^
160        list.GetHashCode() ^
161        o.GetHashCode();
162    }
163  }
164
165  [StorableType("c15e3ac3-2681-48a1-9171-d97321cd60bb")]
166  public enum TestEnum { va1, va2, va3, va8 };
167
168  [StorableType("26BA37F6-926D-4665-A10A-1F39E1CF6468")]
169  public class RootBase {
170    [Storable]
171    private string baseString = "   Serial  ";
172    [Storable]
173    public TestEnum myEnum = TestEnum.va3;
174    public override bool Equals(object obj) {
175      RootBase rb = obj as RootBase;
176      if (rb == null)
177        throw new NotSupportedException();
178      return baseString == rb.baseString &&
179        myEnum == rb.myEnum;
180    }
181    public override int GetHashCode() {
182      return baseString.GetHashCode() ^
183        myEnum.GetHashCode();
184    }
185  }
186
187  [StorableType("F6BCB436-B5F2-40F6-8E2F-7A018CD1CBA0")]
188  public class Root : RootBase {
189    [Storable]
190    public Stack<int> intStack = new Stack<int>();
191    [Storable]
192    public int[] i = new[] { 3, 4, 5, 6 };
193    [Storable(Name = "Test String")]
194    public string s;
195    [Storable]
196    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
197    [Storable]
198    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
199    [Storable]
200    public Custom c;
201    [Storable]
202    public List<Root> selfReferences;
203    [Storable]
204    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
205    [Storable]
206    public bool boolean = true;
207    [Storable]
208    public DateTime dateTime;
209    [Storable]
210    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
211    [Storable]
212    public Dictionary<string, int> dict = new Dictionary<string, int>();
213    [Storable(DefaultValue = "default")]
214    public string uninitialized;
215  }
216
217  [StorableType("a6bd45c2-bf18-47d7-9f66-c130222f2f00")]
218  public enum SimpleEnum { one, two, three }
219  [StorableType("b5c8285e-5c1b-457e-a5a3-e25eb588c283")]
220  public enum ComplexEnum { one = 1, two = 2, three = 3 }
221  [FlagsAttribute]
222  [StorableType("c2ee7205-0a3a-443a-87d6-68568c4f4153")]
223  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
224
225  [StorableType("2F6326ED-023A-415F-B5C7-9F9241940D05")]
226  public class EnumTest {
227    [Storable]
228    public SimpleEnum simpleEnum = SimpleEnum.one;
229    [Storable]
230    public ComplexEnum complexEnum = (ComplexEnum)2;
231    [Storable]
232    public TrickyEnum trickyEnum = (TrickyEnum)15;
233  }
234
235  [StorableType("92365E2A-1184-4280-B763-4853C7ADF3E3")]
236  public class Custom {
237    [Storable]
238    public int i;
239    [Storable]
240    public Root r;
241    [Storable]
242    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
243  }
244
245  [StorableType("7CF19EBC-1EC4-4FBE-BCA9-DA48E3CFE30D")]
246  public class Manager {
247
248    public DateTime lastLoadTime;
249    [Storable]
250    private DateTime lastLoadTimePersistence {
251      get { return lastLoadTime; }
252      set { lastLoadTime = DateTime.Now; }
253    }
254    [Storable]
255    public double? dbl;
256  }
257
258  [StorableType("9092C705-F5E9-4BA9-9750-4357DB29AABF")]
259  public class C {
260    [Storable]
261    public C[][] allCs;
262    [Storable]
263    public KeyValuePair<List<C>, C> kvpList;
264  }
265
266  public class NonSerializable {
267    int x = 0;
268    public override bool Equals(object obj) {
269      NonSerializable ns = obj as NonSerializable;
270      if (ns == null)
271        throw new NotSupportedException();
272      return ns.x == x;
273    }
274    public override int GetHashCode() {
275      return x.GetHashCode();
276    }
277  }
278
279  [StorableType("FD953B0A-BDE6-41E6-91A8-CA3D90C91CDB")]
280  public class SimpleClass {
281    [Storable]
282    public double x { get; set; }
283    [Storable]
284    public int y { get; set; }
285  }
286  #endregion
287
288  [TestClass]
289  [StorableType("6324d1f6-a82b-4914-937a-21846c4af9e6")]
290  public class UseCasesPersistenceNew {
291    #region Helpers
292    private string tempFile;
293    private static Dictionary<Guid, Type> guid2Type;
294    private static Dictionary<Type, Guid> type2Guid;
295    private static Dictionary<Type, Persistence.TypeInfo> typeInfos;
296    private static PropertyInfo guidPropertyInfo = typeof(StorableTypeAttribute).GetProperty("Guid");
297
298
299    [ClassInitialize]
300    public static void Initialize(TestContext testContext) {
301      ConfigurationService.Instance.Reset();
302
303      var guid2TypeFieldInfo = typeof(StaticCache).GetField("guid2Type", BindingFlags.NonPublic | BindingFlags.Instance);
304      var type2GuidFieldInfo = typeof(StaticCache).GetField("type2Guid", BindingFlags.NonPublic | BindingFlags.Instance);
305      var typeInfosFieldInfo = typeof(StaticCache).GetField("typeInfos", BindingFlags.NonPublic | BindingFlags.Instance);
306
307      guid2Type = (Dictionary<Guid, Type>)guid2TypeFieldInfo.GetValue(Mapper.StaticCache);
308      type2Guid = (Dictionary<Type, Guid>)type2GuidFieldInfo.GetValue(Mapper.StaticCache);
309      typeInfos = (Dictionary<Type, Persistence.TypeInfo>)typeInfosFieldInfo.GetValue(Mapper.StaticCache);
310    }
311
312    [TestInitialize()]
313    public void CreateTempFile() {
314      tempFile = Path.GetTempFileName();
315    }
316
317    [TestCleanup()]
318    public void ClearTempFile() {
319      StreamReader reader = new StreamReader(tempFile);
320      string s = reader.ReadToEnd();
321      reader.Close();
322      File.Delete(tempFile);
323    }
324
325    public static void RegisterType(Guid guid, Type type) {
326      Mapper.StaticCache.RegisterType(guid, type);
327    }
328
329    public static void DeregisterType(Type type) {
330      var typeInfo = GetTypeInfo(type);
331      type2Guid.Remove(guid2Type[typeInfo.StorableTypeAttribute.Guid]);
332      guid2Type.Remove(typeInfo.StorableTypeAttribute.Guid);
333    }
334
335    public static Persistence.TypeInfo GetTypeInfo(Type type) {
336      return Mapper.StaticCache.GetTypeInfo(type);
337    }
338
339    //public static void RemoveTypeInfo(Type type) {
340    //  typeInfos.Remove(typeof(ConversionA));
341    //}
342
343    public static Guid GetTypeGuid(Type type) {
344      var typeInfo = GetTypeInfo(type);
345      return typeInfo.StorableTypeAttribute.Guid;
346    }
347
348    public static void SetTypeGuid(Type type, Guid guid) {
349      var typeInfo = GetTypeInfo(type);
350      guidPropertyInfo.SetValue(typeInfo.StorableTypeAttribute, guid);
351    }
352    #endregion
353
354    #region Persistence 4.0 Profiling Helpers 
355    [StorableType("f90de8e3-e7d1-43b2-a8f0-6689ec922e87")]
356    public class PerformanceData {
357      public TimeSpan OldSerializingTime { get; set; }
358      public TimeSpan NewSerializingTime { get; set; }
359      public TimeSpan OldDeserializingTime { get; set; }
360      public TimeSpan NewDeserializingTime { get; set; }
361      public long OldFileSize { get; set; }
362      public long NewFileSize { get; set; }
363      public long OldSerializingMemoryConsumed { get; set; }
364      public long NewSerializingMemoryConsumed { get; set; }
365      public long OldDeserializingMemoryConsumed { get; set; }
366      public long NewDeserializingMemoryConsumed { get; set; }
367    }
368
369    private void SerializeNew(object o) {
370      ProtoBufSerializer serializer = new ProtoBufSerializer();
371      serializer.Serialize(o, tempFile);
372    }
373    private void SerializeOld(object o) {
374      XmlGenerator.Serialize(o, tempFile);
375    }
376    private object DeserializeNew() {
377      ProtoBufSerializer serializer = new ProtoBufSerializer();
378      return serializer.Deserialize(tempFile);
379    }
380    private object DeserialiezOld() {
381      return XmlParser.Deserialize(tempFile);
382    }
383
384    private void CollectGarbage() {
385      GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
386      GC.WaitForPendingFinalizers();
387    }
388
389    public PerformanceData ProfileSingleRun(Func<object> GenerateDataFunc) {
390      PerformanceData performanceData = new PerformanceData();
391      Stopwatch sw = new Stopwatch();
392      object data = GenerateDataFunc();
393      object result = null;
394      long startMem, endMem;
395
396
397      //old file format serializing
398      CollectGarbage();
399      startMem = GC.GetTotalMemory(false);
400      sw.Start();
401      SerializeOld(data);
402      sw.Stop();
403      endMem = GC.GetTotalMemory(false);
404      performanceData.OldSerializingTime = sw.Elapsed;
405      performanceData.OldFileSize = new FileInfo(tempFile).Length;
406      performanceData.OldSerializingMemoryConsumed = endMem - startMem;
407      sw.Reset();
408
409
410      //old file format deserializing
411      CollectGarbage();
412      startMem = GC.GetTotalMemory(false);
413      sw.Start();
414      result = DeserialiezOld();
415      sw.Stop();
416      endMem = GC.GetTotalMemory(false);
417      performanceData.OldDeserializingTime = sw.Elapsed;
418      performanceData.OldDeserializingMemoryConsumed = endMem - startMem;
419      sw.Reset();
420
421
422      //new file format serializing
423      CollectGarbage();
424      startMem = GC.GetTotalMemory(false);
425      sw.Start();
426      SerializeNew(data);
427      sw.Stop();
428      endMem = GC.GetTotalMemory(false);
429      performanceData.NewSerializingTime = sw.Elapsed;
430      performanceData.NewSerializingMemoryConsumed = endMem - startMem;
431      performanceData.NewFileSize = new FileInfo(tempFile).Length;
432      sw.Reset();
433
434
435      //new file format deserializing
436      CollectGarbage();
437      startMem = GC.GetTotalMemory(false);
438      sw.Start();
439      result = DeserializeNew();
440      sw.Stop();
441      endMem = GC.GetTotalMemory(false);
442      performanceData.NewDeserializingTime = sw.Elapsed;
443      performanceData.NewDeserializingMemoryConsumed = endMem - startMem;
444      sw.Reset();
445
446      return performanceData;
447    }
448
449    public string Profile(Func<object> GenerateDataFunc, string filename = null) {
450      int nrOfRepetitions = 30;
451      StringBuilder report = new StringBuilder();
452      List<PerformanceData> dataList = new List<PerformanceData>();
453
454      for (int i = 0; i < nrOfRepetitions; i++) {
455        dataList.Add(ProfileSingleRun(GenerateDataFunc));
456      }
457
458      //report.Append("Performance Report for " + GenerateDataFunc.Method.Name + ": " + Environment.NewLine);
459      report.Append(Environment.NewLine);
460      report.AppendFormat("Avg. old vs. new time for serializing a file; {3};{0};{1};{2}",
461              dataList.Select(x => x.OldSerializingTime).Average(),
462              dataList.Select(x => x.NewSerializingTime).Average(),
463              dataList.Select(x => x.OldSerializingTime.TotalMilliseconds).Average() / dataList.Select(x => x.NewSerializingTime.TotalMilliseconds).Average()
464              , filename);
465      report.Append(Environment.NewLine);
466      report.AppendFormat("Avg. old vs. new time for deserializing a file; {3};{0};{1};{2}",
467              dataList.Select(x => x.OldDeserializingTime).Average(),
468              dataList.Select(x => x.NewDeserializingTime).Average(),
469              dataList.Select(x => x.OldDeserializingTime.TotalMilliseconds).Average() / dataList.Select(x => x.NewDeserializingTime.TotalMilliseconds).Average()
470              , filename);
471      report.Append(Environment.NewLine);
472      report.AppendFormat("Avg. old vs. new file size (in bytes); {3};{0};{1};{2}",
473              dataList.Select(x => x.OldFileSize).Average(),
474              dataList.Select(x => x.NewFileSize).Average(),
475              dataList.Select(x => x.OldFileSize).Average() / dataList.Select(x => x.NewFileSize).Average()
476              , filename);
477      report.Append(Environment.NewLine);
478      report.AppendFormat("Avg. old vs. new memory consumption for serializing a file (in bytes); {3};{0};{1};{2}",
479              dataList.Select(x => x.OldSerializingMemoryConsumed).Average(),
480              dataList.Select(x => x.NewSerializingMemoryConsumed).Average(),
481              dataList.Select(x => x.OldSerializingMemoryConsumed).Average() / dataList.Select(x => x.NewSerializingMemoryConsumed).Average()
482              , filename);
483      report.Append(Environment.NewLine);
484      report.AppendFormat("Avg. old vs. new memory consumption for deserializing a file (in bytes); {3};{0};{1};{2}",
485              dataList.Select(x => x.OldDeserializingMemoryConsumed).Average(),
486              dataList.Select(x => x.NewDeserializingMemoryConsumed).Average(),
487              dataList.Select(x => x.OldDeserializingMemoryConsumed).Average() / dataList.Select(x => x.NewDeserializingMemoryConsumed).Average()
488              , filename);
489      report.Append(Environment.NewLine);
490
491
492      return report.ToString();
493    }
494    #endregion
495
496    #region Persistence 4.0 Test methods
497    [TestMethod]
498    [TestCategory("PersistenceNew")]
499    [TestProperty("Time", "short")]
500    public void TestBool() {
501      var test = new Func<object>(() => { return true; });
502      ProtoBufSerializer serializer = new ProtoBufSerializer();
503      serializer.Serialize(test(), tempFile);
504      object o = serializer.Deserialize(tempFile);
505      bool result = (bool)o;
506      Assert.AreEqual(test(), result);
507
508      string msg = Profile(test);
509      Console.WriteLine(msg);
510    }
511
512    [TestMethod]
513    [TestCategory("PersistenceNew")]
514    [TestProperty("Time", "short")]
515    public void TestInt() {
516      var test = new Func<object>(() => { return (int)42; });
517      ProtoBufSerializer serializer = new ProtoBufSerializer();
518      serializer.Serialize(test(), tempFile);
519      object o = serializer.Deserialize(tempFile);
520      int result = (int)o;
521      Assert.AreEqual(test(), result);
522
523      string msg = Profile(test);
524      Console.WriteLine(msg);
525    }
526
527    [TestMethod]
528    [TestCategory("PersistenceNew")]
529    [TestProperty("Time", "short")]
530    public void TestDouble() {
531      var test = new Func<object>(() => { return 42.5d; });
532      ProtoBufSerializer serializer = new ProtoBufSerializer();
533      serializer.Serialize(test(), tempFile);
534      object o = serializer.Deserialize(tempFile);
535      double result = (double)o;
536      Assert.AreEqual(test(), result);
537      Assert.IsTrue(o is double);
538
539      string msg = Profile(test);
540      Console.WriteLine(msg);
541    }
542
543    [TestMethod]
544    [TestCategory("PersistenceNew")]
545    [TestProperty("Time", "short")]
546    public void TestFloat() {
547      var test = new Func<object>(() => { return 42.5f; });
548      ProtoBufSerializer serializer = new ProtoBufSerializer();
549      serializer.Serialize(test(), tempFile);
550      object o = serializer.Deserialize(tempFile);
551      float result = (float)o;
552      Assert.AreEqual(test(), result);
553      Assert.IsTrue(o is float);
554
555      string msg = Profile(test);
556      Console.WriteLine(msg);
557    }
558
559    [TestMethod]
560    [TestCategory("PersistenceNew")]
561    [TestProperty("Time", "short")]
562    public void TestDecimal() {
563      var test = new Func<object>(() => { return 42.5m; });
564      ProtoBufSerializer serializer = new ProtoBufSerializer();
565      serializer.Serialize(test(), tempFile);
566      object o = serializer.Deserialize(tempFile);
567      decimal result = (decimal)o;
568      Assert.AreEqual(test(), result);
569      Assert.IsTrue(o is decimal);
570
571      string msg = Profile(test);
572      Console.WriteLine(msg);
573    }
574
575    [TestMethod]
576    [TestCategory("PersistenceNew")]
577    [TestProperty("Time", "short")]
578    public void TestLong() {
579      var test = new Func<object>(() => { return 42l; });
580      ProtoBufSerializer serializer = new ProtoBufSerializer();
581      serializer.Serialize(test(), tempFile);
582      object o = serializer.Deserialize(tempFile);
583      long result = (long)o;
584      Assert.AreEqual(test(), result);
585      Assert.IsTrue(o is long);
586
587      string msg = Profile(test);
588      Console.WriteLine(msg);
589    }
590
591    [TestMethod]
592    [TestCategory("PersistenceNew")]
593    [TestProperty("Time", "short")]
594    public void TestUInt() {
595      var test = new Func<object>(() => { return 42u; });
596      ProtoBufSerializer serializer = new ProtoBufSerializer();
597      serializer.Serialize(test(), tempFile);
598      object o = serializer.Deserialize(tempFile);
599      uint result = (uint)o;
600      Assert.AreEqual(test(), result);
601      Assert.IsTrue(o is uint);
602
603      string msg = Profile(test);
604      Console.WriteLine(msg);
605    }
606
607    [TestMethod]
608    [TestCategory("PersistenceNew")]
609    [TestProperty("Time", "short")]
610    public void TestShort() {
611      var test = new Func<object>(() => { short s = 42; return s; });
612      ProtoBufSerializer serializer = new ProtoBufSerializer();
613      serializer.Serialize(test(), tempFile);
614      object o = serializer.Deserialize(tempFile);
615      short result = (short)o;
616      Assert.IsTrue(o is short);
617      Assert.AreEqual(test(), result);
618
619      string msg = Profile(test);
620      Console.WriteLine(msg);
621    }
622
623    [TestMethod]
624    [TestCategory("PersistenceNew")]
625    [TestProperty("Time", "short")]
626    public void TestByte() {
627      var test = new Func<object>(() => { byte b = 42; return b; });
628      ProtoBufSerializer serializer = new ProtoBufSerializer();
629      serializer.Serialize(test(), tempFile);
630      object o = serializer.Deserialize(tempFile);
631      byte result = (byte)o;
632      Assert.IsTrue(o is byte);
633      Assert.AreEqual(test(), result);
634
635      string msg = Profile(test);
636      Console.WriteLine(msg);
637    }
638
639    [TestMethod]
640    [TestCategory("PersistenceNew")]
641    [TestProperty("Time", "short")]
642    public void TestEnumSimple() {
643      var test = new Func<object>(() => { return SimpleEnum.two; });
644
645      ProtoBufSerializer serializer = new ProtoBufSerializer();
646      serializer.Serialize(test(), tempFile);
647      object o = serializer.Deserialize(tempFile);
648      SimpleEnum result = (SimpleEnum)o;
649      Assert.AreEqual(test(), result);
650
651      string msg = Profile(test);
652      Console.WriteLine(msg);
653    }
654
655    [TestMethod]
656    [TestCategory("PersistenceNew")]
657    [TestProperty("Time", "short")]
658    public void TestEnumComplex() {
659      var test = new Func<object>(() => { return ComplexEnum.three; });
660      ProtoBufSerializer serializer = new ProtoBufSerializer();
661      serializer.Serialize(test(), tempFile);
662      object o = serializer.Deserialize(tempFile);
663      ComplexEnum result = (ComplexEnum)o;
664      Assert.AreEqual(test(), result);
665
666      string msg = Profile(test);
667      Console.WriteLine(msg);
668    }
669
670    [TestMethod]
671    [TestCategory("PersistenceNew")]
672    [TestProperty("Time", "short")]
673    public void TestType() {
674      var test = new Func<object>(() => { return typeof(HeuristicLab.Algorithms.GeneticAlgorithm.GeneticAlgorithm); });
675      ProtoBufSerializer serializer = new ProtoBufSerializer();
676      serializer.Serialize(test(), tempFile);
677      object o = serializer.Deserialize(tempFile);
678      Type result = (Type)o;
679      Assert.AreEqual(test(), result);
680
681      string msg = Profile(test);
682      Console.WriteLine(msg);
683    }
684
685    [TestMethod]
686    [TestCategory("PersistenceNew")]
687    [TestProperty("Time", "short")]
688    public void TestBytes() {
689      var test = new Func<byte[]>(() => { return new byte[] { 3, 1 }; });
690      ProtoBufSerializer serializer = new ProtoBufSerializer();
691      serializer.Serialize(test(), tempFile);
692      object o = serializer.Deserialize(tempFile);
693      byte[] result = (byte[])o;
694      Assert.AreEqual(test()[0], result[0]);
695      Assert.AreEqual(test()[1], result[1]);
696
697      string msg = Profile(test);
698      Console.WriteLine(msg);
699    }
700
701    [TestMethod]
702    [TestCategory("PersistenceNew")]
703    [TestProperty("Time", "short")]
704    public void TestSBytes() {
705      var test = new Func<sbyte[]>(() => { return new sbyte[] { 3, 1 }; });
706      ProtoBufSerializer serializer = new ProtoBufSerializer();
707      serializer.Serialize(test(), tempFile);
708      object o = serializer.Deserialize(tempFile);
709      sbyte[] result = (sbyte[])o;
710      Assert.AreEqual(test()[0], result[0]);
711      Assert.AreEqual(test()[1], result[1]);
712
713      string msg = Profile(test);
714      Console.WriteLine(msg);
715    }
716
717    [TestMethod]
718    [TestCategory("PersistenceNew")]
719    [TestProperty("Time", "short")]
720    public void TestChars() {
721      var test = new Func<char[]>(() => { return new char[] { 'a', 'b' }; });
722      ProtoBufSerializer serializer = new ProtoBufSerializer();
723      serializer.Serialize(test(), tempFile);
724      object o = serializer.Deserialize(tempFile);
725      char[] result = (char[])o;
726      Assert.AreEqual(test()[0], result[0]);
727      Assert.AreEqual(test()[1], result[1]);
728
729      string msg = Profile(test);
730      Console.WriteLine(msg);
731    }
732
733    [TestMethod]
734    [TestCategory("PersistenceNew")]
735    [TestProperty("Time", "short")]
736    public void TestShorts() {
737      var test = new Func<short[]>(() => { return new short[] { 3, 1 }; });
738      ProtoBufSerializer serializer = new ProtoBufSerializer();
739      serializer.Serialize(test(), tempFile);
740      object o = serializer.Deserialize(tempFile);
741      short[] result = (short[])o;
742      Assert.AreEqual(test()[0], result[0]);
743      Assert.AreEqual(test()[1], result[1]);
744
745      string msg = Profile(test);
746      Console.WriteLine(msg);
747    }
748
749    [TestMethod]
750    [TestCategory("PersistenceNew")]
751    [TestProperty("Time", "short")]
752    public void TestUShorts() {
753      var test = new Func<ushort[]>(() => { return new ushort[] { 3, 1 }; });
754      ProtoBufSerializer serializer = new ProtoBufSerializer();
755      serializer.Serialize(test(), tempFile);
756      object o = serializer.Deserialize(tempFile);
757      ushort[] result = (ushort[])o;
758      Assert.AreEqual(test()[0], result[0]);
759      Assert.AreEqual(test()[1], result[1]);
760
761      string msg = Profile(test);
762      Console.WriteLine(msg);
763    }
764
765    [TestMethod]
766    [TestCategory("PersistenceNew")]
767    [TestProperty("Time", "short")]
768    public void TestString() {
769      var test = new Func<object>(() => { return "Hello World!"; });
770      ProtoBufSerializer serializer = new ProtoBufSerializer();
771      serializer.Serialize(test(), tempFile);
772      object o = serializer.Deserialize(tempFile);
773      string result = (string)o;
774      Assert.AreEqual(test(), result);
775
776      string msg = Profile(test);
777      Console.WriteLine(msg);
778    }
779
780    [TestMethod]
781    [TestCategory("PersistenceNew")]
782    [TestProperty("Time", "short")]
783    public void TestColor() {
784      var test = new Func<object>(() => { return Color.FromArgb(12, 34, 56, 78); });
785      ProtoBufSerializer serializer = new ProtoBufSerializer();
786      serializer.Serialize(test(), tempFile);
787      object o = serializer.Deserialize(tempFile);
788      Color result = (Color)o;
789      Assert.AreEqual(test(), result);
790
791      string msg = Profile(test);
792      Console.WriteLine(msg);
793    }
794
795    [TestMethod]
796    [TestCategory("PersistenceNew")]
797    [TestProperty("Time", "short")]
798    public void TestPoint() {
799      var test = new Func<object>(() => { return new Point(3, 4); });
800      ProtoBufSerializer serializer = new ProtoBufSerializer();
801      serializer.Serialize(test(), tempFile);
802      object o = serializer.Deserialize(tempFile);
803      Point result = (Point)o;
804      Assert.AreEqual(((Point)test()).X, result.X);
805      Assert.AreEqual(((Point)test()).Y, result.Y);
806
807      string msg = Profile(test);
808      Console.WriteLine(msg);
809    }
810
811    [TestMethod]
812    [TestCategory("PersistenceNew")]
813    [TestProperty("Time", "short")]
814    public void TestBoolArray() {
815      var test = new Func<bool[]>(() => { return new[] { true, false, true }; });
816      ProtoBufSerializer serializer = new ProtoBufSerializer();
817      serializer.Serialize(test(), tempFile);
818      object o = serializer.Deserialize(tempFile);
819      bool[] result = (bool[])o;
820      Assert.AreEqual(test()[0], result[0]);
821      Assert.AreEqual(test()[1], result[1]);
822      Assert.AreEqual(test()[2], result[2]);
823
824      string msg = Profile(test);
825      Console.WriteLine(msg);
826    }
827
828    [TestMethod]
829    [TestCategory("PersistenceNew")]
830    [TestProperty("Time", "short")]
831    public void TestIntArray() {
832      var test = new Func<int[]>(() => { return new[] { 41, 22, 13 }; });
833      ProtoBufSerializer serializer = new ProtoBufSerializer();
834      serializer.Serialize(test(), tempFile);
835      object o = serializer.Deserialize(tempFile);
836      int[] result = (int[])o;
837      Assert.AreEqual(test()[0], result[0]);
838      Assert.AreEqual(test()[1], result[1]);
839      Assert.AreEqual(test()[2], result[2]);
840
841      string msg = Profile(test);
842      Console.WriteLine(msg);
843    }
844
845    [TestMethod]
846    [TestCategory("PersistenceNew")]
847    [TestProperty("Time", "short")]
848    public void TestLongArray() {
849      var test = new Func<long[]>(() => { return new[] { 414481188112191633l, 245488586662l, 13546881335845865l }; });
850      ProtoBufSerializer serializer = new ProtoBufSerializer();
851      serializer.Serialize(test(), tempFile);
852      object o = serializer.Deserialize(tempFile);
853      long[] result = (long[])o;
854      Assert.AreEqual(test()[0], result[0]);
855      Assert.AreEqual(test()[1], result[1]);
856      Assert.AreEqual(test()[2], result[2]);
857
858      string msg = Profile(test);
859      Console.WriteLine(msg);
860    }
861
862    [TestMethod]
863    [TestCategory("PersistenceNew")]
864    [TestProperty("Time", "short")]
865    public void TestDoubleArray() {
866      var test = new Func<double[]>(() => { return new[] { 41.5, 22.7, 13.8 }; });
867      ProtoBufSerializer serializer = new ProtoBufSerializer();
868      serializer.Serialize(test(), tempFile);
869      object o = serializer.Deserialize(tempFile);
870      double[] result = (double[])o;
871      Assert.AreEqual(test()[0], result[0]);
872      Assert.AreEqual(test()[1], result[1]);
873      Assert.AreEqual(test()[2], result[2]);
874
875      string msg = Profile(test);
876      Console.WriteLine(msg);
877    }
878
879    [TestMethod]
880    [TestCategory("PersistenceNew")]
881    [TestProperty("Time", "short")]
882    public void TestObjectArray() {
883      var test = new Func<SimpleClass[]>(() => {
884        return new[] { new SimpleClass() { x = 42, y = 43 },
885                       new SimpleClass() { x = 44.44, y = 5677 },
886                       new SimpleClass() { x = 533.33, y = 2345 } };
887      });
888      ProtoBufSerializer serializer = new ProtoBufSerializer();
889      serializer.Serialize(test(), tempFile);
890      object o = serializer.Deserialize(tempFile);
891      SimpleClass[] result = (SimpleClass[])o;
892      Assert.AreEqual(test()[0].x, result[0].x);
893      Assert.AreEqual(test()[0].y, result[0].y);
894      Assert.AreEqual(test()[1].x, result[1].x);
895      Assert.AreEqual(test()[1].y, result[1].y);
896      Assert.AreEqual(test()[2].x, result[2].x);
897      Assert.AreEqual(test()[2].y, result[2].y);
898
899      string msg = Profile(test);
900      Console.WriteLine(msg);
901    }
902
903    [TestMethod]
904    [TestCategory("PersistenceNew")]
905    [TestProperty("Time", "short")]
906    public void TestStack() {
907      var test = new Func<Stack>(() => {
908        return new Stack(new int[] { 1, 2, 3 });
909      });
910      ProtoBufSerializer serializer = new ProtoBufSerializer();
911      serializer.Serialize(test(), tempFile);
912      object o = serializer.Deserialize(tempFile);
913      Stack result = (Stack)o;
914      var actualStack = test();
915      Assert.AreEqual(actualStack.Pop(), result.Pop());
916      Assert.AreEqual(actualStack.Pop(), result.Pop());
917      Assert.AreEqual(actualStack.Pop(), result.Pop());
918
919      string msg = Profile(test);
920      Console.WriteLine(msg);
921    }
922
923    [TestMethod]
924    [TestCategory("PersistenceNew")]
925    [TestProperty("Time", "short")]
926    public void TestArrayOfStack() {
927      var test = new Func<object[]>(() => {
928        return new object[] {
929          new Stack(new int[] { 1, 2, 3 }),
930          new Stack<int>(new int[] { 1, 2, 3 }),
931      };
932      });
933      ProtoBufSerializer serializer = new ProtoBufSerializer();
934      serializer.Serialize(test(), tempFile);
935      object o = serializer.Deserialize(tempFile);
936      var result = (object[])o;
937      var firstStack = (Stack)result[0];
938      var secondStack = (Stack<int>)result[1];
939      var actual = test();
940      var actualFirst = (Stack)actual[0];
941      var actualSecond = (Stack<int>)actual[1];
942
943      Assert.AreEqual(actualFirst.Pop(), firstStack.Pop());
944      Assert.AreEqual(actualFirst.Pop(), firstStack.Pop());
945      Assert.AreEqual(actualFirst.Pop(), firstStack.Pop());
946      Assert.AreEqual(actualSecond.Pop(), secondStack.Pop());
947      Assert.AreEqual(actualSecond.Pop(), secondStack.Pop());
948      Assert.AreEqual(actualSecond.Pop(), secondStack.Pop());
949
950      string msg = Profile(test);
951      Console.WriteLine(msg);
952    }
953
954
955    [TestMethod]
956    [TestCategory("PersistenceNew")]
957    [TestProperty("Time", "short")]
958    public void TestIntValueArray() {
959      var test = new Func<IntValue[]>(() => { return new[] { new IntValue(41), new IntValue(22), new IntValue(13) }; });
960      ProtoBufSerializer serializer = new ProtoBufSerializer();
961      serializer.Serialize(test(), tempFile);
962      object o = serializer.Deserialize(tempFile);
963      IntValue[] result = (IntValue[])o;
964      Assert.AreEqual(test()[0].Value, result[0].Value);
965      Assert.AreEqual(test()[1].Value, result[1].Value);
966      Assert.AreEqual(test()[2].Value, result[2].Value);
967
968      string msg = Profile(test);
969      Console.WriteLine(msg);
970    }
971
972    [TestMethod]
973    [TestCategory("PersistenceNew")]
974    [TestProperty("Time", "short")]
975    public void TestIntValueArrayArray() {
976      var test = new Func<IntValue[][]>(() => { return new IntValue[][] { new IntValue[] { new IntValue(41), new IntValue(22), new IntValue(13) } }; });
977      ProtoBufSerializer serializer = new ProtoBufSerializer();
978      serializer.Serialize(test(), tempFile);
979      object o = serializer.Deserialize(tempFile);
980      IntValue[][] result = (IntValue[][])o;
981      Assert.AreEqual(test()[0][0].Value, result[0][0].Value);
982      Assert.AreEqual(test()[0][1].Value, result[0][1].Value);
983      Assert.AreEqual(test()[0][2].Value, result[0][2].Value);
984
985      string msg = Profile(test);
986      Console.WriteLine(msg);
987    }
988    #endregion
989
990    #region Old Persistence Tests
991    [TestMethod]
992    [TestCategory("PersistenceNew")]
993    [TestProperty("Time", "short")]
994    public void ComplexStorable() {
995      ProtoBufSerializer serializer = new ProtoBufSerializer();
996      Root r = InitializeComplexStorable();
997      serializer.Serialize(r, tempFile);
998      Root newR = (Root)serializer.Deserialize(tempFile);
999      CompareComplexStorables(r, newR);
1000    }
1001
1002    private static void CompareComplexStorables(Root r, Root newR) {
1003      Assert.AreEqual(
1004        DebugStringGenerator.Serialize(r),
1005        DebugStringGenerator.Serialize(newR));
1006      Assert.AreSame(newR, newR.selfReferences[0]);
1007      Assert.AreNotSame(r, newR);
1008      Assert.AreEqual(r.myEnum, TestEnum.va1);
1009      Assert.AreEqual(r.i[0], 7);
1010      Assert.AreEqual(r.i[1], 5);
1011      Assert.AreEqual(r.i[2], 6);
1012      Assert.AreEqual(r.s, "new value");
1013      Assert.AreEqual(r.intArray[0], 3);
1014      Assert.AreEqual(r.intArray[1], 2);
1015      Assert.AreEqual(r.intArray[2], 1);
1016      Assert.AreEqual(r.intList[0], 9);
1017      Assert.AreEqual(r.intList[1], 8);
1018      Assert.AreEqual(r.intList[2], 7);
1019      Assert.AreEqual(r.multiDimArray[0, 0], 5);
1020      Assert.AreEqual(r.multiDimArray[0, 1], 4);
1021      Assert.AreEqual(r.multiDimArray[0, 2], 3);
1022      Assert.AreEqual(r.multiDimArray[1, 0], 1);
1023      Assert.AreEqual(r.multiDimArray[1, 1], 4);
1024      Assert.AreEqual(r.multiDimArray[1, 2], 6);
1025      Assert.IsFalse(r.boolean);
1026      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
1027      Assert.AreEqual(r.kvp.Key, "string key");
1028      Assert.AreEqual(r.kvp.Value, 321);
1029      Assert.IsNull(r.uninitialized);
1030      Assert.AreEqual(newR.myEnum, TestEnum.va1);
1031      Assert.AreEqual(newR.i[0], 7);
1032      Assert.AreEqual(newR.i[1], 5);
1033      Assert.AreEqual(newR.i[2], 6);
1034      Assert.AreEqual(newR.s, "new value");
1035      Assert.AreEqual(newR.intArray[0], 3);
1036      Assert.AreEqual(newR.intArray[1], 2);
1037      Assert.AreEqual(newR.intArray[2], 1);
1038      Assert.AreEqual(newR.intList[0], 9);
1039      Assert.AreEqual(newR.intList[1], 8);
1040      Assert.AreEqual(newR.intList[2], 7);
1041      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
1042      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
1043      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
1044      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
1045      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
1046      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
1047      Assert.AreEqual(newR.intStack.Pop(), 3);
1048      Assert.AreEqual(newR.intStack.Pop(), 2);
1049      Assert.AreEqual(newR.intStack.Pop(), 1);
1050      Assert.IsFalse(newR.boolean);
1051      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
1052      Assert.AreEqual(newR.kvp.Key, "string key");
1053      Assert.AreEqual(newR.kvp.Value, 321);
1054      Assert.IsNull(newR.uninitialized);
1055    }
1056
1057    private static Root InitializeComplexStorable() {
1058      Root r = new Root();
1059      r.intStack.Push(1);
1060      r.intStack.Push(2);
1061      r.intStack.Push(3);
1062      r.selfReferences = new List<Root> { r, r };
1063      r.c = new Custom { r = r };
1064      r.dict.Add("one", 1);
1065      r.dict.Add("two", 2);
1066      r.dict.Add("three", 3);
1067      r.myEnum = TestEnum.va1;
1068      r.i = new[] { 7, 5, 6 };
1069      r.s = "new value";
1070      r.intArray = new ArrayList { 3, 2, 1 };
1071      r.intList = new List<int> { 9, 8, 7 };
1072      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
1073      r.boolean = false;
1074      r.dateTime = DateTime.Now;
1075      r.kvp = new KeyValuePair<string, int>("string key", 321);
1076      r.uninitialized = null;
1077
1078      return r;
1079    }
1080
1081    [TestMethod]
1082    [TestCategory("PersistenceNew")]
1083    [TestProperty("Time", "short")]
1084    public void SelfReferences() {
1085      ProtoBufSerializer serializer = new ProtoBufSerializer();
1086      C c = new C();
1087      C[][] cs = new C[2][];
1088      cs[0] = new C[] { c };
1089      cs[1] = new C[] { c };
1090      c.allCs = cs;
1091      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
1092      serializer.Serialize(cs, tempFile);
1093      object o = serializer.Deserialize(tempFile);
1094      Assert.AreEqual(
1095        DebugStringGenerator.Serialize(cs),
1096        DebugStringGenerator.Serialize(o));
1097      Assert.AreSame(c, c.allCs[0][0]);
1098      Assert.AreSame(c, c.allCs[1][0]);
1099      Assert.AreSame(c, c.kvpList.Key[0]);
1100      Assert.AreSame(c, c.kvpList.Value);
1101      C[][] newCs = (C[][])o;
1102      C newC = newCs[0][0];
1103      Assert.AreSame(newC, newC.allCs[0][0]);
1104      Assert.AreSame(newC, newC.allCs[1][0]);
1105      Assert.AreSame(newC, newC.kvpList.Key[0]);
1106      Assert.AreSame(newC, newC.kvpList.Value);
1107    }
1108
1109    [TestMethod]
1110    [TestCategory("PersistenceNew")]
1111    [TestProperty("Time", "short")]
1112    public void ArrayCreation() {
1113      ProtoBufSerializer serializer = new ProtoBufSerializer();
1114      ArrayList[] arrayListArray = new ArrayList[4];
1115      arrayListArray[0] = new ArrayList();
1116      arrayListArray[0].Add(arrayListArray);
1117      arrayListArray[0].Add(arrayListArray);
1118      arrayListArray[1] = new ArrayList();
1119      arrayListArray[1].Add(arrayListArray);
1120      arrayListArray[2] = new ArrayList();
1121      arrayListArray[2].Add(arrayListArray);
1122      arrayListArray[2].Add(arrayListArray);
1123      Array a = Array.CreateInstance(
1124                              typeof(object),
1125                              new[] { 1, 2 }, new[] { 3, 4 });
1126      arrayListArray[2].Add(a);
1127      serializer.Serialize(arrayListArray, tempFile);
1128      object o = serializer.Deserialize(tempFile);
1129      Assert.AreEqual(
1130        DebugStringGenerator.Serialize(arrayListArray),
1131        DebugStringGenerator.Serialize(o));
1132      ArrayList[] newArray = (ArrayList[])o;
1133      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
1134      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
1135      Assert.AreSame(newArray, newArray[0][0]);
1136      Assert.AreSame(newArray, newArray[2][1]);
1137    }
1138
1139    [TestMethod]
1140    [TestCategory("PersistenceNew")]
1141    [TestProperty("Time", "short")]
1142    public void CustomSerializationProperty() {
1143      ProtoBufSerializer serializer = new ProtoBufSerializer();
1144      Manager m = new Manager();
1145      serializer.Serialize(m, tempFile);
1146      Manager newM = (Manager)serializer.Deserialize(tempFile);
1147      Assert.AreNotEqual(
1148        DebugStringGenerator.Serialize(m),
1149        DebugStringGenerator.Serialize(newM));
1150      Assert.AreEqual(m.dbl, newM.dbl);
1151      Assert.AreEqual(m.lastLoadTime, new DateTime());
1152      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
1153      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
1154    }
1155
1156    [TestMethod]
1157    [TestCategory("PersistenceNew")]
1158    [TestProperty("Time", "short")]
1159    public void Primitives() {
1160      ProtoBufSerializer serializer = new ProtoBufSerializer();
1161      PrimitivesTest sdt = new PrimitivesTest();
1162      serializer.Serialize(sdt, tempFile);
1163      object o = serializer.Deserialize(tempFile);
1164      Assert.AreEqual(
1165        DebugStringGenerator.Serialize(sdt),
1166        DebugStringGenerator.Serialize(o));
1167    }
1168
1169    [TestMethod]
1170    [TestCategory("PersistenceNew")]
1171    [TestProperty("Time", "short")]
1172    public void MultiDimensionalArray() {
1173      ProtoBufSerializer serializer = new ProtoBufSerializer();
1174      string[,] mDimString = new string[,] {
1175        {"ora", "et", "labora"},
1176        {"Beten", "und", "Arbeiten"}
1177      };
1178      serializer.Serialize(mDimString, tempFile);
1179      object o = serializer.Deserialize(tempFile);
1180      Assert.AreEqual(
1181        DebugStringGenerator.Serialize(mDimString),
1182        DebugStringGenerator.Serialize(o));
1183    }
1184
1185    [StorableType("87A331AF-14DC-48B3-B577-D49065743BE6")]
1186    public class NestedType {
1187      [Storable]
1188      private string value = "value";
1189      public override bool Equals(object obj) {
1190        NestedType nt = obj as NestedType;
1191        if (nt == null)
1192          throw new NotSupportedException();
1193        return nt.value == value;
1194      }
1195      public override int GetHashCode() {
1196        return value.GetHashCode();
1197      }
1198    }
1199
1200    [TestMethod]
1201    [TestCategory("PersistenceNew")]
1202    [TestProperty("Time", "short")]
1203    public void NestedTypeTest() {
1204      ProtoBufSerializer serializer = new ProtoBufSerializer();
1205      NestedType t = new NestedType();
1206      serializer.Serialize(t, tempFile);
1207      object o = serializer.Deserialize(tempFile);
1208      Assert.AreEqual(
1209        DebugStringGenerator.Serialize(t),
1210        DebugStringGenerator.Serialize(o));
1211      Assert.IsTrue(t.Equals(o));
1212    }
1213
1214
1215    [TestMethod]
1216    [TestCategory("PersistenceNew")]
1217    [TestProperty("Time", "short")]
1218    public void SimpleArray() {
1219      ProtoBufSerializer serializer = new ProtoBufSerializer();
1220      string[] strings = { "ora", "et", "labora" };
1221      serializer.Serialize(strings, tempFile);
1222      object o = serializer.Deserialize(tempFile);
1223      Assert.AreEqual(
1224        DebugStringGenerator.Serialize(strings),
1225        DebugStringGenerator.Serialize(o));
1226    }
1227
1228    [TestMethod]
1229    [TestCategory("PersistenceNew")]
1230    [TestProperty("Time", "short")]
1231    public void PrimitiveRoot() {
1232      ProtoBufSerializer serializer = new ProtoBufSerializer();
1233      serializer.Serialize(12.3f, tempFile);
1234      object o = serializer.Deserialize(tempFile);
1235      Assert.AreEqual(
1236        DebugStringGenerator.Serialize(12.3f),
1237        DebugStringGenerator.Serialize(o));
1238    }
1239
1240    private string formatFullMemberName(MemberInfo mi) {
1241      return new StringBuilder()
1242        .Append(mi.DeclaringType.Assembly.GetName().Name)
1243        .Append(": ")
1244        .Append(mi.DeclaringType.Namespace)
1245        .Append('.')
1246        .Append(mi.DeclaringType.Name)
1247        .Append('.')
1248        .Append(mi.Name).ToString();
1249    }
1250
1251    public void CodingConventions() {
1252      List<string> lowerCaseMethodNames = new List<string>();
1253      List<string> lowerCaseProperties = new List<string>();
1254      List<string> lowerCaseFields = new List<string>();
1255      foreach (Assembly a in PluginLoader.Assemblies) {
1256        if (!a.GetName().Name.StartsWith("HeuristicLab"))
1257          continue;
1258        foreach (Type t in a.GetTypes()) {
1259          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
1260            if (mi.DeclaringType.Name.StartsWith("<>"))
1261              continue;
1262            if (char.IsLower(mi.Name[0])) {
1263              if (mi.MemberType == MemberTypes.Field)
1264                lowerCaseFields.Add(formatFullMemberName(mi));
1265              if (mi.MemberType == MemberTypes.Property)
1266                lowerCaseProperties.Add(formatFullMemberName(mi));
1267              if (mi.MemberType == MemberTypes.Method &&
1268                !mi.Name.StartsWith("get_") &&
1269                !mi.Name.StartsWith("set_") &&
1270                !mi.Name.StartsWith("add_") &&
1271                !mi.Name.StartsWith("remove_") &&
1272                !mi.Name.StartsWith("op_"))
1273                lowerCaseMethodNames.Add(formatFullMemberName(mi));
1274            }
1275          }
1276        }
1277      }
1278      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
1279      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
1280      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
1281    }
1282
1283    [TestMethod]
1284    [TestCategory("PersistenceNew")]
1285    [TestProperty("Time", "short")]
1286    public void Enums() {
1287      ProtoBufSerializer serializer = new ProtoBufSerializer();
1288      EnumTest et = new EnumTest();
1289      et.simpleEnum = SimpleEnum.two;
1290      et.complexEnum = ComplexEnum.three;
1291      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
1292      serializer.Serialize(et, tempFile);
1293      EnumTest newEt = (EnumTest)serializer.Deserialize(tempFile);
1294      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
1295      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
1296      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
1297    }
1298
1299    [TestMethod]
1300    [TestCategory("PersistenceNew")]
1301    [TestProperty("Time", "short")]
1302    public void TestAliasingWithOverriddenEquals() {
1303      ProtoBufSerializer serializer = new ProtoBufSerializer();
1304      List<IntWrapper> ints = new List<IntWrapper>();
1305      ints.Add(new IntWrapper(1));
1306      ints.Add(new IntWrapper(1));
1307      Assert.AreEqual(ints[0], ints[1]);
1308      Assert.AreNotSame(ints[0], ints[1]);
1309      serializer.Serialize(ints, tempFile);
1310      List<IntWrapper> newInts = (List<IntWrapper>)serializer.Deserialize(tempFile);
1311      Assert.AreEqual(newInts[0].Value, 1);
1312      Assert.AreEqual(newInts[1].Value, 1);
1313      Assert.AreEqual(newInts[0], newInts[1]);
1314      Assert.AreNotSame(newInts[0], newInts[1]);
1315    }
1316
1317    [TestMethod]
1318    [TestCategory("PersistenceNew")]
1319    [TestProperty("Time", "short")]
1320    public void NonDefaultConstructorTest() {
1321      ProtoBufSerializer serializer = new ProtoBufSerializer();
1322      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
1323      try {
1324        serializer.Serialize(c, tempFile);
1325        Assert.Fail("Exception not thrown");
1326      } catch (PersistenceException) {
1327      }
1328    }
1329
1330    [TestMethod]
1331    [TestCategory("PersistenceNew")]
1332    [TestProperty("Time", "short")]
1333    public void TestSavingException() {
1334      ProtoBufSerializer serializer = new ProtoBufSerializer();
1335      List<int> list = new List<int> { 1, 2, 3 };
1336      serializer.Serialize(list, tempFile);
1337      NonSerializable s = new NonSerializable();
1338      try {
1339        serializer.Serialize(s, tempFile);
1340        Assert.Fail("Exception expected");
1341      } catch (PersistenceException) { }
1342      List<int> newList = (List<int>)serializer.Deserialize(tempFile);
1343      Assert.AreEqual(list[0], newList[0]);
1344      Assert.AreEqual(list[1], newList[1]);
1345    }
1346
1347    [TestMethod]
1348    [TestCategory("PersistenceNew")]
1349    [TestProperty("Time", "short")]
1350    public void TestTypeStringConversion() {
1351      string name = typeof(List<int>[]).AssemblyQualifiedName;
1352      string shortName =
1353        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
1354      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
1355      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
1356      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
1357    }
1358
1359    [TestMethod]
1360    [TestCategory("PersistenceNew")]
1361    [TestProperty("Time", "short")]
1362    public void TestHexadecimalPublicKeyToken() {
1363      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
1364      string shortName = "TestClass, TestAssembly";
1365      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
1366      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
1367    }
1368
1369    [TestMethod]
1370    [TestCategory("PersistenceNew")]
1371    [TestProperty("Time", "short")]
1372    public void InheritanceTest() {
1373      ProtoBufSerializer serializer = new ProtoBufSerializer();
1374      New n = new New();
1375      serializer.Serialize(n, tempFile);
1376      New nn = (New)serializer.Deserialize(tempFile);
1377      Assert.AreEqual(n.Name, nn.Name);
1378      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
1379    }
1380
1381    [StorableType("B963EF51-12B4-432E-8C54-88F026F9ACE2")]
1382    class Child {
1383      [Storable]
1384      public GrandParent grandParent;
1385    }
1386
1387    [StorableType("E66E9606-967A-4C35-A361-F6F0D21C064A")]
1388    class Parent {
1389      [Storable]
1390      public Child child;
1391    }
1392
1393    [StorableType("34D3893A-57AD-4F72-878B-81D6FA3F14A9")]
1394    class GrandParent {
1395      [Storable]
1396      public Parent parent;
1397    }
1398
1399    [TestMethod]
1400    [TestCategory("PersistenceNew")]
1401    [TestProperty("Time", "short")]
1402    public void InstantiateParentChainReference() {
1403      ProtoBufSerializer serializer = new ProtoBufSerializer();
1404      GrandParent gp = new GrandParent();
1405      gp.parent = new Parent();
1406      gp.parent.child = new Child();
1407      gp.parent.child.grandParent = gp;
1408      Assert.AreSame(gp, gp.parent.child.grandParent);
1409      serializer.Serialize(gp, tempFile);
1410      GrandParent newGp = (GrandParent)serializer.Deserialize(tempFile);
1411      Assert.AreSame(newGp, newGp.parent.child.grandParent);
1412    }
1413
1414    [StorableType("15DF777F-B12D-4FD4-88C3-8CB4C9CE4F0C")]
1415    struct TestStruct {
1416      int value;
1417      int PropertyValue { get; set; }
1418      public TestStruct(int value)
1419        : this() {
1420        this.value = value;
1421        PropertyValue = value;
1422      }
1423    }
1424
1425    [TestMethod]
1426    [TestCategory("PersistenceNew")]
1427    [TestProperty("Time", "short")]
1428    public void StructTest() {
1429      ProtoBufSerializer serializer = new ProtoBufSerializer();
1430      TestStruct s = new TestStruct(10);
1431      serializer.Serialize(s, tempFile);
1432      TestStruct newS = (TestStruct)serializer.Deserialize(tempFile);
1433      Assert.AreEqual(s, newS);
1434    }
1435
1436    [TestMethod]
1437    [TestCategory("PersistenceNew")]
1438    [TestProperty("Time", "short")]
1439    public void PointTest() {
1440      ProtoBufSerializer serializer = new ProtoBufSerializer();
1441      Point p = new Point(12, 34);
1442      serializer.Serialize(p, tempFile);
1443      Point newP = (Point)serializer.Deserialize(tempFile);
1444      Assert.AreEqual(p, newP);
1445    }
1446
1447    [TestMethod]
1448    [TestCategory("PersistenceNew")]
1449    [TestProperty("Time", "short")]
1450    public void NullableValueTypes() {
1451      ProtoBufSerializer serializer = new ProtoBufSerializer();
1452      double?[] d = new double?[] { null, 1, 2, 3 };
1453      serializer.Serialize(d, tempFile);
1454      double?[] newD = (double?[])serializer.Deserialize(tempFile);
1455      Assert.AreEqual(d[0], newD[0]);
1456      Assert.AreEqual(d[1], newD[1]);
1457      Assert.AreEqual(d[2], newD[2]);
1458      Assert.AreEqual(d[3], newD[3]);
1459    }
1460
1461    [TestMethod]
1462    [TestCategory("PersistenceNew")]
1463    [TestProperty("Time", "short")]
1464    public void BitmapTest() {
1465      ProtoBufSerializer serializer = new ProtoBufSerializer();
1466      Icon icon = System.Drawing.SystemIcons.Hand;
1467      Bitmap bitmap = icon.ToBitmap();
1468      serializer.Serialize(bitmap, tempFile);
1469      Bitmap newBitmap = (Bitmap)serializer.Deserialize(tempFile);
1470
1471      Assert.AreEqual(bitmap.Size, newBitmap.Size);
1472      for (int i = 0; i < bitmap.Size.Width; i++)
1473        for (int j = 0; j < bitmap.Size.Height; j++)
1474          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
1475    }
1476
1477    [StorableType("E846BC49-20F3-4D3F-A3F3-73D4F2DB1C2E")]
1478    private class PersistenceHooks {
1479      [Storable]
1480      public int a;
1481      [Storable]
1482      public int b;
1483      public int sum;
1484      public bool WasSerialized { get; private set; }
1485      [StorableHook(HookType.BeforeSerialization)]
1486      void PreSerializationHook() {
1487        WasSerialized = true;
1488      }
1489      [StorableHook(HookType.AfterDeserialization)]
1490      void PostDeserializationHook() {
1491        sum = a + b;
1492      }
1493    }
1494
1495    [TestMethod]
1496    [TestCategory("PersistenceNew")]
1497    [TestProperty("Time", "short")]
1498    public void HookTest() {
1499      ProtoBufSerializer serializer = new ProtoBufSerializer();
1500      PersistenceHooks hookTest = new PersistenceHooks();
1501      hookTest.a = 2;
1502      hookTest.b = 5;
1503      Assert.IsFalse(hookTest.WasSerialized);
1504      Assert.AreEqual(hookTest.sum, 0);
1505      serializer.Serialize(hookTest, tempFile);
1506      Assert.IsTrue(hookTest.WasSerialized);
1507      Assert.AreEqual(hookTest.sum, 0);
1508      PersistenceHooks newHookTest = (PersistenceHooks)serializer.Deserialize(tempFile);
1509      Assert.AreEqual(newHookTest.a, hookTest.a);
1510      Assert.AreEqual(newHookTest.b, hookTest.b);
1511      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
1512      Assert.IsFalse(newHookTest.WasSerialized);
1513    }
1514
1515    [StorableType("A35D71DF-397F-4910-A950-ED6923BE9483")]
1516    private class CustomConstructor {
1517      public string Value = "none";
1518      public CustomConstructor() {
1519        Value = "default";
1520      }
1521      [StorableConstructor]
1522      private CustomConstructor(StorableConstructorFlag _) {
1523        Value = "persistence";
1524      }
1525    }
1526
1527    [TestMethod]
1528    [TestCategory("PersistenceNew")]
1529    [TestProperty("Time", "short")]
1530    public void TestCustomConstructor() {
1531      ProtoBufSerializer serializer = new ProtoBufSerializer();
1532      CustomConstructor cc = new CustomConstructor();
1533      Assert.AreEqual(cc.Value, "default");
1534      serializer.Serialize(cc, tempFile);
1535      CustomConstructor newCC = (CustomConstructor)serializer.Deserialize(tempFile);
1536      Assert.AreEqual(newCC.Value, "persistence");
1537    }
1538
1539    [StorableType("D276E825-1F35-4BAC-8937-9ABC91D5C316")]
1540    public class ExplodingDefaultConstructor {
1541      public ExplodingDefaultConstructor() {
1542        throw new Exception("this constructor will always fail");
1543      }
1544      public ExplodingDefaultConstructor(string password) {
1545      }
1546    }
1547
1548    [TestMethod]
1549    [TestCategory("PersistenceNew")]
1550    [TestProperty("Time", "short")]
1551    public void TestConstructorExceptionUnwrapping() {
1552      ProtoBufSerializer serializer = new ProtoBufSerializer();
1553      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
1554      serializer.Serialize(x, tempFile);
1555      try {
1556        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)serializer.Deserialize(tempFile);
1557        Assert.Fail("Exception expected");
1558      } catch (PersistenceException pe) {
1559        Assert.AreEqual(pe.InnerException.Message, "this constructor will always fail");
1560      }
1561    }
1562
1563    [TestMethod]
1564    [TestCategory("PersistenceNew")]
1565    [TestProperty("Time", "short")]
1566    public void TestStreaming() {
1567      ProtoBufSerializer serializer = new ProtoBufSerializer();
1568      using (MemoryStream stream = new MemoryStream()) {
1569        Root r = InitializeComplexStorable();
1570        serializer.Serialize(r, stream);
1571        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
1572          Root newR = (Root)serializer.Deserialize(stream2);
1573          CompareComplexStorables(r, newR);
1574        }
1575      }
1576    }
1577
1578    [StorableType("4921031B-CB61-4677-97AD-9236A4CEC200")]
1579    public class HookInheritanceTestBase {
1580      [Storable]
1581      public object a;
1582      public object link;
1583      [StorableHook(HookType.AfterDeserialization)]
1584      private void relink() {
1585        link = a;
1586      }
1587    }
1588
1589    [StorableType("321CEE0A-5201-4CE2-B135-2343890D96BF")]
1590    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
1591      [Storable]
1592      public object b;
1593      [StorableHook(HookType.AfterDeserialization)]
1594      private void relink() {
1595        Assert.AreSame(a, link);
1596        link = b;
1597      }
1598    }
1599
1600    [TestMethod]
1601    [TestCategory("PersistenceNew")]
1602    [TestProperty("Time", "short")]
1603    public void TestLinkInheritance() {
1604      ProtoBufSerializer serializer = new ProtoBufSerializer();
1605      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
1606      c.a = new object();
1607      serializer.Serialize(c, tempFile);
1608      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)serializer.Deserialize(tempFile);
1609      Assert.AreSame(c.b, c.link);
1610    }
1611
1612    [StorableType(StorableMemberSelection.AllFields, "B9AB42E8-1932-425B-B4CF-F31F07EAC599")]
1613    public class AllFieldsStorable {
1614      public int Value1 = 1;
1615      [Storable]
1616      public int Value2 = 2;
1617      public int Value3 { get; private set; }
1618      public int Value4 { get; private set; }
1619      [StorableConstructor]
1620      private AllFieldsStorable(StorableConstructorFlag _) { }
1621      public AllFieldsStorable() {
1622        Value1 = 12;
1623        Value2 = 23;
1624        Value3 = 34;
1625        Value4 = 56;
1626      }
1627    }
1628
1629    [TestMethod]
1630    [TestCategory("PersistenceNew")]
1631    [TestProperty("Time", "short")]
1632    public void TestStorableTypeDiscoveryAllFields() {
1633      ProtoBufSerializer serializer = new ProtoBufSerializer();
1634      AllFieldsStorable afs = new AllFieldsStorable();
1635      serializer.Serialize(afs, tempFile);
1636      AllFieldsStorable newAfs = (AllFieldsStorable)serializer.Deserialize(tempFile);
1637      Assert.AreEqual(afs.Value1, newAfs.Value1);
1638      Assert.AreEqual(afs.Value2, newAfs.Value2);
1639      Assert.AreEqual(0, newAfs.Value3);
1640      Assert.AreEqual(0, newAfs.Value4);
1641    }
1642
1643    [StorableType(StorableMemberSelection.AllProperties, "CB7DC31C-AEF3-4EB8-91CA-248B767E9F92")]
1644    public class AllPropertiesStorable {
1645      public int Value1 = 1;
1646      [Storable]
1647      public int Value2 = 2;
1648      public int Value3 { get; private set; }
1649      public int Value4 { get; private set; }
1650
1651      [StorableConstructor]
1652      private AllPropertiesStorable(StorableConstructorFlag _) { }
1653      public AllPropertiesStorable() {
1654        Value1 = 12;
1655        Value2 = 23;
1656        Value3 = 34;
1657        Value4 = 56;
1658      }
1659    }
1660
1661    [TestMethod]
1662    [TestCategory("PersistenceNew")]
1663    [TestProperty("Time", "short")]
1664    public void TestStorableTypeDiscoveryAllProperties() {
1665      ProtoBufSerializer serializer = new ProtoBufSerializer();
1666      AllPropertiesStorable afs = new AllPropertiesStorable();
1667      serializer.Serialize(afs, tempFile);
1668      AllPropertiesStorable newAfs = (AllPropertiesStorable)serializer.Deserialize(tempFile);
1669      Assert.AreEqual(1, newAfs.Value1);
1670      Assert.AreEqual(2, newAfs.Value2);
1671      Assert.AreEqual(afs.Value3, newAfs.Value3);
1672      Assert.AreEqual(afs.Value4, newAfs.Value4);
1673
1674    }
1675
1676    [StorableType(StorableMemberSelection.AllFieldsAndAllProperties, "0AD8D68F-E0FF-4FA8-8A72-1148CD91A2B9")]
1677    public class AllFieldsAndAllPropertiesStorable {
1678      public int Value1 = 1;
1679      [Storable]
1680      public int Value2 = 2;
1681      public int Value3 { get; private set; }
1682      public int Value4 { get; private set; }
1683      [StorableConstructor]
1684      private AllFieldsAndAllPropertiesStorable(StorableConstructorFlag _) { }
1685      public AllFieldsAndAllPropertiesStorable() {
1686        Value1 = 12;
1687        Value2 = 23;
1688        Value3 = 34;
1689        Value4 = 56;
1690      }
1691    }
1692
1693    [TestMethod]
1694    [TestCategory("PersistenceNew")]
1695    [TestProperty("Time", "short")]
1696    public void TestStorableTypeDiscoveryAllFieldsAndAllProperties() {
1697      ProtoBufSerializer serializer = new ProtoBufSerializer();
1698      AllFieldsAndAllPropertiesStorable afs = new AllFieldsAndAllPropertiesStorable();
1699      serializer.Serialize(afs, tempFile);
1700      AllFieldsAndAllPropertiesStorable newAfs = (AllFieldsAndAllPropertiesStorable)serializer.Deserialize(tempFile);
1701      Assert.AreEqual(afs.Value1, newAfs.Value1);
1702      Assert.AreEqual(afs.Value2, newAfs.Value2);
1703      Assert.AreEqual(afs.Value3, newAfs.Value3);
1704      Assert.AreEqual(afs.Value4, newAfs.Value4);
1705    }
1706
1707    [StorableType(StorableMemberSelection.MarkedOnly, "0D94E6D4-64E3-4637-B1EE-DEF2B3F6E2E0")]
1708    public class MarkedOnlyStorable {
1709      public int Value1 = 1;
1710      [Storable]
1711      public int Value2 = 2;
1712      public int Value3 { get; private set; }
1713      public int Value4 { get; private set; }
1714      [StorableConstructor]
1715      private MarkedOnlyStorable(StorableConstructorFlag _) { }
1716      public MarkedOnlyStorable() {
1717        Value1 = 12;
1718        Value2 = 23;
1719        Value3 = 34;
1720        Value4 = 56;
1721      }
1722    }
1723
1724    [TestMethod]
1725    [TestCategory("PersistenceNew")]
1726    [TestProperty("Time", "short")]
1727    public void TestStorableTypeDiscoveryMarkedOnly() {
1728      ProtoBufSerializer serializer = new ProtoBufSerializer();
1729      MarkedOnlyStorable afs = new MarkedOnlyStorable();
1730      serializer.Serialize(afs, tempFile);
1731      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)serializer.Deserialize(tempFile);
1732      Assert.AreEqual(1, newAfs.Value1);
1733      Assert.AreEqual(afs.Value2, newAfs.Value2);
1734      Assert.AreEqual(0, newAfs.Value3);
1735      Assert.AreEqual(0, newAfs.Value4);
1736    }
1737
1738    [TestMethod]
1739    [TestCategory("PersistenceNew")]
1740    [TestProperty("Time", "short")]
1741    public void TestLineEndings() {
1742      ProtoBufSerializer serializer = new ProtoBufSerializer();
1743      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
1744      List<string> lines = new List<string>();
1745      foreach (var br in lineBreaks)
1746        lines.Add("line1" + br + "line2");
1747      serializer.Serialize(lines, tempFile);
1748      List<string> newLines = (List<string>)serializer.Deserialize(tempFile);
1749      Assert.AreEqual(lines.Count, newLines.Count);
1750      for (int i = 0; i < lineBreaks.Count; i++) {
1751        Assert.AreEqual(lines[i], newLines[i]);
1752      }
1753    }
1754
1755    [TestMethod]
1756    [TestCategory("PersistenceNew")]
1757    [TestProperty("Time", "short")]
1758    public void TestSpecialNumbers() {
1759      ProtoBufSerializer serializer = new ProtoBufSerializer();
1760      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
1761      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
1762      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
1763      Assert.IsTrue(double.IsNaN(specials[2]));
1764      serializer.Serialize(specials, tempFile);
1765      List<double> newSpecials = (List<double>)serializer.Deserialize(tempFile);
1766      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
1767      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
1768      Assert.IsTrue(double.IsNaN(newSpecials[2]));
1769    }
1770
1771    [TestMethod]
1772    [TestCategory("PersistenceNew")]
1773    [TestProperty("Time", "short")]
1774    public void TestStringSplit() {
1775      string s = "1.2;2.3;3.4;;;4.9";
1776      var l = s.EnumerateSplit(';').ToList();
1777      Assert.AreEqual("1.2", l[0]);
1778      Assert.AreEqual("2.3", l[1]);
1779      Assert.AreEqual("3.4", l[2]);
1780      Assert.AreEqual("4.9", l[3]);
1781    }
1782
1783    [StorableType("B13CB1B0-D2DA-47B8-A715-B166A28B1F03")]
1784    private class IdentityComparer<T> : IEqualityComparer<T> {
1785
1786      public bool Equals(T x, T y) {
1787        return x.Equals(y);
1788      }
1789
1790      public int GetHashCode(T obj) {
1791        return obj.GetHashCode();
1792      }
1793    }
1794
1795    [TestMethod]
1796    [TestCategory("PersistenceNew")]
1797    [TestProperty("Time", "short")]
1798    public void TestHashSetSerializer() {
1799      ProtoBufSerializer serializer = new ProtoBufSerializer();
1800      var hashSets = new List<HashSet<int>>() {
1801        new HashSet<int>(new[] { 1, 2, 3 }),
1802        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1803      };
1804      serializer.Serialize(hashSets, tempFile);
1805      var newHashSets = (List<HashSet<int>>)serializer.Deserialize(tempFile);
1806      Assert.IsTrue(newHashSets[0].Contains(1));
1807      Assert.IsTrue(newHashSets[0].Contains(2));
1808      Assert.IsTrue(newHashSets[0].Contains(3));
1809      Assert.IsTrue(newHashSets[1].Contains(4));
1810      Assert.IsTrue(newHashSets[1].Contains(5));
1811      Assert.IsTrue(newHashSets[1].Contains(6));
1812      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1813      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1814    }
1815
1816    [TestMethod]
1817    [TestCategory("PersistenceNew")]
1818    [TestProperty("Time", "short")]
1819    public void TestConcreteDictionarySerializer() {
1820      ProtoBufSerializer serializer = new ProtoBufSerializer();
1821      var dictionaries = new List<Dictionary<int, int>>() {
1822        new Dictionary<int, int>(),
1823        new Dictionary<int, int>(new IdentityComparer<int>()),
1824      };
1825      dictionaries[0].Add(1, 1);
1826      dictionaries[0].Add(2, 2);
1827      dictionaries[0].Add(3, 3);
1828      dictionaries[1].Add(4, 4);
1829      dictionaries[1].Add(5, 5);
1830      dictionaries[1].Add(6, 6);
1831      serializer.Serialize(dictionaries, tempFile);
1832      var newDictionaries = (List<Dictionary<int, int>>)serializer.Deserialize(tempFile);
1833      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1834      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1835      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1836      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1837      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1838      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1839      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1840      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1841      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1842      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1843      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1844      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1845      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1846      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1847    }
1848
1849    [StorableType("A9B0D7FB-0CAF-4DD7-9045-EA136F9176F7")]
1850    public class ReadOnlyFail {
1851      [Storable]
1852      public string ReadOnly {
1853        get { return "fail"; }
1854      }
1855    }
1856
1857    [TestMethod]
1858    [TestCategory("PersistenceNew")]
1859    [TestProperty("Time", "short")]
1860    public void TestReadOnlyFail() {
1861      ProtoBufSerializer serializer = new ProtoBufSerializer();
1862      try {
1863        serializer.Serialize(new ReadOnlyFail(), tempFile);
1864        Assert.Fail("Exception expected");
1865      } catch (PersistenceException) {
1866      } catch {
1867        Assert.Fail("PersistenceException expected");
1868      }
1869    }
1870
1871
1872    [StorableType("2C9CC576-6823-4784-817B-37C8AF0B1C29")]
1873    public class WriteOnlyFail {
1874      [Storable]
1875      public string WriteOnly {
1876        set { throw new InvalidOperationException("this property should never be set."); }
1877      }
1878    }
1879
1880    [TestMethod]
1881    [TestCategory("PersistenceNew")]
1882    [TestProperty("Time", "short")]
1883    public void TestWriteOnlyFail() {
1884      ProtoBufSerializer serializer = new ProtoBufSerializer();
1885      try {
1886        serializer.Serialize(new WriteOnlyFail(), tempFile);
1887        Assert.Fail("Exception expected");
1888      } catch (PersistenceException) {
1889      } catch {
1890        Assert.Fail("PersistenceException expected.");
1891      }
1892    }
1893
1894    // TODO
1895    //[StorableType("8052D9E3-6DDD-4AE1-9B5B-67C6D5436512")]
1896    //public class OneWayTest {
1897    //  public OneWayTest() { this.value = "default"; }
1898    //  public string value;
1899    //  [Storable(AllowOneWay = true)]
1900    //  public string ReadOnly {
1901    //    get { return "ReadOnly"; }
1902    //  }
1903    //  [Storable(AllowOneWay = true)]
1904    //  public string WriteOnly {
1905    //    set { this.value = value; }
1906    //  }
1907    //}
1908
1909    //[TestMethod]
1910    //[TestCategory("PersistenceNew")]
1911    //[TestProperty("Time", "short")]
1912    //public void TestTypeCacheExport() {
1913    //  ProtoBufSerializer serializer = new ProtoBufSerializer();
1914    //  var test = new List<List<int>>();
1915    //  test.Add(new List<int>() { 1, 2, 3 });
1916    //  IEnumerable<Type> types;
1917    //  using (var stream = new MemoryStream()) {
1918    //    XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1919    //  }
1920    //  List<Type> t = new List<Type>(types);
1921    //  // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1922    //  Assert.IsTrue(t.Contains(typeof(List<int>)));
1923    //  Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1924    //  Assert.AreEqual(t.Count, 2);
1925    //}
1926
1927    [TestMethod]
1928    [TestCategory("PersistenceNew")]
1929    [TestProperty("Time", "short")]
1930    public void TupleTest() {
1931      var t1 = Tuple.Create(1);
1932      var t2 = Tuple.Create('1', "2");
1933      var t3 = Tuple.Create(3.0, 3f, 5);
1934      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1935      var tuple = Tuple.Create(t1, t2, t3, t4);
1936      SerializeNew(tuple);
1937      var newTuple = DeserializeNew();
1938      Assert.AreEqual(tuple, newTuple);
1939    }
1940
1941    [TestMethod]
1942    [TestCategory("PersistenceNew")]
1943    [TestProperty("Time", "short")]
1944    public void FontTest() {
1945      ProtoBufSerializer serializer = new ProtoBufSerializer();
1946      List<Font> fonts = new List<Font>() {
1947        new Font(FontFamily.GenericSansSerif, 12),
1948        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
1949        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
1950        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
1951      };
1952      serializer.Serialize(fonts, tempFile);
1953      var newFonts = (List<Font>)serializer.Deserialize(tempFile);
1954      Assert.AreEqual(fonts[0], newFonts[0]);
1955      Assert.AreEqual(fonts[1], newFonts[1]);
1956      Assert.AreEqual(fonts[2], newFonts[2]);
1957      Assert.AreEqual(fonts[3], newFonts[3]);
1958    }
1959
1960    [TestMethod]
1961    [TestCategory("PersistenceNew")]
1962    [TestProperty("Time", "medium")]
1963    public void ConcurrencyTest() {
1964      ProtoBufSerializer serializer = new ProtoBufSerializer();
1965      int n = 20;
1966      Task[] tasks = new Task[n];
1967      for (int i = 0; i < n; i++) {
1968        tasks[i] = Task.Factory.StartNew((idx) => {
1969          byte[] data;
1970          using (var stream = new MemoryStream()) {
1971            serializer.Serialize(new GeneticAlgorithm(), stream);
1972            data = stream.ToArray();
1973          }
1974        }, i);
1975      }
1976      Task.WaitAll(tasks);
1977    }
1978
1979    [TestMethod]
1980    [TestCategory("PersistenceNew")]
1981    [TestProperty("Time", "medium")]
1982    public void ConcurrentBitmapTest() {
1983      ProtoBufSerializer serializer = new ProtoBufSerializer();
1984      Bitmap b = new Bitmap(300, 300);
1985      System.Random r = new System.Random();
1986      for (int x = 0; x < b.Height; x++) {
1987        for (int y = 0; y < b.Width; y++) {
1988          b.SetPixel(x, y, Color.FromArgb(r.Next()));
1989        }
1990      }
1991      Task[] tasks = new Task[20];
1992      byte[][] datas = new byte[tasks.Length][];
1993      for (int i = 0; i < tasks.Length; i++) {
1994        tasks[i] = Task.Factory.StartNew((idx) => {
1995          using (var stream = new MemoryStream()) {
1996            serializer.Serialize(b, stream);
1997            datas[(int)idx] = stream.ToArray();
1998          }
1999        }, i);
2000      }
2001      Task.WaitAll(tasks);
2002    }
2003
2004    [StorableType("4b4f6317-30c9-4ccd-ad5f-01775f728fbc")]
2005    public class G<T, T2> {
2006      [StorableType("dad331ad-dfc5-4ea5-b044-3e582fcc648d")]
2007      public class S { }
2008      [StorableType("171d3a18-d0ce-498a-a85f-7107a8a198ef")]
2009      public class S2<T3, T4> { }
2010    }
2011
2012    [TestMethod]
2013    [TestCategory("PersistenceNew")]
2014    [TestProperty("Time", "short")]
2015    public void TestSpecialCharacters() {
2016      ProtoBufSerializer serializer = new ProtoBufSerializer();
2017      var s = "abc" + "\x15" + "def";
2018      serializer.Serialize(s, tempFile);
2019      var newS = serializer.Deserialize(tempFile);
2020      Assert.AreEqual(s, newS);
2021    }
2022
2023    [TestMethod]
2024    [TestCategory("PersistenceNew")]
2025    [TestProperty("Time", "short")]
2026    public void TestByteArray() {
2027      ProtoBufSerializer serializer = new ProtoBufSerializer();
2028      var b = new byte[3];
2029      b[0] = 0;
2030      b[1] = 200;
2031      b[2] = byte.MaxValue;
2032      serializer.Serialize(b, tempFile);
2033      var newB = (byte[])serializer.Deserialize(tempFile);
2034      CollectionAssert.AreEqual(b, newB);
2035    }
2036
2037    [TestMethod]
2038    [TestCategory("PersistenceNew")]
2039    [TestProperty("Time", "short")]
2040    public void TestOptionalNumberEnumerable() {
2041      ProtoBufSerializer serializer = new ProtoBufSerializer();
2042      var values = new List<double?> { 0, null, double.NaN, double.PositiveInfinity, double.MaxValue, 1 };
2043      serializer.Serialize(values, tempFile);
2044      var newValues = (List<double?>)serializer.Deserialize(tempFile);
2045      CollectionAssert.AreEqual(values, newValues);
2046    }
2047
2048    [TestMethod]
2049    [TestCategory("PersistenceNew")]
2050    [TestProperty("Time", "short")]
2051    public void TestOptionalDateTimeEnumerable() {
2052      ProtoBufSerializer serializer = new ProtoBufSerializer();
2053      var values = new List<DateTime?> { DateTime.MinValue, null, DateTime.Now, DateTime.Now.Add(TimeSpan.FromDays(1)),
2054        DateTime.ParseExact("10.09.2014 12:21", "dd.MM.yyyy hh:mm", CultureInfo.InvariantCulture), DateTime.MaxValue};
2055      serializer.Serialize(values, tempFile);
2056      var newValues = (List<DateTime?>)serializer.Deserialize(tempFile);
2057      CollectionAssert.AreEqual(values, newValues);
2058    }
2059
2060    [TestMethod]
2061    [TestCategory("PersistenceNew")]
2062    [TestProperty("Time", "short")]
2063    public void TestStringEnumerable() {
2064      ProtoBufSerializer serializer = new ProtoBufSerializer();
2065      var values = new List<string> { "", null, "s", "string", string.Empty, "123", "<![CDATA[nice]]>", "<![CDATA[nasty unterminated" };
2066      serializer.Serialize(values, tempFile);
2067      var newValues = (List<String>)serializer.Deserialize(tempFile);
2068      CollectionAssert.AreEqual(values, newValues);
2069    }
2070
2071    [TestMethod]
2072    [TestCategory("PersistenceNew")]
2073    [TestProperty("Time", "short")]
2074    public void TestUnicodeCharArray() {
2075      ProtoBufSerializer serializer = new ProtoBufSerializer();
2076      var s = Encoding.UTF8.GetChars(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
2077      serializer.Serialize(s, tempFile);
2078      var newS = (char[])serializer.Deserialize(tempFile);
2079      CollectionAssert.AreEqual(s, newS);
2080    }
2081
2082    [TestMethod]
2083    [TestCategory("PersistenceNew")]
2084    [TestProperty("Time", "short")]
2085    public void TestUnicode() {
2086      ProtoBufSerializer serializer = new ProtoBufSerializer();
2087      var s = Encoding.UTF8.GetString(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
2088      serializer.Serialize(s, tempFile);
2089      var newS = serializer.Deserialize(tempFile);
2090      Assert.AreEqual(s, newS);
2091    }
2092
2093    [TestMethod]
2094    [TestCategory("PersistenceNew")]
2095    [TestProperty("Time", "short")]
2096    public void TestQueue() {
2097      ProtoBufSerializer serializer = new ProtoBufSerializer();
2098      var q = new Queue<int>(new[] { 1, 2, 3, 4, 0 });
2099      serializer.Serialize(q, tempFile);
2100      var newQ = (Queue<int>)serializer.Deserialize(tempFile);
2101      CollectionAssert.AreEqual(q, newQ);
2102    }
2103    #endregion
2104
2105    #region New Persistence Tests
2106    [StorableType("6075F1E8-948A-4AD8-8F5A-942B777852EC")]
2107    public class A {
2108      [Storable]
2109      public B B { get; set; }
2110
2111      [Storable]
2112      public int i;
2113    }
2114    [StorableType("287BFEA0-6E27-4839-BCEF-D134FE738AC8")]
2115    public class B {
2116      [Storable]
2117      public A A { get; set; }
2118
2119      [StorableHook(HookType.AfterDeserialization)]
2120      void PostDeserializationHook() {
2121        //Assert.AreEqual(3, A.i);
2122      }
2123    }
2124
2125    [TestMethod]
2126    [TestCategory("PersistenceNew")]
2127    [TestProperty("Time", "short")]
2128    public void TestCyclicReferencesWithTuple() {
2129      var test = new Func<A>(() => {
2130        var a = new A { i = 4 };
2131        var b = new B { A = a };
2132        a.B = b;
2133        return a;
2134      });
2135
2136      //ProtoBufSerializer serializer = new ProtoBufSerializer();
2137      //serializer.Serialize(test(), tempFile);
2138      //object o = serializer.Deserialize(tempFile);
2139      //A result = (A)o;
2140
2141      XmlGenerator.Serialize(test(), tempFile);
2142      object o = XmlParser.Deserialize(tempFile);
2143
2144      string msg = Profile(test);
2145      Console.WriteLine(msg);
2146    }
2147
2148
2149    #region conversion
2150
2151    //[StorableType("F9F51075-490C-48E3-BF64-14514A210149", 1)]
2152    //private class OldBaseType {
2153    //  [Storable]
2154    //  public ItemCollection<IItem> items;
2155    //}
2156    //[StorableType("D211A828-6440-4E72-A8C7-AA4F9B4FFA75", 1)]
2157    //private class V1 : OldBaseType {
2158    //  [Storable]
2159    //  public IntValue a;
2160
2161    //  [Storable]
2162    //  public ItemList<IntValue> vals;
2163
2164    //  [Storable]
2165    //  public V1 mySelf;
2166
2167    //  [Storable]
2168    //  public Tuple<int, int> tup;
2169
2170    //  [Storable]
2171    //  public int x;
2172    //  [Storable]
2173    //  public int y;
2174
2175    //  [Storable]
2176    //  public string s;
2177    //}
2178
2179
2180    //[StorableType("B72C58C8-3321-4706-AA94-578F57337070")]
2181    //private class NewBaseType {
2182    //  [Storable]
2183    //  public DoubleValue[] items;
2184    //}
2185    //[StorableType("00000000-0000-0000-0000-BADCAFFEE001", 2)] // for testing (version 2)
2186    //private class V2 : NewBaseType {
2187    //  [Storable]
2188    //  public int a;
2189
2190    //  [Storable]
2191    //  public int[] val;
2192
2193    //  [Storable]
2194    //  public V2 mySelf;
2195
2196    //  [Storable]
2197    //  public int TupItem1;
2198
2199    //  [Storable]
2200    //  public int TupItem2;
2201
2202    //  [Storable]
2203    //  public Point coords;
2204
2205    //  [Storable(Name = "s")]
2206    //  public string StorableString { get; set; }
2207    //}
2208
2209    //[StorableType("00000000-0000-0000-0000-BADCAFFEE002", 3)] // for testing (version 3)
2210    //private class V3 : NewBaseType {
2211    //  [Storable]
2212    //  public int a;
2213
2214    //  [Storable]
2215    //  public int[] val;
2216
2217    //  [Storable]
2218    //  public V3 mySelf;
2219
2220    //  [Storable]
2221    //  public Tuple<int, int> tup;
2222
2223    //  [Storable]
2224    //  public Point coords;
2225
2226    //  [Storable(Name = "s", AllowOneWay = true)]
2227    //  public string StorableString { set { PublicString = value; } }
2228    //  public string PublicString { get; set; }
2229    //}
2230
2231    //private static class Conversions {
2232    //  [StorableConversion("D211A828-6440-4E72-A8C7-AA4F9B4FFA75", 1)]
2233    //  private static Dictionary<string, object> ConvertV1(Dictionary<string, object> values) {
2234    //    var newValues = new Dictionary<string, object>();
2235    //    var items = (ItemCollection<IItem>)values["F9F51075-490C-48E3-BF64-14514A210149.items"];
2236    //    newValues["B72C58C8-3321-4706-AA94-578F57337070.items"] = items.Select(iv => new DoubleValue((double)(((dynamic)iv).Value))).ToArray();
2237    //    newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.a"] = ((IntValue)values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.a"]).Value;
2238    //    newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.val"] = ((ItemList<IntValue>)values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.vals"]).Select(iv => iv.Value).ToArray();
2239
2240    //    newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.mySelf"] = values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.mySelf"]; // myself type will be mapped correctly
2241
2242    //    var tup = (Tuple<int, int>)values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.tup"];
2243    //    if (tup != null) {
2244    //      newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.TupItem1"] = tup.Item1;
2245    //      newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.TupItem2"] = tup.Item2;
2246    //    }
2247
2248    //    newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.coords"] = new Point((int)values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.x"], (int)values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.y"]);
2249
2250    //    return newValues;
2251    //  }
2252
2253    //  [StorableConversion("D211A828-6440-4E72-A8C7-AA4F9B4FFA75", 2)]
2254    //  private static Dictionary<string, object> ConvertV2(Dictionary<string, object> values) {
2255    //    var newValues = new Dictionary<string, object>();
2256    //    newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.a"] = values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.a"];
2257    //    newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.val"] = values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.val"];
2258    //    newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.mySelf"] = values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.mySelf"];
2259
2260    //    newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.tup"] = Tuple.Create((int)values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.TupItem1"], (int)values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.TupItem2"]);
2261    //    newValues["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.coords"] = values["D211A828-6440-4E72-A8C7-AA4F9B4FFA75.coords"];
2262
2263    //    return newValues;
2264    //  }
2265    //}
2266
2267    //[TestMethod]
2268    //[TestCategory("PersistenceNew")]
2269    //[TestProperty("Time", "short")]
2270    //public void TestConversion() {
2271    //  var test = new Func<V1>(() => {
2272    //    var p = new V1();
2273    //    p.a = new IntValue(1);
2274    //    p.mySelf = p;
2275    //    p.vals = new ItemList<IntValue>(new IntValue[] { p.a, new IntValue(2), new IntValue(3) });
2276    //    p.tup = Tuple.Create(17, 4);
2277    //    var dv = new DoubleValue(1.0);
2278    //    p.items = new ItemCollection<IItem>(new IItem[] { dv, dv, p.a });
2279    //    p.s = "123";
2280    //    return p;
2281    //  });
2282
2283    //  ProtoBufSerializer serializer = new ProtoBufSerializer();
2284    //  var old = test();
2285    //  serializer.Serialize(old, tempFile);
2286
2287    //  DeregisterType(typeof(V1));
2288    //  DeregisterType(typeof(V2));
2289    //  DeregisterType(typeof(V3));
2290
2291    //  RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(V1)).Guid, typeof(V3));
2292    //  SetTypeGuid(typeof(V3), GetTypeGuid(typeof(V1)));
2293    //  RemoveTypeInfo(typeof(V1));
2294
2295    //  object o = serializer.Deserialize(tempFile);
2296    //  var restored = (V3)o;
2297    //  Assert.AreEqual(restored.a, old.a.Value);
2298    //  Assert.IsTrue(restored.val.SequenceEqual(old.vals.Select(iv => iv.Value)));
2299    //  Assert.IsTrue(restored.items.Select(item => item.Value).SequenceEqual(old.items.Select(iv => (double)((dynamic)iv).Value)));
2300    //  // Assert.AreSame(restored.items[0], restored.items[1]);
2301    //  Assert.AreSame(restored, restored.mySelf);
2302    //  Assert.AreEqual(restored.PublicString, old.s);
2303    //}
2304
2305    //#endregion
2306
2307    //[TestMethod]
2308    //[TestCategory("PersistenceNew")]
2309    //[TestProperty("Time", "short")]
2310    //public void TestGASerializeDeserializeExecute() {
2311    //  var test = new Func<GeneticAlgorithm>(() => {
2312    //    var ga = new GeneticAlgorithm();
2313    //    ga.Problem = new SingleObjectiveTestFunctionProblem();
2314    //    ga.MaximumGenerations.Value = 100;
2315    //    ga.SetSeedRandomly.Value = false;
2316    //    return ga;
2317    //  });
2318    //  ProtoBufSerializer serializer = new ProtoBufSerializer();
2319    //  GeneticAlgorithm original = test();
2320    //  serializer.Serialize(original, tempFile);
2321    //  object o = serializer.Deserialize(tempFile);
2322
2323    //  // this fails because old persistence didn't handle all IComparer ?
2324    //  // Assert.AreEqual(DebugStringGenerator.Serialize(original),DebugStringGenerator.Serialize(o));
2325
2326    //  GeneticAlgorithm result = (GeneticAlgorithm)o;
2327    //  SamplesUtils.RunAlgorithm(result);
2328    //  SamplesUtils.RunAlgorithm(original);
2329    //  Assert.AreEqual(((DoubleValue)result.Results["BestQuality"].Value).Value,
2330    //    ((DoubleValue)original.Results["BestQuality"].Value).Value);
2331
2332    //  // Assert.AreEqual(DebugStringGenerator.Serialize(result), DebugStringGenerator.Serialize(result2));
2333    //}
2334
2335    //[TestMethod]
2336    //[TestCategory("PersistenceNew")]
2337    //[TestProperty("Time", "short")]
2338    //public void TestLoadingSamples() {
2339    //  var path = @"C:\Dev\Software_HL\branches\PersistenceReintegration\HeuristicLab.Optimizer\3.3\Documents";
2340    //  var serializer = new ProtoBufSerializer();
2341    //  foreach (var fileName in Directory.EnumerateFiles(path, "*.hl")) {
2342    //    var original = XmlParser.Deserialize(fileName);
2343    //    var ok = true;
2344    //    // foreach (var t in original.GetObjectGraphObjects().Select(o => o.GetType())) {
2345    //    //   if (
2346    //    //     t.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
2347    //    //       .Any(ctor => StorableConstructorAttribute.IsStorableConstructor(ctor))) {
2348    //    //     try {
2349    //    //       if (t.IsGenericType) {
2350    //    //         var g = Mapper.StaticCache.GetGuid(t.GetGenericTypeDefinition());
2351    //    //       } else {
2352    //    //         var g = Mapper.StaticCache.GetGuid(t);
2353    //    //       }
2354    //    //     } catch (Exception e) {
2355    //    //       Console.WriteLine(t.FullName);
2356    //    //       ok = false;
2357    //    //     }
2358    //    //   }
2359    //    // }
2360    //    if (ok) {
2361    //      serializer.Serialize(original, fileName + ".proto");
2362    //      // var newVersion = serializer.Deserialize(fileName + ".proto");
2363    //      //Console.WriteLine("File: " + fileName);
2364    //      var p = Profile(() => original, Path.GetFileName(fileName));
2365    //      Console.WriteLine(p);
2366    //    }
2367    //  }
2368    //}
2369
2370    //[StorableType("3B48A44F-93E2-4ECC-A9B9-56E425EF96F8")]
2371    //private class ConversionA {
2372    //  [Storable]
2373    //  public int f;
2374    //}
2375
2376    //[StorableType("00000000-0000-0000-0000-000000000002", 2)]
2377    //private class ConversionANew {
2378    //  [Storable]
2379    //  public int g;
2380    //}
2381
2382    //[StorableType("7CBF2251-CF9F-4D9E-AA7B-C65495AE078F")]
2383    //private class ConversionB : ConversionA {
2384    //  [Storable]
2385    //  public int f;
2386    //  public int BaseF { get { return base.f; } }
2387
2388    //  public ConversionB() {
2389
2390    //  }
2391
2392    //  public ConversionB(int myF, int baseF) {
2393    //    this.f = myF;
2394    //    base.f = baseF;
2395    //  }
2396    //}
2397
2398    //[StorableType("00000000-0000-0000-0000-000000000001", 2)]
2399    //private class ConversionBNew : ConversionANew {
2400    //  [Storable]
2401    //  public int g;
2402
2403    //  public int BaseG { get { return base.g; } }
2404    //}
2405
2406    //private static class NewConversions {
2407    //  [StorableConversion("7CBF2251-CF9F-4D9E-AA7B-C65495AE078F", 1)]
2408    //  private static Dictionary<string, object> ConvertB(Dictionary<string, object> values) {
2409    //    var newValues = new Dictionary<string, object>();
2410    //    newValues["7CBF2251-CF9F-4D9E-AA7B-C65495AE078F.g"] = values["7CBF2251-CF9F-4D9E-AA7B-C65495AE078F.f"];
2411    //    return newValues;
2412    //  }
2413
2414    //  [StorableConversion("3B48A44F-93E2-4ECC-A9B9-56E425EF96F8", 1)]
2415    //  private static Dictionary<string, object> ConvertA(Dictionary<string, object> values) {
2416    //    var newValues = new Dictionary<string, object>();
2417    //    newValues["3B48A44F-93E2-4ECC-A9B9-56E425EF96F8.g"] = values["3B48A44F-93E2-4ECC-A9B9-56E425EF96F8.f"];
2418    //    return newValues;
2419    //  }
2420    //}
2421
2422    //[TestMethod]
2423    //[TestCategory("PersistenceNew")]
2424    //[TestProperty("Time", "short")]
2425    //public void TestConversionCase1() {
2426    //  var test = new Func<ConversionB>(() => {
2427    //    return new ConversionB(1, 2);
2428    //  });
2429
2430    //  ProtoBufSerializer serializer = new ProtoBufSerializer();
2431    //  var old = test();
2432    //  serializer.Serialize(old, tempFile);
2433
2434    //  DeregisterType(typeof(ConversionB));
2435    //  DeregisterType(typeof(ConversionBNew));
2436    //  DeregisterType(typeof(ConversionA));
2437    //  DeregisterType(typeof(ConversionANew));
2438
2439    //  RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(ConversionA)).Guid, typeof(ConversionANew));
2440    //  SetTypeGuid(typeof(ConversionANew), GetTypeGuid(typeof(ConversionA)));
2441    //  RemoveTypeInfo(typeof(ConversionA));
2442
2443    //  RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(ConversionB)).Guid, typeof(ConversionBNew));
2444    //  SetTypeGuid(typeof(ConversionBNew), GetTypeGuid(typeof(ConversionB)));
2445    //  RemoveTypeInfo(typeof(ConversionB));
2446
2447    //  object o = serializer.Deserialize(tempFile);
2448    //  var restored = (ConversionBNew)o;
2449    //  Assert.AreEqual(restored.g, old.f);
2450    //  Assert.AreEqual(restored.BaseG, old.BaseF);
2451    //}
2452
2453    //[StorableType("90470973-4559-428E-AF28-DD95866B0A84")]
2454    //private class A0 {
2455    //  [Storable]
2456    //  public int x;
2457    //}
2458
2459    //[StorableType("00000000-0000-0000-0000-0000000000A1", 2)]
2460    //private class A1 {
2461    //  [Storable]
2462    //  public int y;
2463    //}
2464
2465    //[StorableType("847DD840-3EE3-4A01-AC60-FD7E71ED05F8")]
2466    //private class B0 {
2467    //  [Storable]
2468    //  public int x;
2469    //}
2470
2471    //[StorableType("00000000-0000-0000-0000-0000000000B1", 2)]
2472    //private class B1 : A0 { }
2473
2474    //[StorableType("00000000-0000-0000-0000-0000000000B2", 3)]
2475    //private class B2 {
2476    //  [Storable]
2477    //  public int x;
2478    //}
2479
2480    //private static class ConversionsA2A_B2B {
2481    //  [StorableConversion("847DD840-3EE3-4A01-AC60-FD7E71ED05F8", 1, baseGuid: "90470973-4559-428E-AF28-DD95866B0A84", baseVersion: 1)]
2482    //  private static Dictionary<string, object> ConvertB0_B1(Dictionary<string, object> values) {
2483    //    var newValues = new Dictionary<string, object>();
2484    //    newValues["90470973-4559-428E-AF28-DD95866B0A84.x"] = values["847DD840-3EE3-4A01-AC60-FD7E71ED05F8.x"];
2485    //    return newValues;
2486    //  }
2487
2488    //  [StorableConversion("90470973-4559-428E-AF28-DD95866B0A84", 1)]
2489    //  private static Dictionary<string, object> ConvertA0_A1(Dictionary<string, object> values) {
2490    //    var newValues = new Dictionary<string, object>();
2491    //    newValues["90470973-4559-428E-AF28-DD95866B0A84.y"] = values["90470973-4559-428E-AF28-DD95866B0A84.x"];
2492    //    return newValues;
2493    //  }
2494
2495    //  [StorableConversion("847DD840-3EE3-4A01-AC60-FD7E71ED05F8", 2)]
2496    //  private static Dictionary<string, object> ConvertB1_B2(Dictionary<string, object> values) {
2497    //    var newValues = new Dictionary<string, object>();
2498    //    newValues["847DD840-3EE3-4A01-AC60-FD7E71ED05F8.x"] = values["90470973-4559-428E-AF28-DD95866B0A84.y"];
2499    //    return newValues;
2500    //  }
2501    //}
2502
2503    //[TestMethod]
2504    //[TestCategory("PersistenceNew")]
2505    //[TestProperty("Time", "short")]
2506    //public void TestConversionCase2() {
2507    //  var test = new Func<B0>(() => {
2508    //    return new B0() { x = 17 };
2509    //  });
2510
2511    //  ProtoBufSerializer serializer = new ProtoBufSerializer();
2512    //  var old = test();
2513    //  serializer.Serialize(old, tempFile);
2514
2515    //  DeregisterType(typeof(B0));
2516    //  DeregisterType(typeof(B1));
2517    //  DeregisterType(typeof(B2));
2518    //  DeregisterType(typeof(A0));
2519    //  DeregisterType(typeof(A1));
2520
2521    //  RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(B0)).Guid, typeof(B2));
2522    //  SetTypeGuid(typeof(B2), GetTypeGuid(typeof(B0)));
2523    //  RemoveTypeInfo(typeof(B0));
2524
2525    //  RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(A0)).Guid, typeof(A1));
2526    //  SetTypeGuid(typeof(A1), GetTypeGuid(typeof(A0)));
2527    //  RemoveTypeInfo(typeof(A0));
2528
2529    //  object o = serializer.Deserialize(tempFile);
2530    //  var restored = (B2)o;
2531    //  Assert.AreEqual(restored.x, old.x);
2532    //}
2533
2534    //#region Inheritance Chain Test
2535    //[StorableType("C1BFC249-89F6-45E2-8DFB-DA95E1BE9B95")]
2536    //private class InheritanceA0 {
2537    //  [Storable]
2538    //  public int x;
2539    //}
2540
2541    //[StorableType("00000000-0000-0000-0000-0000000001A1", 2)]
2542    //private class InheritanceA1 {
2543    //  [Storable]
2544    //  public int y;
2545    //}
2546
2547    //[StorableType("28A5F6B8-49AF-4C6A-AF0E-F92EB4511722", 1)]
2548    //private class InheritanceC0 {
2549    //  [Storable]
2550    //  public int x;
2551    //}
2552
2553    //[StorableType("00000000-0000-0000-0000-0000000001C1", 2)]
2554    //private class InheritanceC1 {
2555    //  [Storable]
2556    //  public int x;
2557    //}
2558
2559    //[StorableType("41108958-227D-43C4-B049-80AD0D3DB7F6")]
2560    //private class InheritanceB0 : InheritanceA0 {
2561    //  [Storable]
2562    //  public int x;
2563
2564    //  [StorableConstructor]
2565    //  private InheritanceB0(StorableConstructorFlag flag) { }
2566    //  public InheritanceB0(int x) {
2567    //    this.x = x;
2568    //    base.x = x;
2569    //  }
2570    //}
2571
2572    //[StorableType("00000000-0000-0000-0000-0000000001B1", 2)]
2573    //private class InheritanceB1 : InheritanceC1 { }
2574
2575    //private static class InheritanceConversionsA2A_B2B {
2576    //  [StorableConversion("C1BFC249-89F6-45E2-8DFB-DA95E1BE9B95", 1)]
2577    //  private static Dictionary<string, object> ConvertA0_A1(Dictionary<string, object> values) {
2578    //    var newValues = new Dictionary<string, object>();
2579    //    newValues["C1BFC249-89F6-45E2-8DFB-DA95E1BE9B95.y"] = values["C1BFC249-89F6-45E2-8DFB-DA95E1BE9B95.x"];
2580    //    return newValues;
2581    //  }
2582
2583    //  [StorableConversion("41108958-227D-43C4-B049-80AD0D3DB7F6", 1, baseGuid: "C1BFC249-89F6-45E2-8DFB-DA95E1BE9B95", baseVersion: 2)]
2584    //  private static Dictionary<string, object> ConvertB0_B1(Dictionary<string, object> values, out List<Tuple<string, uint>> typeChain) {
2585    //    typeChain = new List<Tuple<string, uint>> {
2586    //      Tuple.Create("28A5F6B8-49AF-4C6A-AF0E-F92EB4511722", 1u)
2587    //    };
2588
2589    //    var newValues = new Dictionary<string, object>();
2590    //    newValues["41108958-227D-43C4-B049-80AD0D3DB7F6.x"] = values["C1BFC249-89F6-45E2-8DFB-DA95E1BE9B95.y"];
2591    //    newValues["28A5F6B8-49AF-4C6A-AF0E-F92EB4511722.x"] = values["C1BFC249-89F6-45E2-8DFB-DA95E1BE9B95.y"];
2592    //    return newValues;
2593    //  }
2594
2595    //  [StorableConversion("28A5F6B8-49AF-4C6A-AF0E-F92EB4511722", 1)]
2596    //  private static Dictionary<string, object> ConvertC0_C1(Dictionary<string, object> values) {
2597    //    var newValues = new Dictionary<string, object>();
2598    //    newValues["28A5F6B8-49AF-4C6A-AF0E-F92EB4511722.x"] = (int)values["28A5F6B8-49AF-4C6A-AF0E-F92EB4511722.x"] * 2;
2599    //    return newValues;
2600    //  }
2601    //}
2602
2603    ////private static class InheritanceConversionsWithNamesDemo {
2604    ////  [StorableConversion("A", 1)]
2605    ////  private static Dictionary<string, object> ConvertA1_A2(Dictionary<string, object> values) {
2606    ////    var newValues = new Dictionary<string, object>();
2607    ////    newValues["y"] = values["x"];
2608    ////    return newValues;
2609    ////  }
2610
2611    ////  [StorableConversion("B", 1, baseGuid: "A", baseVersion: 2)]
2612    ////  private static Dictionary<string, object> ConvertB1_B2(Dictionary<string, object> values, out List<Tuple<string, uint>> typeChain) {
2613    ////    typeChain = new List<Tuple<string, uint>> {
2614    ////      Tuple.Create("C", 1u)
2615    ////    };
2616
2617    ////    var newValues = new Dictionary<string, object>();
2618    ////    newValues["x"] = values["A.y"];
2619    ////    newValues["C.x"] = values["A.y"];
2620    ////    return newValues;
2621    ////  }
2622
2623    ////  [StorableConversion("C", 1)]
2624    ////  private static Dictionary<string, object> ConvertC1_C2(Dictionary<string, object> values) {
2625    ////    var newValues = new Dictionary<string, object>();
2626    ////    newValues["x"] = (int)values["x"] * 2;
2627    ////    return newValues;
2628    ////  }
2629
2630    ////  [StorableConversion("C", 1, "D", 1)]
2631    ////  //[StorableConversion("D", 1, "E", 1)]
2632    ////  private static string Rename() { return "D"; }
2633    ////}
2634
2635    //[TestMethod]
2636    //[TestCategory("PersistenceNew")]
2637    //[TestProperty("Time", "short")]
2638    //public void TestInheritanceConversionCase1() {
2639    //  var test = new Func<InheritanceB0>(() => {
2640    //    return new InheritanceB0(17);
2641    //  });
2642
2643    //  ProtoBufSerializer serializer = new ProtoBufSerializer();
2644    //  var old = test();
2645    //  serializer.Serialize(old, tempFile);
2646
2647    //  DeregisterType(typeof(InheritanceB0));
2648    //  DeregisterType(typeof(InheritanceB1));
2649    //  DeregisterType(typeof(InheritanceA0));
2650    //  DeregisterType(typeof(InheritanceA1));
2651    //  DeregisterType(typeof(InheritanceC0));
2652    //  DeregisterType(typeof(InheritanceC1));
2653
2654    //  RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(InheritanceA0)).Guid, typeof(InheritanceA1));
2655    //  SetTypeGuid(typeof(InheritanceA1), GetTypeGuid(typeof(InheritanceA0)));
2656    //  RemoveTypeInfo(typeof(InheritanceA0));
2657
2658    //  RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(InheritanceB0)).Guid, typeof(InheritanceB1));
2659    //  SetTypeGuid(typeof(InheritanceB1), GetTypeGuid(typeof(InheritanceB0)));
2660    //  RemoveTypeInfo(typeof(InheritanceB0));
2661
2662    //  RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(InheritanceC0)).Guid, typeof(InheritanceC1));
2663    //  SetTypeGuid(typeof(InheritanceC1), GetTypeGuid(typeof(InheritanceC0)));
2664    //  RemoveTypeInfo(typeof(InheritanceC0));
2665
2666    //  object o = serializer.Deserialize(tempFile);
2667    //  var restoredC1 = (InheritanceC1)o;
2668    //  var restoredB1 = (InheritanceB1)o;
2669    //  Assert.AreEqual(old.x * 2, restoredC1.x);
2670    //}
2671    #endregion
2672    #endregion
2673  }
2674}
Note: See TracBrowser for help on using the repository browser.