Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15034 was 15034, checked in by gkronber, 7 years ago

#2520: improved conversions

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