Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceOverhaul/HeuristicLab.Tests/HeuristicLab.Persistence-3.3/UseCasesPersistenceNew.cs @ 14594

Last change on this file since 14594 was 14594, checked in by jkarder, 7 years ago

#2520: worked on persistence

File size: 75.7 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.Data;
35using HeuristicLab.Persistence;
36using HeuristicLab.Persistence.Auxiliary;
37using HeuristicLab.Persistence.Core;
38using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
39using HeuristicLab.Persistence.Default.DebugString;
40using HeuristicLab.Persistence.Default.Xml;
41using HeuristicLab.Persistence.Tests;
42using HeuristicLab.Problems.TestFunctions;
43using HeuristicLab.Tests;
44using Microsoft.VisualStudio.TestTools.UnitTesting;
45
46namespace HeuristicLab.PersistenceNew.Tests {
47  public static class EnumerableTimeSpanExtensions {
48    public static TimeSpan Average(this IEnumerable<TimeSpan> span) {
49      var avg = (long)Math.Round(span.Select(x => x.Ticks).Average());
50      return new TimeSpan(avg);
51    }
52  }
53
54  #region Test Classes
55  [StorableClass("7D9672BD-703D-42BB-9080-9929885D4580")]
56  public class NumberTest {
57    [Storable]
58    private bool _bool = true;
59    [Storable]
60    private byte _byte = 0xFF;
61    [Storable]
62    private sbyte _sbyte = 0xF;
63    [Storable]
64    private short _short = -123;
65    [Storable]
66    private ushort _ushort = 123;
67    [Storable]
68    private int _int = -123;
69    [Storable]
70    private uint _uint = 123;
71    [Storable]
72    private long _long = 123456;
73    [Storable]
74    private ulong _ulong = 123456;
75    public override bool Equals(object obj) {
76      NumberTest nt = obj as NumberTest;
77      if (nt == null)
78        throw new NotSupportedException();
79      return
80        nt._bool == _bool &&
81        nt._byte == _byte &&
82        nt._sbyte == _sbyte &&
83        nt._short == _short &&
84        nt._ushort == _ushort &&
85        nt._int == _int &&
86        nt._uint == _uint &&
87        nt._long == _long &&
88        nt._ulong == _ulong;
89    }
90    public override int GetHashCode() {
91      return
92        _bool.GetHashCode() ^
93        _byte.GetHashCode() ^
94        _sbyte.GetHashCode() ^
95        _short.GetHashCode() ^
96        _short.GetHashCode() ^
97        _int.GetHashCode() ^
98        _uint.GetHashCode() ^
99        _long.GetHashCode() ^
100        _ulong.GetHashCode();
101    }
102  }
103
104  [StorableClass("EEB19599-D5AC-48ED-A56B-CF213DFAF2E4")]
105  public class NonDefaultConstructorClass {
106    [Storable]
107    int value;
108    public NonDefaultConstructorClass(int value) {
109      this.value = value;
110    }
111  }
112
113  [StorableClass("EE43FE7A-6D07-4D52-9338-C21B3485F82A")]
114  public class IntWrapper {
115
116    [Storable]
117    public int Value;
118
119    private IntWrapper() { }
120
121    public IntWrapper(int value) {
122      this.Value = value;
123    }
124
125    public override bool Equals(object obj) {
126      if (obj as IntWrapper == null)
127        return false;
128      return Value.Equals(((IntWrapper)obj).Value);
129    }
130    public override int GetHashCode() {
131      return Value.GetHashCode();
132    }
133
134  }
135
136  [StorableClass("00A8E48E-8E8A-443C-A327-9F6ACCBE7E80")]
137  public class PrimitivesTest : NumberTest {
138    [Storable]
139    private char c = 'e';
140    [Storable]
141    private long[,] _long_array =
142      new long[,] { { 123, 456, }, { 789, 123 } };
143    [Storable]
144    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
145    [Storable]
146    private object o = new object();
147    public override bool Equals(object obj) {
148      PrimitivesTest pt = obj as PrimitivesTest;
149      if (pt == null)
150        throw new NotSupportedException();
151      return base.Equals(obj) &&
152        c == pt.c &&
153        _long_array == pt._long_array &&
154        list == pt.list &&
155        o == pt.o;
156    }
157    public override int GetHashCode() {
158      return base.GetHashCode() ^
159        c.GetHashCode() ^
160        _long_array.GetHashCode() ^
161        list.GetHashCode() ^
162        o.GetHashCode();
163    }
164  }
165
166  public enum TestEnum { va1, va2, va3, va8 };
167
168  [StorableClass("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  [StorableClass("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  public enum SimpleEnum { one, two, three }
218  public enum ComplexEnum { one = 1, two = 2, three = 3 }
219  [FlagsAttribute]
220  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
221
222  [StorableClass("2F6326ED-023A-415F-B5C7-9F9241940D05")]
223  public class EnumTest {
224    [Storable]
225    public SimpleEnum simpleEnum = SimpleEnum.one;
226    [Storable]
227    public ComplexEnum complexEnum = (ComplexEnum)2;
228    [Storable]
229    public TrickyEnum trickyEnum = (TrickyEnum)15;
230  }
231
232  [StorableClass("92365E2A-1184-4280-B763-4853C7ADF3E3")]
233  public class Custom {
234    [Storable]
235    public int i;
236    [Storable]
237    public Root r;
238    [Storable]
239    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
240  }
241
242  [StorableClass("7CF19EBC-1EC4-4FBE-BCA9-DA48E3CFE30D")]
243  public class Manager {
244
245    public DateTime lastLoadTime;
246    [Storable]
247    private DateTime lastLoadTimePersistence {
248      get { return lastLoadTime; }
249      set { lastLoadTime = DateTime.Now; }
250    }
251    [Storable]
252    public double? dbl;
253  }
254
255  [StorableClass("9092C705-F5E9-4BA9-9750-4357DB29AABF")]
256  public class C {
257    [Storable]
258    public C[][] allCs;
259    [Storable]
260    public KeyValuePair<List<C>, C> kvpList;
261  }
262
263  public class NonSerializable {
264    int x = 0;
265    public override bool Equals(object obj) {
266      NonSerializable ns = obj as NonSerializable;
267      if (ns == null)
268        throw new NotSupportedException();
269      return ns.x == x;
270    }
271    public override int GetHashCode() {
272      return x.GetHashCode();
273    }
274  }
275
276  [StorableClass("FD953B0A-BDE6-41E6-91A8-CA3D90C91CDB")]
277  public class SimpleClass {
278    [Storable]
279    public double x { get; set; }
280    [Storable]
281    public int y { get; set; }
282  }
283
284  #endregion
285
286  [TestClass]
287  public class UseCasesPersistenceNew {
288    #region Helpers
289    private string tempFile;
290
291    [ClassInitialize]
292    public static void Initialize(TestContext testContext) {
293      ConfigurationService.Instance.Reset();
294    }
295
296    [TestInitialize()]
297    public void CreateTempFile() {
298      tempFile = Path.GetTempFileName();
299    }
300
301    [TestCleanup()]
302    public void ClearTempFile() {
303      StreamReader reader = new StreamReader(tempFile);
304      string s = reader.ReadToEnd();
305      reader.Close();
306      File.Delete(tempFile);
307    }
308    #endregion
309
310    #region Persistence 4.0 Profiling Helpers 
311    public class PerformanceData {
312      public TimeSpan OldSerializingTime { get; set; }
313      public TimeSpan NewSerializingTime { get; set; }
314      public TimeSpan OldDeserializingTime { get; set; }
315      public TimeSpan NewDeserializingTime { get; set; }
316      public long OldFileSize { get; set; }
317      public long NewFileSize { get; set; }
318      public long OldSerializingMemoryConsumed { get; set; }
319      public long NewSerializingMemoryConsumed { get; set; }
320      public long OldDeserializingMemoryConsumed { get; set; }
321      public long NewDeserializingMemoryConsumed { get; set; }
322    }
323
324    private void SerializeNew(object o) {
325      ProtoBufSerializer serializer = new ProtoBufSerializer();
326      serializer.Serialize(o, tempFile);
327    }
328    private void SerializeOld(object o) {
329      XmlGenerator.Serialize(o, tempFile);
330    }
331    private object DeserializeNew() {
332      ProtoBufSerializer serializer = new ProtoBufSerializer();
333      return serializer.Deserialize(tempFile);
334    }
335    private object DeserialiezOld() {
336      return XmlParser.Deserialize(tempFile);
337    }
338
339    private void CollectGarbage() {
340      GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
341      GC.WaitForPendingFinalizers();
342    }
343
344    public PerformanceData ProfileSingleRun(Func<object> GenerateDataFunc) {
345      PerformanceData performanceData = new PerformanceData();
346      Stopwatch sw = new Stopwatch();
347      object data = GenerateDataFunc();
348      object result = null;
349      long startMem, endMem;
350
351
352      //old file format serializing
353      CollectGarbage();
354      startMem = GC.GetTotalMemory(false);
355      sw.Start();
356      SerializeOld(data);
357      sw.Stop();
358      endMem = GC.GetTotalMemory(false);
359      performanceData.OldSerializingTime = sw.Elapsed;
360      performanceData.OldFileSize = new FileInfo(tempFile).Length;
361      performanceData.OldSerializingMemoryConsumed = endMem - startMem;
362      sw.Reset();
363
364
365      //old file format deserializing
366      CollectGarbage();
367      startMem = GC.GetTotalMemory(false);
368      sw.Start();
369      result = DeserialiezOld();
370      sw.Stop();
371      endMem = GC.GetTotalMemory(false);
372      performanceData.OldDeserializingTime = sw.Elapsed;
373      performanceData.OldDeserializingMemoryConsumed = endMem - startMem;
374      sw.Reset();
375
376
377      //new file format serializing
378      CollectGarbage();
379      startMem = GC.GetTotalMemory(false);
380      sw.Start();
381      SerializeNew(data);
382      sw.Stop();
383      endMem = GC.GetTotalMemory(false);
384      performanceData.NewSerializingTime = sw.Elapsed;
385      performanceData.NewSerializingMemoryConsumed = endMem - startMem;
386      performanceData.NewFileSize = new FileInfo(tempFile).Length;
387      sw.Reset();
388
389
390      //new file format deserializing
391      CollectGarbage();
392      startMem = GC.GetTotalMemory(false);
393      sw.Start();
394      result = DeserializeNew();
395      sw.Stop();
396      endMem = GC.GetTotalMemory(false);
397      performanceData.NewDeserializingTime = sw.Elapsed;
398      performanceData.NewDeserializingMemoryConsumed = endMem - startMem;
399      sw.Reset();
400
401      return performanceData;
402    }
403
404    public string Profile(Func<object> GenerateDataFunc) {
405      int nrOfRepetitions = 30;
406      StringBuilder report = new StringBuilder();
407      List<PerformanceData> dataList = new List<PerformanceData>();
408
409      for (int i = 0; i < nrOfRepetitions; i++) {
410        dataList.Add(ProfileSingleRun(GenerateDataFunc));
411      }
412
413      report.Append("Performance Report for " + GenerateDataFunc.Method.Name + ": " + Environment.NewLine);
414      report.Append(Environment.NewLine);
415      report.AppendFormat("Avg. old vs. new time for serializing a file; {0};{1};{2}",
416              dataList.Select(x => x.OldSerializingTime).Average(),
417              dataList.Select(x => x.NewSerializingTime).Average(),
418              dataList.Select(x => x.OldSerializingTime.TotalMilliseconds).Average() / dataList.Select(x => x.NewSerializingTime.TotalMilliseconds).Average()
419              );
420      report.Append(Environment.NewLine);
421      report.AppendFormat("Avg. old vs. new time for deserializing a file; {0};{1};{2}",
422              dataList.Select(x => x.OldDeserializingTime).Average(),
423              dataList.Select(x => x.NewDeserializingTime).Average(),
424              dataList.Select(x => x.OldDeserializingTime.TotalMilliseconds).Average() / dataList.Select(x => x.NewDeserializingTime.TotalMilliseconds).Average()
425              );
426      report.Append(Environment.NewLine);
427      report.AppendFormat("Avg. old vs. new file size (in bytes); {0};{1};{2}",
428              dataList.Select(x => x.OldFileSize).Average(),
429              dataList.Select(x => x.NewFileSize).Average(),
430              dataList.Select(x => x.OldFileSize).Average() / dataList.Select(x => x.NewFileSize).Average()
431              );
432      report.Append(Environment.NewLine);
433      report.AppendFormat("Avg. old vs. new memory consumption for serializing a file (in bytes); {0};{1};{2}",
434              dataList.Select(x => x.OldSerializingMemoryConsumed).Average(),
435              dataList.Select(x => x.NewSerializingMemoryConsumed).Average(),
436              dataList.Select(x => x.OldSerializingMemoryConsumed).Average() / dataList.Select(x => x.NewSerializingMemoryConsumed).Average()
437              );
438      report.Append(Environment.NewLine);
439      report.AppendFormat("Avg. old vs. new memory consumption for deserializing a file (in bytes); {0};{1};{2}",
440              dataList.Select(x => x.OldDeserializingMemoryConsumed).Average(),
441              dataList.Select(x => x.NewDeserializingMemoryConsumed).Average(),
442              dataList.Select(x => x.OldDeserializingMemoryConsumed).Average() / dataList.Select(x => x.NewDeserializingMemoryConsumed).Average()
443              );
444      report.Append(Environment.NewLine);
445
446
447      return report.ToString();
448    }
449    #endregion
450
451    #region Persistence 4.0 test methods
452    [TestMethod]
453    [TestCategory("Persistence4")]
454    [TestProperty("Time", "short")]
455    public void TestBool() {
456      var test = new Func<object>(() => { return true; });
457      ProtoBufSerializer serializer = new ProtoBufSerializer();
458      serializer.Serialize(test(), tempFile);
459      object o = serializer.Deserialize(tempFile);
460      bool result = (bool)o;
461      Assert.AreEqual(test(), result);
462
463      string msg = Profile(test);
464      Console.WriteLine(msg);
465    }
466
467    [TestMethod]
468    [TestCategory("Persistence4")]
469    [TestProperty("Time", "short")]
470    public void TestInt() {
471      var test = new Func<object>(() => { return (int)42; });
472      ProtoBufSerializer serializer = new ProtoBufSerializer();
473      serializer.Serialize(test(), tempFile);
474      object o = serializer.Deserialize(tempFile);
475      int result = (int)o;
476      Assert.AreEqual(test(), result);
477
478      string msg = Profile(test);
479      Console.WriteLine(msg);
480    }
481
482    [TestMethod]
483    [TestCategory("Persistence4")]
484    [TestProperty("Time", "short")]
485    public void TestDouble() {
486      var test = new Func<object>(() => { return 42.5d; });
487      ProtoBufSerializer serializer = new ProtoBufSerializer();
488      serializer.Serialize(test(), tempFile);
489      object o = serializer.Deserialize(tempFile);
490      double result = (double)o;
491      Assert.AreEqual(test(), result);
492      Assert.IsTrue(o is double);
493
494      string msg = Profile(test);
495      Console.WriteLine(msg);
496    }
497
498    [TestMethod]
499    [TestCategory("Persistence4")]
500    [TestProperty("Time", "short")]
501    public void TestFloat() {
502      var test = new Func<object>(() => { return 42.5f; });
503      ProtoBufSerializer serializer = new ProtoBufSerializer();
504      serializer.Serialize(test(), tempFile);
505      object o = serializer.Deserialize(tempFile);
506      float result = (float)o;
507      Assert.AreEqual(test(), result);
508      Assert.IsTrue(o is float);
509
510      string msg = Profile(test);
511      Console.WriteLine(msg);
512    }
513
514    [TestMethod]
515    [TestCategory("Persistence4")]
516    [TestProperty("Time", "short")]
517    public void TestDecimal() {
518      var test = new Func<object>(() => { return 42.5m; });
519      ProtoBufSerializer serializer = new ProtoBufSerializer();
520      serializer.Serialize(test(), tempFile);
521      object o = serializer.Deserialize(tempFile);
522      decimal result = (decimal)o;
523      Assert.AreEqual(test(), result);
524      Assert.IsTrue(o is decimal);
525
526      string msg = Profile(test);
527      Console.WriteLine(msg);
528    }
529
530    [TestMethod]
531    [TestCategory("Persistence4")]
532    [TestProperty("Time", "short")]
533    public void TestLong() {
534      var test = new Func<object>(() => { return 42l; });
535      ProtoBufSerializer serializer = new ProtoBufSerializer();
536      serializer.Serialize(test(), tempFile);
537      object o = serializer.Deserialize(tempFile);
538      long result = (long)o;
539      Assert.AreEqual(test(), result);
540      Assert.IsTrue(o is long);
541
542      string msg = Profile(test);
543      Console.WriteLine(msg);
544    }
545
546    [TestMethod]
547    [TestCategory("Persistence4")]
548    [TestProperty("Time", "short")]
549    public void TestUInt() {
550      var test = new Func<object>(() => { return 42u; });
551      ProtoBufSerializer serializer = new ProtoBufSerializer();
552      serializer.Serialize(test(), tempFile);
553      object o = serializer.Deserialize(tempFile);
554      uint result = (uint)o;
555      Assert.AreEqual(test(), result);
556      Assert.IsTrue(o is uint);
557
558      string msg = Profile(test);
559      Console.WriteLine(msg);
560    }
561
562    [TestMethod]
563    [TestCategory("Persistence4")]
564    [TestProperty("Time", "short")]
565    public void TestShort() {
566      var test = new Func<object>(() => { short s = 42; return s; });
567      ProtoBufSerializer serializer = new ProtoBufSerializer();
568      serializer.Serialize(test(), tempFile);
569      object o = serializer.Deserialize(tempFile);
570      short result = (short)o;
571      Assert.IsTrue(o is short);
572      Assert.AreEqual(test(), result);
573
574      string msg = Profile(test);
575      Console.WriteLine(msg);
576    }
577
578    [TestMethod]
579    [TestCategory("Persistence4")]
580    [TestProperty("Time", "short")]
581    public void TestByte() {
582      var test = new Func<object>(() => { byte b = 42; return b; });
583      ProtoBufSerializer serializer = new ProtoBufSerializer();
584      serializer.Serialize(test(), tempFile);
585      object o = serializer.Deserialize(tempFile);
586      byte result = (byte)o;
587      Assert.IsTrue(o is byte);
588      Assert.AreEqual(test(), result);
589
590      string msg = Profile(test);
591      Console.WriteLine(msg);
592    }
593
594    [TestMethod]
595    [TestCategory("Persistence4")]
596    [TestProperty("Time", "short")]
597    public void TestEnumSimple() {
598      var test = new Func<object>(() => { return SimpleEnum.two; });
599
600      ProtoBufSerializer serializer = new ProtoBufSerializer();
601      serializer.Serialize(test(), tempFile);
602      object o = serializer.Deserialize(tempFile);
603      SimpleEnum result = (SimpleEnum)o;
604      Assert.AreEqual(test(), result);
605
606      string msg = Profile(test);
607      Console.WriteLine(msg);
608    }
609
610    [TestMethod]
611    [TestCategory("Persistence4")]
612    [TestProperty("Time", "short")]
613    public void TestEnumComplex() {
614      var test = new Func<object>(() => { return ComplexEnum.three; });
615      ProtoBufSerializer serializer = new ProtoBufSerializer();
616      serializer.Serialize(test(), tempFile);
617      object o = serializer.Deserialize(tempFile);
618      ComplexEnum result = (ComplexEnum)o;
619      Assert.AreEqual(test(), result);
620
621      string msg = Profile(test);
622      Console.WriteLine(msg);
623    }
624
625    [TestMethod]
626    [TestCategory("Persistence4")]
627    [TestProperty("Time", "short")]
628    public void TestType() {
629      var test = new Func<object>(() => { return typeof(HeuristicLab.Algorithms.GeneticAlgorithm.GeneticAlgorithm); });
630      ProtoBufSerializer serializer = new ProtoBufSerializer();
631      serializer.Serialize(test(), tempFile);
632      object o = serializer.Deserialize(tempFile);
633      Type result = (Type)o;
634      Assert.AreEqual(test(), result);
635
636      string msg = Profile(test);
637      Console.WriteLine(msg);
638    }
639
640    [TestMethod]
641    [TestCategory("Persistence4")]
642    [TestProperty("Time", "short")]
643    public void TestBytes() {
644      var test = new Func<byte[]>(() => { return new byte[] { 3, 1 }; });
645      ProtoBufSerializer serializer = new ProtoBufSerializer();
646      serializer.Serialize(test(), tempFile);
647      object o = serializer.Deserialize(tempFile);
648      byte[] result = (byte[])o;
649      Assert.AreEqual(test()[0], result[0]);
650      Assert.AreEqual(test()[1], result[1]);
651
652      string msg = Profile(test);
653      Console.WriteLine(msg);
654    }
655
656    [TestMethod]
657    [TestCategory("Persistence4")]
658    [TestProperty("Time", "short")]
659    public void TestSBytes() {
660      var test = new Func<sbyte[]>(() => { return new sbyte[] { 3, 1 }; });
661      ProtoBufSerializer serializer = new ProtoBufSerializer();
662      serializer.Serialize(test(), tempFile);
663      object o = serializer.Deserialize(tempFile);
664      sbyte[] result = (sbyte[])o;
665      Assert.AreEqual(test()[0], result[0]);
666      Assert.AreEqual(test()[1], result[1]);
667
668      string msg = Profile(test);
669      Console.WriteLine(msg);
670    }
671
672    [TestMethod]
673    [TestCategory("Persistence4")]
674    [TestProperty("Time", "short")]
675    public void TestChars() {
676      var test = new Func<char[]>(() => { return new char[] { 'a', 'b' }; });
677      ProtoBufSerializer serializer = new ProtoBufSerializer();
678      serializer.Serialize(test(), tempFile);
679      object o = serializer.Deserialize(tempFile);
680      char[] result = (char[])o;
681      Assert.AreEqual(test()[0], result[0]);
682      Assert.AreEqual(test()[1], result[1]);
683
684      string msg = Profile(test);
685      Console.WriteLine(msg);
686    }
687
688    [TestMethod]
689    [TestCategory("Persistence4")]
690    [TestProperty("Time", "short")]
691    public void TestShorts() {
692      var test = new Func<short[]>(() => { return new short[] { 3, 1 }; });
693      ProtoBufSerializer serializer = new ProtoBufSerializer();
694      serializer.Serialize(test(), tempFile);
695      object o = serializer.Deserialize(tempFile);
696      short[] result = (short[])o;
697      Assert.AreEqual(test()[0], result[0]);
698      Assert.AreEqual(test()[1], result[1]);
699
700      string msg = Profile(test);
701      Console.WriteLine(msg);
702    }
703
704    [TestMethod]
705    [TestCategory("Persistence4")]
706    [TestProperty("Time", "short")]
707    public void TestUShorts() {
708      var test = new Func<ushort[]>(() => { return new ushort[] { 3, 1 }; });
709      ProtoBufSerializer serializer = new ProtoBufSerializer();
710      serializer.Serialize(test(), tempFile);
711      object o = serializer.Deserialize(tempFile);
712      ushort[] result = (ushort[])o;
713      Assert.AreEqual(test()[0], result[0]);
714      Assert.AreEqual(test()[1], result[1]);
715
716      string msg = Profile(test);
717      Console.WriteLine(msg);
718    }
719
720    [TestMethod]
721    [TestCategory("Persistence4")]
722    [TestProperty("Time", "short")]
723    public void TestString() {
724      var test = new Func<object>(() => { return "Hello World!"; });
725      ProtoBufSerializer serializer = new ProtoBufSerializer();
726      serializer.Serialize(test(), tempFile);
727      object o = serializer.Deserialize(tempFile);
728      string result = (string)o;
729      Assert.AreEqual(test(), result);
730
731      string msg = Profile(test);
732      Console.WriteLine(msg);
733    }
734
735    [TestMethod]
736    [TestCategory("Persistence4")]
737    [TestProperty("Time", "short")]
738    public void TestColor() {
739      var test = new Func<object>(() => { return Color.FromArgb(12, 34, 56, 78); });
740      ProtoBufSerializer serializer = new ProtoBufSerializer();
741      serializer.Serialize(test(), tempFile);
742      object o = serializer.Deserialize(tempFile);
743      Color result = (Color)o;
744      Assert.AreEqual(test(), result);
745
746      string msg = Profile(test);
747      Console.WriteLine(msg);
748    }
749
750    [TestMethod]
751    [TestCategory("Persistence4")]
752    [TestProperty("Time", "short")]
753    public void TestPoint() {
754      var test = new Func<object>(() => { return new Point(3, 4); });
755      ProtoBufSerializer serializer = new ProtoBufSerializer();
756      serializer.Serialize(test(), tempFile);
757      object o = serializer.Deserialize(tempFile);
758      Point result = (Point)o;
759      Assert.AreEqual(((Point)test()).X, result.X);
760      Assert.AreEqual(((Point)test()).Y, result.Y);
761
762      string msg = Profile(test);
763      Console.WriteLine(msg);
764    }
765
766    [TestMethod]
767    [TestCategory("Persistence4")]
768    [TestProperty("Time", "short")]
769    public void TestBoolArray() {
770      var test = new Func<bool[]>(() => { return new[] { true, false, true }; });
771      ProtoBufSerializer serializer = new ProtoBufSerializer();
772      serializer.Serialize(test(), tempFile);
773      object o = serializer.Deserialize(tempFile);
774      bool[] result = (bool[])o;
775      Assert.AreEqual(test()[0], result[0]);
776      Assert.AreEqual(test()[1], result[1]);
777      Assert.AreEqual(test()[2], result[2]);
778
779      string msg = Profile(test);
780      Console.WriteLine(msg);
781    }
782
783    [TestMethod]
784    [TestCategory("Persistence4")]
785    [TestProperty("Time", "short")]
786    public void TestIntArray() {
787      var test = new Func<int[]>(() => { return new[] { 41, 22, 13 }; });
788      ProtoBufSerializer serializer = new ProtoBufSerializer();
789      serializer.Serialize(test(), tempFile);
790      object o = serializer.Deserialize(tempFile);
791      int[] result = (int[])o;
792      Assert.AreEqual(test()[0], result[0]);
793      Assert.AreEqual(test()[1], result[1]);
794      Assert.AreEqual(test()[2], result[2]);
795
796      string msg = Profile(test);
797      Console.WriteLine(msg);
798    }
799
800    [TestMethod]
801    [TestCategory("Persistence4")]
802    [TestProperty("Time", "short")]
803    public void TestLongArray() {
804      var test = new Func<long[]>(() => { return new[] { 414481188112191633l, 245488586662l, 13546881335845865l }; });
805      ProtoBufSerializer serializer = new ProtoBufSerializer();
806      serializer.Serialize(test(), tempFile);
807      object o = serializer.Deserialize(tempFile);
808      long[] result = (long[])o;
809      Assert.AreEqual(test()[0], result[0]);
810      Assert.AreEqual(test()[1], result[1]);
811      Assert.AreEqual(test()[2], result[2]);
812
813      string msg = Profile(test);
814      Console.WriteLine(msg);
815    }
816
817    [TestMethod]
818    [TestCategory("Persistence4")]
819    [TestProperty("Time", "short")]
820    public void TestDoubleArray() {
821      var test = new Func<double[]>(() => { return new[] { 41.5, 22.7, 13.8 }; });
822      ProtoBufSerializer serializer = new ProtoBufSerializer();
823      serializer.Serialize(test(), tempFile);
824      object o = serializer.Deserialize(tempFile);
825      double[] result = (double[])o;
826      Assert.AreEqual(test()[0], result[0]);
827      Assert.AreEqual(test()[1], result[1]);
828      Assert.AreEqual(test()[2], result[2]);
829
830      string msg = Profile(test);
831      Console.WriteLine(msg);
832    }
833
834    [TestMethod]
835    [TestCategory("Persistence4")]
836    [TestProperty("Time", "short")]
837    public void TestObjectArray() {
838      var test = new Func<SimpleClass[]>(() => {
839        return new[] { new SimpleClass() { x = 42, y = 43 },
840                       new SimpleClass() { x = 44.44, y = 5677 },
841                       new SimpleClass() { x = 533.33, y = 2345 } };
842      });
843      ProtoBufSerializer serializer = new ProtoBufSerializer();
844      serializer.Serialize(test(), tempFile);
845      object o = serializer.Deserialize(tempFile);
846      SimpleClass[] result = (SimpleClass[])o;
847      Assert.AreEqual(test()[0].x, result[0].x);
848      Assert.AreEqual(test()[0].y, result[0].y);
849      Assert.AreEqual(test()[1].x, result[1].x);
850      Assert.AreEqual(test()[1].y, result[1].y);
851      Assert.AreEqual(test()[2].x, result[2].x);
852      Assert.AreEqual(test()[2].y, result[2].y);
853
854      string msg = Profile(test);
855      Console.WriteLine(msg);
856    }
857
858    [TestMethod]
859    [TestCategory("Persistence4")]
860    [TestProperty("Time", "short")]
861    public void TestStack() {
862      var test = new Func<Stack>(() => {
863        return new Stack(new int[] { 1, 2, 3 });
864      });
865      ProtoBufSerializer serializer = new ProtoBufSerializer();
866      serializer.Serialize(test(), tempFile);
867      object o = serializer.Deserialize(tempFile);
868      Stack result = (Stack)o;
869      var actualStack = test();
870      Assert.AreEqual(actualStack.Pop(), result.Pop());
871      Assert.AreEqual(actualStack.Pop(), result.Pop());
872      Assert.AreEqual(actualStack.Pop(), result.Pop());
873
874      string msg = Profile(test);
875      Console.WriteLine(msg);
876    }
877
878    [TestMethod]
879    [TestCategory("Persistence4")]
880    [TestProperty("Time", "short")]
881    public void TestArrayOfStack() {
882      var test = new Func<object[]>(() => {
883        return new object[] {
884          new Stack(new int[] { 1, 2, 3 }),
885          new Stack<int>(new int[] { 1, 2, 3 }),
886      };
887      });
888      ProtoBufSerializer serializer = new ProtoBufSerializer();
889      serializer.Serialize(test(), tempFile);
890      object o = serializer.Deserialize(tempFile);
891      var result = (object[])o;
892      var firstStack = (Stack)result[0];
893      var secondStack = (Stack<int>)result[1];
894      var actual = test();
895      var actualFirst = (Stack)actual[0];
896      var actualSecond = (Stack<int>)actual[1];
897
898      Assert.AreEqual(actualFirst.Pop(), firstStack.Pop());
899      Assert.AreEqual(actualFirst.Pop(), firstStack.Pop());
900      Assert.AreEqual(actualFirst.Pop(), firstStack.Pop());
901      Assert.AreEqual(actualSecond.Pop(), secondStack.Pop());
902      Assert.AreEqual(actualSecond.Pop(), secondStack.Pop());
903      Assert.AreEqual(actualSecond.Pop(), secondStack.Pop());
904
905      string msg = Profile(test);
906      Console.WriteLine(msg);
907    }
908
909
910    [TestMethod]
911    [TestCategory("Persistence4")]
912    [TestProperty("Time", "short")]
913    public void TestIntValueArray() {
914      var test = new Func<IntValue[]>(() => { return new[] { new IntValue(41), new IntValue(22), new IntValue(13) }; });
915      ProtoBufSerializer serializer = new ProtoBufSerializer();
916      serializer.Serialize(test(), tempFile);
917      object o = serializer.Deserialize(tempFile);
918      IntValue[] result = (IntValue[])o;
919      Assert.AreEqual(test()[0].Value, result[0].Value);
920      Assert.AreEqual(test()[1].Value, result[1].Value);
921      Assert.AreEqual(test()[2].Value, result[2].Value);
922
923      string msg = Profile(test);
924      Console.WriteLine(msg);
925    }
926
927    [TestMethod]
928    [TestCategory("Persistence4")]
929    [TestProperty("Time", "short")]
930    public void TestIntValueArrayArray() {
931      var test = new Func<IntValue[][]>(() => { return new IntValue[][] { new IntValue[] { new IntValue(41), new IntValue(22), new IntValue(13) } }; });
932      ProtoBufSerializer serializer = new ProtoBufSerializer();
933      serializer.Serialize(test(), tempFile);
934      object o = serializer.Deserialize(tempFile);
935      IntValue[][] result = (IntValue[][])o;
936      Assert.AreEqual(test()[0][0].Value, result[0][0].Value);
937      Assert.AreEqual(test()[0][1].Value, result[0][1].Value);
938      Assert.AreEqual(test()[0][2].Value, result[0][2].Value);
939
940      string msg = Profile(test);
941      Console.WriteLine(msg);
942    }
943    #endregion
944
945
946    #region Old persistence test methods
947    [TestMethod]
948    [TestCategory("Persistence4")]
949    [TestProperty("Time", "short")]
950    public void ComplexStorable() {
951      ProtoBufSerializer serializer = new ProtoBufSerializer();
952      Root r = InitializeComplexStorable();
953      serializer.Serialize(r, tempFile);
954      Root newR = (Root)serializer.Deserialize(tempFile);
955      CompareComplexStorables(r, newR);
956    }
957
958    private static void CompareComplexStorables(Root r, Root newR) {
959      Assert.AreEqual(
960        DebugStringGenerator.Serialize(r),
961        DebugStringGenerator.Serialize(newR));
962      Assert.AreSame(newR, newR.selfReferences[0]);
963      Assert.AreNotSame(r, newR);
964      Assert.AreEqual(r.myEnum, TestEnum.va1);
965      Assert.AreEqual(r.i[0], 7);
966      Assert.AreEqual(r.i[1], 5);
967      Assert.AreEqual(r.i[2], 6);
968      Assert.AreEqual(r.s, "new value");
969      Assert.AreEqual(r.intArray[0], 3);
970      Assert.AreEqual(r.intArray[1], 2);
971      Assert.AreEqual(r.intArray[2], 1);
972      Assert.AreEqual(r.intList[0], 9);
973      Assert.AreEqual(r.intList[1], 8);
974      Assert.AreEqual(r.intList[2], 7);
975      Assert.AreEqual(r.multiDimArray[0, 0], 5);
976      Assert.AreEqual(r.multiDimArray[0, 1], 4);
977      Assert.AreEqual(r.multiDimArray[0, 2], 3);
978      Assert.AreEqual(r.multiDimArray[1, 0], 1);
979      Assert.AreEqual(r.multiDimArray[1, 1], 4);
980      Assert.AreEqual(r.multiDimArray[1, 2], 6);
981      Assert.IsFalse(r.boolean);
982      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
983      Assert.AreEqual(r.kvp.Key, "string key");
984      Assert.AreEqual(r.kvp.Value, 321);
985      Assert.IsNull(r.uninitialized);
986      Assert.AreEqual(newR.myEnum, TestEnum.va1);
987      Assert.AreEqual(newR.i[0], 7);
988      Assert.AreEqual(newR.i[1], 5);
989      Assert.AreEqual(newR.i[2], 6);
990      Assert.AreEqual(newR.s, "new value");
991      Assert.AreEqual(newR.intArray[0], 3);
992      Assert.AreEqual(newR.intArray[1], 2);
993      Assert.AreEqual(newR.intArray[2], 1);
994      Assert.AreEqual(newR.intList[0], 9);
995      Assert.AreEqual(newR.intList[1], 8);
996      Assert.AreEqual(newR.intList[2], 7);
997      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
998      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
999      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
1000      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
1001      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
1002      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
1003      Assert.AreEqual(newR.intStack.Pop(), 3);
1004      Assert.AreEqual(newR.intStack.Pop(), 2);
1005      Assert.AreEqual(newR.intStack.Pop(), 1);
1006      Assert.IsFalse(newR.boolean);
1007      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
1008      Assert.AreEqual(newR.kvp.Key, "string key");
1009      Assert.AreEqual(newR.kvp.Value, 321);
1010      Assert.IsNull(newR.uninitialized);
1011    }
1012
1013    private static Root InitializeComplexStorable() {
1014      Root r = new Root();
1015      r.intStack.Push(1);
1016      r.intStack.Push(2);
1017      r.intStack.Push(3);
1018      r.selfReferences = new List<Root> { r, r };
1019      r.c = new Custom { r = r };
1020      r.dict.Add("one", 1);
1021      r.dict.Add("two", 2);
1022      r.dict.Add("three", 3);
1023      r.myEnum = TestEnum.va1;
1024      r.i = new[] { 7, 5, 6 };
1025      r.s = "new value";
1026      r.intArray = new ArrayList { 3, 2, 1 };
1027      r.intList = new List<int> { 9, 8, 7 };
1028      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
1029      r.boolean = false;
1030      r.dateTime = DateTime.Now;
1031      r.kvp = new KeyValuePair<string, int>("string key", 321);
1032      r.uninitialized = null;
1033
1034      return r;
1035    }
1036
1037    [TestMethod]
1038    [TestCategory("Persistence4")]
1039    [TestProperty("Time", "short")]
1040    public void SelfReferences() {
1041      ProtoBufSerializer serializer = new ProtoBufSerializer();
1042      C c = new C();
1043      C[][] cs = new C[2][];
1044      cs[0] = new C[] { c };
1045      cs[1] = new C[] { c };
1046      c.allCs = cs;
1047      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
1048      serializer.Serialize(cs, tempFile);
1049      object o = serializer.Deserialize(tempFile);
1050      Assert.AreEqual(
1051        DebugStringGenerator.Serialize(cs),
1052        DebugStringGenerator.Serialize(o));
1053      Assert.AreSame(c, c.allCs[0][0]);
1054      Assert.AreSame(c, c.allCs[1][0]);
1055      Assert.AreSame(c, c.kvpList.Key[0]);
1056      Assert.AreSame(c, c.kvpList.Value);
1057      C[][] newCs = (C[][])o;
1058      C newC = newCs[0][0];
1059      Assert.AreSame(newC, newC.allCs[0][0]);
1060      Assert.AreSame(newC, newC.allCs[1][0]);
1061      Assert.AreSame(newC, newC.kvpList.Key[0]);
1062      Assert.AreSame(newC, newC.kvpList.Value);
1063    }
1064
1065    [TestMethod]
1066    [TestCategory("Persistence4")]
1067    [TestProperty("Time", "short")]
1068    public void ArrayCreation() {
1069      ProtoBufSerializer serializer = new ProtoBufSerializer();
1070      ArrayList[] arrayListArray = new ArrayList[4];
1071      arrayListArray[0] = new ArrayList();
1072      arrayListArray[0].Add(arrayListArray);
1073      arrayListArray[0].Add(arrayListArray);
1074      arrayListArray[1] = new ArrayList();
1075      arrayListArray[1].Add(arrayListArray);
1076      arrayListArray[2] = new ArrayList();
1077      arrayListArray[2].Add(arrayListArray);
1078      arrayListArray[2].Add(arrayListArray);
1079      //Array a = Array.CreateInstance(
1080      //                        typeof(object),
1081      //                        new[] { 1, 2 }, new[] { 3, 4 });
1082      //arrayListArray[2].Add(a);
1083      serializer.Serialize(arrayListArray, tempFile);
1084      object o = serializer.Deserialize(tempFile);
1085      Assert.AreEqual(
1086        DebugStringGenerator.Serialize(arrayListArray),
1087        DebugStringGenerator.Serialize(o));
1088      ArrayList[] newArray = (ArrayList[])o;
1089      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
1090      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
1091      Assert.AreSame(newArray, newArray[0][0]);
1092      Assert.AreSame(newArray, newArray[2][1]);
1093    }
1094
1095    [TestMethod]
1096    [TestCategory("Persistence4")]
1097    [TestProperty("Time", "short")]
1098    public void CustomSerializationProperty() {
1099      ProtoBufSerializer serializer = new ProtoBufSerializer();
1100      Manager m = new Manager();
1101      serializer.Serialize(m, tempFile);
1102      Manager newM = (Manager)serializer.Deserialize(tempFile);
1103      Assert.AreNotEqual(
1104        DebugStringGenerator.Serialize(m),
1105        DebugStringGenerator.Serialize(newM));
1106      Assert.AreEqual(m.dbl, newM.dbl);
1107      Assert.AreEqual(m.lastLoadTime, new DateTime());
1108      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
1109      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
1110    }
1111
1112    [TestMethod]
1113    [TestCategory("Persistence4")]
1114    [TestProperty("Time", "short")]
1115    public void Primitives() {
1116      ProtoBufSerializer serializer = new ProtoBufSerializer();
1117      PrimitivesTest sdt = new PrimitivesTest();
1118      serializer.Serialize(sdt, tempFile);
1119      object o = serializer.Deserialize(tempFile);
1120      Assert.AreEqual(
1121        DebugStringGenerator.Serialize(sdt),
1122        DebugStringGenerator.Serialize(o));
1123    }
1124
1125    [TestMethod]
1126    [TestCategory("Persistence4")]
1127    [TestProperty("Time", "short")]
1128    public void MultiDimensionalArray() {
1129      ProtoBufSerializer serializer = new ProtoBufSerializer();
1130      string[,] mDimString = new string[,] {
1131        {"ora", "et", "labora"},
1132        {"Beten", "und", "Arbeiten"}
1133      };
1134      serializer.Serialize(mDimString, tempFile);
1135      object o = serializer.Deserialize(tempFile);
1136      Assert.AreEqual(
1137        DebugStringGenerator.Serialize(mDimString),
1138        DebugStringGenerator.Serialize(o));
1139    }
1140
1141    [StorableClass("87A331AF-14DC-48B3-B577-D49065743BE6")]
1142    public class NestedType {
1143      [Storable]
1144      private string value = "value";
1145      public override bool Equals(object obj) {
1146        NestedType nt = obj as NestedType;
1147        if (nt == null)
1148          throw new NotSupportedException();
1149        return nt.value == value;
1150      }
1151      public override int GetHashCode() {
1152        return value.GetHashCode();
1153      }
1154    }
1155
1156    [TestMethod]
1157    [TestCategory("Persistence4")]
1158    [TestProperty("Time", "short")]
1159    public void NestedTypeTest() {
1160      ProtoBufSerializer serializer = new ProtoBufSerializer();
1161      NestedType t = new NestedType();
1162      serializer.Serialize(t, tempFile);
1163      object o = serializer.Deserialize(tempFile);
1164      Assert.AreEqual(
1165        DebugStringGenerator.Serialize(t),
1166        DebugStringGenerator.Serialize(o));
1167      Assert.IsTrue(t.Equals(o));
1168    }
1169
1170
1171    [TestMethod]
1172    [TestCategory("Persistence4")]
1173    [TestProperty("Time", "short")]
1174    public void SimpleArray() {
1175      ProtoBufSerializer serializer = new ProtoBufSerializer();
1176      string[] strings = { "ora", "et", "labora" };
1177      serializer.Serialize(strings, tempFile);
1178      object o = serializer.Deserialize(tempFile);
1179      Assert.AreEqual(
1180        DebugStringGenerator.Serialize(strings),
1181        DebugStringGenerator.Serialize(o));
1182    }
1183
1184    [TestMethod]
1185    [TestCategory("Persistence4")]
1186    [TestProperty("Time", "short")]
1187    public void PrimitiveRoot() {
1188      ProtoBufSerializer serializer = new ProtoBufSerializer();
1189      serializer.Serialize(12.3f, tempFile);
1190      object o = serializer.Deserialize(tempFile);
1191      Assert.AreEqual(
1192        DebugStringGenerator.Serialize(12.3f),
1193        DebugStringGenerator.Serialize(o));
1194    }
1195
1196    private string formatFullMemberName(MemberInfo mi) {
1197      return new StringBuilder()
1198        .Append(mi.DeclaringType.Assembly.GetName().Name)
1199        .Append(": ")
1200        .Append(mi.DeclaringType.Namespace)
1201        .Append('.')
1202        .Append(mi.DeclaringType.Name)
1203        .Append('.')
1204        .Append(mi.Name).ToString();
1205    }
1206
1207    public void CodingConventions() {
1208      List<string> lowerCaseMethodNames = new List<string>();
1209      List<string> lowerCaseProperties = new List<string>();
1210      List<string> lowerCaseFields = new List<string>();
1211      foreach (Assembly a in PluginLoader.Assemblies) {
1212        if (!a.GetName().Name.StartsWith("HeuristicLab"))
1213          continue;
1214        foreach (Type t in a.GetTypes()) {
1215          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
1216            if (mi.DeclaringType.Name.StartsWith("<>"))
1217              continue;
1218            if (char.IsLower(mi.Name[0])) {
1219              if (mi.MemberType == MemberTypes.Field)
1220                lowerCaseFields.Add(formatFullMemberName(mi));
1221              if (mi.MemberType == MemberTypes.Property)
1222                lowerCaseProperties.Add(formatFullMemberName(mi));
1223              if (mi.MemberType == MemberTypes.Method &&
1224                !mi.Name.StartsWith("get_") &&
1225                !mi.Name.StartsWith("set_") &&
1226                !mi.Name.StartsWith("add_") &&
1227                !mi.Name.StartsWith("remove_") &&
1228                !mi.Name.StartsWith("op_"))
1229                lowerCaseMethodNames.Add(formatFullMemberName(mi));
1230            }
1231          }
1232        }
1233      }
1234      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
1235      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
1236      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
1237    }
1238
1239    [TestMethod]
1240    [TestCategory("Persistence4")]
1241    [TestProperty("Time", "short")]
1242    public void Enums() {
1243      ProtoBufSerializer serializer = new ProtoBufSerializer();
1244      EnumTest et = new EnumTest();
1245      et.simpleEnum = SimpleEnum.two;
1246      et.complexEnum = ComplexEnum.three;
1247      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
1248      serializer.Serialize(et, tempFile);
1249      EnumTest newEt = (EnumTest)serializer.Deserialize(tempFile);
1250      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
1251      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
1252      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
1253    }
1254
1255    [TestMethod]
1256    [TestCategory("Persistence4")]
1257    [TestProperty("Time", "short")]
1258    public void TestAliasingWithOverriddenEquals() {
1259      ProtoBufSerializer serializer = new ProtoBufSerializer();
1260      List<IntWrapper> ints = new List<IntWrapper>();
1261      ints.Add(new IntWrapper(1));
1262      ints.Add(new IntWrapper(1));
1263      Assert.AreEqual(ints[0], ints[1]);
1264      Assert.AreNotSame(ints[0], ints[1]);
1265      serializer.Serialize(ints, tempFile);
1266      List<IntWrapper> newInts = (List<IntWrapper>)serializer.Deserialize(tempFile);
1267      Assert.AreEqual(newInts[0].Value, 1);
1268      Assert.AreEqual(newInts[1].Value, 1);
1269      Assert.AreEqual(newInts[0], newInts[1]);
1270      Assert.AreNotSame(newInts[0], newInts[1]);
1271    }
1272
1273    [TestMethod]
1274    [TestCategory("Persistence4")]
1275    [TestProperty("Time", "short")]
1276    public void NonDefaultConstructorTest() {
1277      ProtoBufSerializer serializer = new ProtoBufSerializer();
1278      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
1279      try {
1280        serializer.Serialize(c, tempFile);
1281        Assert.Fail("Exception not thrown");
1282      } catch (PersistenceException) {
1283      }
1284    }
1285
1286    [TestMethod]
1287    [TestCategory("Persistence4")]
1288    [TestProperty("Time", "short")]
1289    public void TestSavingException() {
1290      ProtoBufSerializer serializer = new ProtoBufSerializer();
1291      List<int> list = new List<int> { 1, 2, 3 };
1292      serializer.Serialize(list, tempFile);
1293      NonSerializable s = new NonSerializable();
1294      try {
1295        serializer.Serialize(s, tempFile);
1296        Assert.Fail("Exception expected");
1297      } catch (PersistenceException) { }
1298      List<int> newList = (List<int>)serializer.Deserialize(tempFile);
1299      Assert.AreEqual(list[0], newList[0]);
1300      Assert.AreEqual(list[1], newList[1]);
1301    }
1302
1303    [TestMethod]
1304    [TestCategory("Persistence4")]
1305    [TestProperty("Time", "short")]
1306    public void TestTypeStringConversion() {
1307      string name = typeof(List<int>[]).AssemblyQualifiedName;
1308      string shortName =
1309        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
1310      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
1311      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
1312      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
1313    }
1314
1315    [TestMethod]
1316    [TestCategory("Persistence4")]
1317    [TestProperty("Time", "short")]
1318    public void TestHexadecimalPublicKeyToken() {
1319      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
1320      string shortName = "TestClass, TestAssembly";
1321      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
1322      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
1323    }
1324
1325    [TestMethod]
1326    [TestCategory("Persistence4")]
1327    [TestProperty("Time", "short")]
1328    public void InheritanceTest() {
1329      ProtoBufSerializer serializer = new ProtoBufSerializer();
1330      New n = new New();
1331      serializer.Serialize(n, tempFile);
1332      New nn = (New)serializer.Deserialize(tempFile);
1333      Assert.AreEqual(n.Name, nn.Name);
1334      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
1335    }
1336
1337    [StorableClass("B963EF51-12B4-432E-8C54-88F026F9ACE2")]
1338    class Child {
1339      [Storable]
1340      public GrandParent grandParent;
1341    }
1342
1343    [StorableClass("E66E9606-967A-4C35-A361-F6F0D21C064A")]
1344    class Parent {
1345      [Storable]
1346      public Child child;
1347    }
1348
1349    [StorableClass("34D3893A-57AD-4F72-878B-81D6FA3F14A9")]
1350    class GrandParent {
1351      [Storable]
1352      public Parent parent;
1353    }
1354
1355    [TestMethod]
1356    [TestCategory("Persistence4")]
1357    [TestProperty("Time", "short")]
1358    public void InstantiateParentChainReference() {
1359      ProtoBufSerializer serializer = new ProtoBufSerializer();
1360      GrandParent gp = new GrandParent();
1361      gp.parent = new Parent();
1362      gp.parent.child = new Child();
1363      gp.parent.child.grandParent = gp;
1364      Assert.AreSame(gp, gp.parent.child.grandParent);
1365      serializer.Serialize(gp, tempFile);
1366      GrandParent newGp = (GrandParent)serializer.Deserialize(tempFile);
1367      Assert.AreSame(newGp, newGp.parent.child.grandParent);
1368    }
1369
1370    struct TestStruct {
1371      int value;
1372      int PropertyValue { get; set; }
1373      public TestStruct(int value)
1374        : this() {
1375        this.value = value;
1376        PropertyValue = value;
1377      }
1378    }
1379
1380    [TestMethod]
1381    [TestCategory("Persistence4")]
1382    [TestProperty("Time", "short")]
1383    public void StructTest() {
1384      ProtoBufSerializer serializer = new ProtoBufSerializer();
1385      TestStruct s = new TestStruct(10);
1386      serializer.Serialize(s, tempFile);
1387      TestStruct newS = (TestStruct)serializer.Deserialize(tempFile);
1388      Assert.AreEqual(s, newS);
1389    }
1390
1391    [TestMethod]
1392    [TestCategory("Persistence4")]
1393    [TestProperty("Time", "short")]
1394    public void PointTest() {
1395      ProtoBufSerializer serializer = new ProtoBufSerializer();
1396      Point p = new Point(12, 34);
1397      serializer.Serialize(p, tempFile);
1398      Point newP = (Point)serializer.Deserialize(tempFile);
1399      Assert.AreEqual(p, newP);
1400    }
1401
1402    [TestMethod]
1403    [TestCategory("Persistence4")]
1404    [TestProperty("Time", "short")]
1405    public void NullableValueTypes() {
1406      ProtoBufSerializer serializer = new ProtoBufSerializer();
1407      double?[] d = new double?[] { null, 1, 2, 3 };
1408      serializer.Serialize(d, tempFile);
1409      double?[] newD = (double?[])serializer.Deserialize(tempFile);
1410      Assert.AreEqual(d[0], newD[0]);
1411      Assert.AreEqual(d[1], newD[1]);
1412      Assert.AreEqual(d[2], newD[2]);
1413      Assert.AreEqual(d[3], newD[3]);
1414    }
1415
1416    [TestMethod]
1417    [TestCategory("Persistence4")]
1418    [TestProperty("Time", "short")]
1419    public void BitmapTest() {
1420      ProtoBufSerializer serializer = new ProtoBufSerializer();
1421      Icon icon = System.Drawing.SystemIcons.Hand;
1422      Bitmap bitmap = icon.ToBitmap();
1423      serializer.Serialize(bitmap, tempFile);
1424      Bitmap newBitmap = (Bitmap)serializer.Deserialize(tempFile);
1425
1426      Assert.AreEqual(bitmap.Size, newBitmap.Size);
1427      for (int i = 0; i < bitmap.Size.Width; i++)
1428        for (int j = 0; j < bitmap.Size.Height; j++)
1429          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
1430    }
1431
1432    [StorableClass("E846BC49-20F3-4D3F-A3F3-73D4F2DB1C2E")]
1433    private class PersistenceHooks {
1434      [Storable]
1435      public int a;
1436      [Storable]
1437      public int b;
1438      public int sum;
1439      public bool WasSerialized { get; private set; }
1440      [StorableHook(HookType.BeforeSerialization)]
1441      void PreSerializationHook() {
1442        WasSerialized = true;
1443      }
1444      [StorableHook(HookType.AfterDeserialization)]
1445      void PostDeserializationHook() {
1446        sum = a + b;
1447      }
1448    }
1449
1450    [TestMethod]
1451    [TestCategory("Persistence4")]
1452    [TestProperty("Time", "short")]
1453    public void HookTest() {
1454      ProtoBufSerializer serializer = new ProtoBufSerializer();
1455      PersistenceHooks hookTest = new PersistenceHooks();
1456      hookTest.a = 2;
1457      hookTest.b = 5;
1458      Assert.IsFalse(hookTest.WasSerialized);
1459      Assert.AreEqual(hookTest.sum, 0);
1460      serializer.Serialize(hookTest, tempFile);
1461      Assert.IsTrue(hookTest.WasSerialized);
1462      Assert.AreEqual(hookTest.sum, 0);
1463      PersistenceHooks newHookTest = (PersistenceHooks)serializer.Deserialize(tempFile);
1464      Assert.AreEqual(newHookTest.a, hookTest.a);
1465      Assert.AreEqual(newHookTest.b, hookTest.b);
1466      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
1467      Assert.IsFalse(newHookTest.WasSerialized);
1468    }
1469
1470    [StorableClass("A35D71DF-397F-4910-A950-ED6923BE9483")]
1471    private class CustomConstructor {
1472      public string Value = "none";
1473      public CustomConstructor() {
1474        Value = "default";
1475      }
1476      [StorableConstructor]
1477      private CustomConstructor(bool deserializing) {
1478        Assert.IsTrue(deserializing);
1479        Value = "persistence";
1480      }
1481    }
1482
1483    [TestMethod]
1484    [TestCategory("Persistence4")]
1485    [TestProperty("Time", "short")]
1486    public void TestCustomConstructor() {
1487      ProtoBufSerializer serializer = new ProtoBufSerializer();
1488      CustomConstructor cc = new CustomConstructor();
1489      Assert.AreEqual(cc.Value, "default");
1490      serializer.Serialize(cc, tempFile);
1491      CustomConstructor newCC = (CustomConstructor)serializer.Deserialize(tempFile);
1492      Assert.AreEqual(newCC.Value, "persistence");
1493    }
1494
1495    [StorableClass("D276E825-1F35-4BAC-8937-9ABC91D5C316")]
1496    public class ExplodingDefaultConstructor {
1497      public ExplodingDefaultConstructor() {
1498        throw new Exception("this constructor will always fail");
1499      }
1500      public ExplodingDefaultConstructor(string password) {
1501      }
1502    }
1503
1504    [TestMethod]
1505    [TestCategory("Persistence4")]
1506    [TestProperty("Time", "short")]
1507    public void TestConstructorExceptionUnwrapping() {
1508      ProtoBufSerializer serializer = new ProtoBufSerializer();
1509      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
1510      serializer.Serialize(x, tempFile);
1511      try {
1512        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)serializer.Deserialize(tempFile);
1513        Assert.Fail("Exception expected");
1514      } catch (PersistenceException pe) {
1515        Assert.AreEqual(pe.InnerException.Message, "this constructor will always fail");
1516      }
1517    }
1518
1519    [TestMethod]
1520    [TestCategory("Persistence4")]
1521    [TestProperty("Time", "short")]
1522    public void TestStreaming() {
1523      ProtoBufSerializer serializer = new ProtoBufSerializer();
1524      using (MemoryStream stream = new MemoryStream()) {
1525        Root r = InitializeComplexStorable();
1526        serializer.Serialize(r, stream);
1527        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
1528          Root newR = (Root)serializer.Deserialize(stream2);
1529          CompareComplexStorables(r, newR);
1530        }
1531      }
1532    }
1533
1534    [StorableClass("4921031B-CB61-4677-97AD-9236A4CEC200")]
1535    public class HookInheritanceTestBase {
1536      [Storable]
1537      public object a;
1538      public object link;
1539      [StorableHook(HookType.AfterDeserialization)]
1540      private void relink() {
1541        link = a;
1542      }
1543    }
1544
1545    [StorableClass("321CEE0A-5201-4CE2-B135-2343890D96BF")]
1546    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
1547      [Storable]
1548      public object b;
1549      [StorableHook(HookType.AfterDeserialization)]
1550      private void relink() {
1551        Assert.AreSame(a, link);
1552        link = b;
1553      }
1554    }
1555
1556    [TestMethod]
1557    [TestCategory("Persistence4")]
1558    [TestProperty("Time", "short")]
1559    public void TestLinkInheritance() {
1560      ProtoBufSerializer serializer = new ProtoBufSerializer();
1561      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
1562      c.a = new object();
1563      serializer.Serialize(c, tempFile);
1564      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)serializer.Deserialize(tempFile);
1565      Assert.AreSame(c.b, c.link);
1566    }
1567
1568    [StorableClass(StorableClassType.AllFields, "B9AB42E8-1932-425B-B4CF-F31F07EAC599")]
1569    public class AllFieldsStorable {
1570      public int Value1 = 1;
1571      [Storable]
1572      public int Value2 = 2;
1573      public int Value3 { get; private set; }
1574      public int Value4 { get; private set; }
1575      [StorableConstructor]
1576      public AllFieldsStorable(bool isDeserializing) {
1577        if (!isDeserializing) {
1578          Value1 = 12;
1579          Value2 = 23;
1580          Value3 = 34;
1581          Value4 = 56;
1582        }
1583      }
1584    }
1585
1586    [TestMethod]
1587    [TestCategory("Persistence4")]
1588    [TestProperty("Time", "short")]
1589    public void TestStorableClassDiscoveryAllFields() {
1590      ProtoBufSerializer serializer = new ProtoBufSerializer();
1591      AllFieldsStorable afs = new AllFieldsStorable(false);
1592      serializer.Serialize(afs, tempFile);
1593      AllFieldsStorable newAfs = (AllFieldsStorable)serializer.Deserialize(tempFile);
1594      Assert.AreEqual(afs.Value1, newAfs.Value1);
1595      Assert.AreEqual(afs.Value2, newAfs.Value2);
1596      Assert.AreEqual(0, newAfs.Value3);
1597      Assert.AreEqual(0, newAfs.Value4);
1598    }
1599
1600    [StorableClass(StorableClassType.AllProperties, "CB7DC31C-AEF3-4EB8-91CA-248B767E9F92")]
1601    public class AllPropertiesStorable {
1602      public int Value1 = 1;
1603      [Storable]
1604      public int Value2 = 2;
1605      public int Value3 { get; private set; }
1606      public int Value4 { get; private set; }
1607      [StorableConstructor]
1608      public AllPropertiesStorable(bool isDeserializing) {
1609        if (!isDeserializing) {
1610          Value1 = 12;
1611          Value2 = 23;
1612          Value3 = 34;
1613          Value4 = 56;
1614        }
1615      }
1616    }
1617
1618    [TestMethod]
1619    [TestCategory("Persistence4")]
1620    [TestProperty("Time", "short")]
1621    public void TestStorableClassDiscoveryAllProperties() {
1622      ProtoBufSerializer serializer = new ProtoBufSerializer();
1623      AllPropertiesStorable afs = new AllPropertiesStorable(false);
1624      serializer.Serialize(afs, tempFile);
1625      AllPropertiesStorable newAfs = (AllPropertiesStorable)serializer.Deserialize(tempFile);
1626      Assert.AreEqual(1, newAfs.Value1);
1627      Assert.AreEqual(2, newAfs.Value2);
1628      Assert.AreEqual(afs.Value3, newAfs.Value3);
1629      Assert.AreEqual(afs.Value4, newAfs.Value4);
1630
1631    }
1632
1633    [StorableClass(StorableClassType.AllFieldsAndAllProperties, "0AD8D68F-E0FF-4FA8-8A72-1148CD91A2B9")]
1634    public class AllFieldsAndAllPropertiesStorable {
1635      public int Value1 = 1;
1636      [Storable]
1637      public int Value2 = 2;
1638      public int Value3 { get; private set; }
1639      public int Value4 { get; private set; }
1640      [StorableConstructor]
1641      public AllFieldsAndAllPropertiesStorable(bool isDeserializing) {
1642        if (!isDeserializing) {
1643          Value1 = 12;
1644          Value2 = 23;
1645          Value3 = 34;
1646          Value4 = 56;
1647        }
1648      }
1649    }
1650
1651    [TestMethod]
1652    [TestCategory("Persistence4")]
1653    [TestProperty("Time", "short")]
1654    public void TestStorableClassDiscoveryAllFieldsAndAllProperties() {
1655      ProtoBufSerializer serializer = new ProtoBufSerializer();
1656      AllFieldsAndAllPropertiesStorable afs = new AllFieldsAndAllPropertiesStorable(false);
1657      serializer.Serialize(afs, tempFile);
1658      AllFieldsAndAllPropertiesStorable newAfs = (AllFieldsAndAllPropertiesStorable)serializer.Deserialize(tempFile);
1659      Assert.AreEqual(afs.Value1, newAfs.Value1);
1660      Assert.AreEqual(afs.Value2, newAfs.Value2);
1661      Assert.AreEqual(afs.Value3, newAfs.Value3);
1662      Assert.AreEqual(afs.Value4, newAfs.Value4);
1663    }
1664
1665    [StorableClass(StorableClassType.MarkedOnly, "0D94E6D4-64E3-4637-B1EE-DEF2B3F6E2E0")]
1666    public class MarkedOnlyStorable {
1667      public int Value1 = 1;
1668      [Storable]
1669      public int Value2 = 2;
1670      public int Value3 { get; private set; }
1671      public int Value4 { get; private set; }
1672      [StorableConstructor]
1673      public MarkedOnlyStorable(bool isDeserializing) {
1674        if (!isDeserializing) {
1675          Value1 = 12;
1676          Value2 = 23;
1677          Value3 = 34;
1678          Value4 = 56;
1679        }
1680      }
1681    }
1682
1683    [TestMethod]
1684    [TestCategory("Persistence4")]
1685    [TestProperty("Time", "short")]
1686    public void TestStorableClassDiscoveryMarkedOnly() {
1687      ProtoBufSerializer serializer = new ProtoBufSerializer();
1688      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
1689      serializer.Serialize(afs, tempFile);
1690      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)serializer.Deserialize(tempFile);
1691      Assert.AreEqual(1, newAfs.Value1);
1692      Assert.AreEqual(afs.Value2, newAfs.Value2);
1693      Assert.AreEqual(0, newAfs.Value3);
1694      Assert.AreEqual(0, newAfs.Value4);
1695    }
1696
1697    [TestMethod]
1698    [TestCategory("Persistence4")]
1699    [TestProperty("Time", "short")]
1700    public void TestLineEndings() {
1701      ProtoBufSerializer serializer = new ProtoBufSerializer();
1702      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
1703      List<string> lines = new List<string>();
1704      foreach (var br in lineBreaks)
1705        lines.Add("line1" + br + "line2");
1706      serializer.Serialize(lines, tempFile);
1707      List<string> newLines = (List<string>)serializer.Deserialize(tempFile);
1708      Assert.AreEqual(lines.Count, newLines.Count);
1709      for (int i = 0; i < lineBreaks.Count; i++) {
1710        Assert.AreEqual(lines[i], newLines[i]);
1711      }
1712    }
1713
1714    [TestMethod]
1715    [TestCategory("Persistence4")]
1716    [TestProperty("Time", "short")]
1717    public void TestSpecialNumbers() {
1718      ProtoBufSerializer serializer = new ProtoBufSerializer();
1719      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
1720      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
1721      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
1722      Assert.IsTrue(double.IsNaN(specials[2]));
1723      serializer.Serialize(specials, tempFile);
1724      List<double> newSpecials = (List<double>)serializer.Deserialize(tempFile);
1725      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
1726      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
1727      Assert.IsTrue(double.IsNaN(newSpecials[2]));
1728    }
1729
1730    [TestMethod]
1731    [TestCategory("Persistence4")]
1732    [TestProperty("Time", "short")]
1733    public void TestStringSplit() {
1734      string s = "1.2;2.3;3.4;;;4.9";
1735      var l = s.EnumerateSplit(';').ToList();
1736      Assert.AreEqual("1.2", l[0]);
1737      Assert.AreEqual("2.3", l[1]);
1738      Assert.AreEqual("3.4", l[2]);
1739      Assert.AreEqual("4.9", l[3]);
1740    }
1741
1742    private class IdentityComparer<T> : IEqualityComparer<T> {
1743
1744      public bool Equals(T x, T y) {
1745        return x.Equals(y);
1746      }
1747
1748      public int GetHashCode(T obj) {
1749        return obj.GetHashCode();
1750      }
1751    }
1752
1753    [TestMethod]
1754    [TestCategory("Persistence4")]
1755    [TestProperty("Time", "short")]
1756    public void TestHashSetSerializer() {
1757      ProtoBufSerializer serializer = new ProtoBufSerializer();
1758      var hashSets = new List<HashSet<int>>() {
1759        new HashSet<int>(new[] { 1, 2, 3 }),
1760        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1761      };
1762      serializer.Serialize(hashSets, tempFile);
1763      var newHashSets = (List<HashSet<int>>)serializer.Deserialize(tempFile);
1764      Assert.IsTrue(newHashSets[0].Contains(1));
1765      Assert.IsTrue(newHashSets[0].Contains(2));
1766      Assert.IsTrue(newHashSets[0].Contains(3));
1767      Assert.IsTrue(newHashSets[1].Contains(4));
1768      Assert.IsTrue(newHashSets[1].Contains(5));
1769      Assert.IsTrue(newHashSets[1].Contains(6));
1770      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1771      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1772    }
1773
1774    [TestMethod]
1775    [TestCategory("Persistence4")]
1776    [TestProperty("Time", "short")]
1777    public void TestConcreteDictionarySerializer() {
1778      ProtoBufSerializer serializer = new ProtoBufSerializer();
1779      var dictionaries = new List<Dictionary<int, int>>() {
1780        new Dictionary<int, int>(),
1781        new Dictionary<int, int>(new IdentityComparer<int>()),
1782      };
1783      dictionaries[0].Add(1, 1);
1784      dictionaries[0].Add(2, 2);
1785      dictionaries[0].Add(3, 3);
1786      dictionaries[1].Add(4, 4);
1787      dictionaries[1].Add(5, 5);
1788      dictionaries[1].Add(6, 6);
1789      serializer.Serialize(dictionaries, tempFile);
1790      var newDictionaries = (List<Dictionary<int, int>>)serializer.Deserialize(tempFile);
1791      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1792      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1793      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1794      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1795      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1796      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1797      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1798      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1799      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1800      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1801      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1802      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1803      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1804      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1805    }
1806
1807    [StorableClass("A9B0D7FB-0CAF-4DD7-9045-EA136F9176F7")]
1808    public class ReadOnlyFail {
1809      [Storable]
1810      public string ReadOnly {
1811        get { return "fail"; }
1812      }
1813    }
1814
1815    [TestMethod]
1816    [TestCategory("Persistence4")]
1817    [TestProperty("Time", "short")]
1818    public void TestReadOnlyFail() {
1819      ProtoBufSerializer serializer = new ProtoBufSerializer();
1820      try {
1821        serializer.Serialize(new ReadOnlyFail(), tempFile);
1822        Assert.Fail("Exception expected");
1823      } catch (PersistenceException) {
1824      } catch {
1825        Assert.Fail("PersistenceException expected");
1826      }
1827    }
1828
1829
1830    [StorableClass("2C9CC576-6823-4784-817B-37C8AF0B1C29")]
1831    public class WriteOnlyFail {
1832      [Storable]
1833      public string WriteOnly {
1834        set { throw new InvalidOperationException("this property should never be set."); }
1835      }
1836    }
1837
1838    [TestMethod]
1839    [TestCategory("Persistence4")]
1840    [TestProperty("Time", "short")]
1841    public void TestWriteOnlyFail() {
1842      ProtoBufSerializer serializer = new ProtoBufSerializer();
1843      try {
1844        serializer.Serialize(new WriteOnlyFail(), tempFile);
1845        Assert.Fail("Exception expected");
1846      } catch (PersistenceException) {
1847      } catch {
1848        Assert.Fail("PersistenceException expected.");
1849      }
1850    }
1851
1852    [StorableClass("8052D9E3-6DDD-4AE1-9B5B-67C6D5436512")]
1853    public class OneWayTest {
1854      public OneWayTest() { this.value = "default"; }
1855      public string value;
1856      [Storable(AllowOneWay = true)]
1857      public string ReadOnly {
1858        get { return "ReadOnly"; }
1859      }
1860      [Storable(AllowOneWay = true)]
1861      public string WriteOnly {
1862        set { this.value = value; }
1863      }
1864    }
1865
1866    //TODO
1867    /* [TestMethod]
1868     [TestCategory("Persistence4")]
1869     [TestProperty("Time", "short")]
1870     public void TestTypeCacheExport() {
1871       ProtoBufSerializer serializer = new ProtoBufSerializer();
1872       var test = new List<List<int>>();
1873       test.Add(new List<int>() { 1, 2, 3 });
1874       IEnumerable<Type> types;
1875       using (var stream = new MemoryStream()) {
1876         XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1877       }
1878       List<Type> t = new List<Type>(types);
1879       // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1880       Assert.IsTrue(t.Contains(typeof(List<int>)));
1881       Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1882       Assert.AreEqual(t.Count, 2);
1883     }*/
1884
1885    [TestMethod]
1886    [TestCategory("Persistence4")]
1887    [TestProperty("Time", "short")]
1888    public void TupleTest() {
1889      var t1 = Tuple.Create(1);
1890      var t2 = Tuple.Create('1', "2");
1891      var t3 = Tuple.Create(3.0, 3f, 5);
1892      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1893      var tuple = Tuple.Create(t1, t2, t3, t4);
1894      SerializeNew(tuple);
1895      var newTuple = DeserializeNew();
1896      Assert.AreEqual(tuple, newTuple);
1897    }
1898
1899    [TestMethod]
1900    [TestCategory("Persistence4")]
1901    [TestProperty("Time", "short")]
1902    public void FontTest() {
1903      ProtoBufSerializer serializer = new ProtoBufSerializer();
1904      List<Font> fonts = new List<Font>() {
1905        new Font(FontFamily.GenericSansSerif, 12),
1906        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
1907        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
1908        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
1909      };
1910      serializer.Serialize(fonts, tempFile);
1911      var newFonts = (List<Font>)serializer.Deserialize(tempFile);
1912      Assert.AreEqual(fonts[0], newFonts[0]);
1913      Assert.AreEqual(fonts[1], newFonts[1]);
1914      Assert.AreEqual(fonts[2], newFonts[2]);
1915      Assert.AreEqual(fonts[3], newFonts[3]);
1916    }
1917
1918    [TestMethod]
1919    [TestCategory("Persistence4")]
1920    [TestProperty("Time", "medium")]
1921    public void ConcurrencyTest() {
1922      ProtoBufSerializer serializer = new ProtoBufSerializer();
1923      int n = 20;
1924      Task[] tasks = new Task[n];
1925      for (int i = 0; i < n; i++) {
1926        tasks[i] = Task.Factory.StartNew((idx) => {
1927          byte[] data;
1928          using (var stream = new MemoryStream()) {
1929            serializer.Serialize(new GeneticAlgorithm(), stream);
1930            data = stream.ToArray();
1931          }
1932        }, i);
1933      }
1934      Task.WaitAll(tasks);
1935    }
1936
1937    [TestMethod]
1938    [TestCategory("Persistence4")]
1939    [TestProperty("Time", "medium")]
1940    public void ConcurrentBitmapTest() {
1941      ProtoBufSerializer serializer = new ProtoBufSerializer();
1942      Bitmap b = new Bitmap(300, 300);
1943      System.Random r = new System.Random();
1944      for (int x = 0; x < b.Height; x++) {
1945        for (int y = 0; y < b.Width; y++) {
1946          b.SetPixel(x, y, Color.FromArgb(r.Next()));
1947        }
1948      }
1949      Task[] tasks = new Task[20];
1950      byte[][] datas = new byte[tasks.Length][];
1951      for (int i = 0; i < tasks.Length; i++) {
1952        tasks[i] = Task.Factory.StartNew((idx) => {
1953          using (var stream = new MemoryStream()) {
1954            serializer.Serialize(b, stream);
1955            datas[(int)idx] = stream.ToArray();
1956          }
1957        }, i);
1958      }
1959      Task.WaitAll(tasks);
1960    }
1961
1962    public class G<T, T2> {
1963      public class S { }
1964      public class S2<T3, T4> { }
1965    }
1966
1967
1968    [TestMethod]
1969    [TestCategory("Persistence4")]
1970    [TestProperty("Time", "short")]
1971    public void TestSpecialCharacters() {
1972      ProtoBufSerializer serializer = new ProtoBufSerializer();
1973      var s = "abc" + "\x15" + "def";
1974      serializer.Serialize(s, tempFile);
1975      var newS = serializer.Deserialize(tempFile);
1976      Assert.AreEqual(s, newS);
1977    }
1978
1979    [TestMethod]
1980    [TestCategory("Persistence4")]
1981    [TestProperty("Time", "short")]
1982    public void TestByteArray() {
1983      ProtoBufSerializer serializer = new ProtoBufSerializer();
1984      var b = new byte[3];
1985      b[0] = 0;
1986      b[1] = 200;
1987      b[2] = byte.MaxValue;
1988      serializer.Serialize(b, tempFile);
1989      var newB = (byte[])serializer.Deserialize(tempFile);
1990      CollectionAssert.AreEqual(b, newB);
1991    }
1992
1993    [TestMethod]
1994    [TestCategory("Persistence4")]
1995    [TestProperty("Time", "short")]
1996    public void TestOptionalNumberEnumerable() {
1997      ProtoBufSerializer serializer = new ProtoBufSerializer();
1998      var values = new List<double?> { 0, null, double.NaN, double.PositiveInfinity, double.MaxValue, 1 };
1999      serializer.Serialize(values, tempFile);
2000      var newValues = (List<double?>)serializer.Deserialize(tempFile);
2001      CollectionAssert.AreEqual(values, newValues);
2002    }
2003
2004    [TestMethod]
2005    [TestCategory("Persistence4")]
2006    [TestProperty("Time", "short")]
2007    public void TestOptionalDateTimeEnumerable() {
2008      ProtoBufSerializer serializer = new ProtoBufSerializer();
2009      var values = new List<DateTime?> { DateTime.MinValue, null, DateTime.Now, DateTime.Now.Add(TimeSpan.FromDays(1)),
2010        DateTime.ParseExact("10.09.2014 12:21", "dd.MM.yyyy hh:mm", CultureInfo.InvariantCulture), DateTime.MaxValue};
2011      serializer.Serialize(values, tempFile);
2012      var newValues = (List<DateTime?>)serializer.Deserialize(tempFile);
2013      CollectionAssert.AreEqual(values, newValues);
2014    }
2015
2016    [TestMethod]
2017    [TestCategory("Persistence4")]
2018    [TestProperty("Time", "short")]
2019    public void TestStringEnumerable() {
2020      ProtoBufSerializer serializer = new ProtoBufSerializer();
2021      var values = new List<string> { "", null, "s", "string", string.Empty, "123", "<![CDATA[nice]]>", "<![CDATA[nasty unterminated" };
2022      serializer.Serialize(values, tempFile);
2023      var newValues = (List<String>)serializer.Deserialize(tempFile);
2024      CollectionAssert.AreEqual(values, newValues);
2025    }
2026
2027    [TestMethod]
2028    [TestCategory("Persistence4")]
2029    [TestProperty("Time", "short")]
2030    public void TestUnicodeCharArray() {
2031      ProtoBufSerializer serializer = new ProtoBufSerializer();
2032      var s = Encoding.UTF8.GetChars(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
2033      serializer.Serialize(s, tempFile);
2034      var newS = (char[])serializer.Deserialize(tempFile);
2035      CollectionAssert.AreEqual(s, newS);
2036    }
2037
2038    [TestMethod]
2039    [TestCategory("Persistence4")]
2040    [TestProperty("Time", "short")]
2041    public void TestUnicode() {
2042      ProtoBufSerializer serializer = new ProtoBufSerializer();
2043      var s = Encoding.UTF8.GetString(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
2044      serializer.Serialize(s, tempFile);
2045      var newS = serializer.Deserialize(tempFile);
2046      Assert.AreEqual(s, newS);
2047    }
2048
2049    [TestMethod]
2050    [TestCategory("Persistence4")]
2051    [TestProperty("Time", "short")]
2052    public void TestQueue() {
2053      ProtoBufSerializer serializer = new ProtoBufSerializer();
2054      var q = new Queue<int>(new[] { 1, 2, 3, 4, 0 });
2055      serializer.Serialize(q, tempFile);
2056      var newQ = (Queue<int>)serializer.Deserialize(tempFile);
2057      CollectionAssert.AreEqual(q, newQ);
2058    }
2059    #endregion
2060
2061    [StorableClass("6075F1E8-948A-4AD8-8F5A-942B777852EC")]
2062    public class A {
2063      [Storable]
2064      public B B { get; set; }
2065
2066      [Storable] public int i;
2067    }
2068    [StorableClass("6075F1E8-948A-4AD8-8F5A-942B777852EC")]
2069    public class B {
2070      [Storable]
2071      public A A { get; set; }
2072
2073      [StorableHook(HookType.AfterDeserialization)]
2074      void PostDeserializationHook() {
2075        //Assert.AreEqual(3, A.i);
2076      }
2077    }
2078
2079    [TestMethod]
2080    [TestCategory("Persistence4")]
2081    [TestProperty("Time", "short")]
2082    public void TestCyclicReferencesWithTuple() {
2083      var test = new Func<A>(() => {
2084        var a = new A { i = 4 };
2085        var b = new B { A = a };
2086        a.B = b;
2087        return a;
2088      });
2089
2090      //ProtoBufSerializer serializer = new ProtoBufSerializer();
2091      //serializer.Serialize(test(), tempFile);
2092      //object o = serializer.Deserialize(tempFile);
2093      //A result = (A)o;
2094
2095      XmlGenerator.Serialize(test(), tempFile);
2096      object o = XmlParser.Deserialize(tempFile);
2097
2098      string msg = Profile(test);
2099      Console.WriteLine(msg);
2100    }
2101
2102    [TestMethod]
2103    [TestCategory("Persistence4")]
2104    [TestProperty("Time", "short")]
2105    public void TestGASerializeDeserializeExecute() {
2106      var test = new Func<GeneticAlgorithm>(() => {
2107        var ga = new GeneticAlgorithm();
2108        ga.Problem = new SingleObjectiveTestFunctionProblem();
2109        ga.MaximumGenerations.Value = 100;
2110        ga.SetSeedRandomly.Value = false;
2111        return ga;
2112      });
2113      ProtoBufSerializer serializer = new ProtoBufSerializer();
2114      serializer.Serialize(test(), tempFile);
2115      object o = serializer.Deserialize(tempFile);
2116      GeneticAlgorithm result = (GeneticAlgorithm)o;
2117      SamplesUtils.RunAlgorithm(result);
2118      GeneticAlgorithm original = test();
2119      SamplesUtils.RunAlgorithm(original);
2120      //Assert.AreEqual(original.Results[""], result);
2121
2122      //string msg = Profile(test);
2123      //Console.WriteLine(msg);
2124    }
2125    [TestMethod]
2126    [TestCategory("Persistence4")]
2127    [TestProperty("Time", "short")]
2128    public void TestLoadingSamples() {
2129      var path = @"D:\Dev\HL\branches\PersistenceOverhaul\HeuristicLab.Optimizer\3.3\Documents";
2130      var serializer = new ProtoBufSerializer();
2131      foreach (var fileName in Directory.EnumerateFiles(path, "*.hl")) {
2132        var original = XmlParser.Deserialize(fileName);
2133        serializer.Serialize(original, fileName + ".proto");
2134        // var newVersion = serializer.Deserialize(fileName + ".proto");
2135        var p = Profile(() => original);
2136        Console.WriteLine(p);
2137      }
2138    }
2139  }
2140}
Note: See TracBrowser for help on using the repository browser.