Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2520 added unit tests and fixed all test cases for old persistence

File size: 84.4 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.Common;
35using HeuristicLab.Core;
36using HeuristicLab.Data;
37using HeuristicLab.Persistence;
38using HeuristicLab.Persistence.Auxiliary;
39using HeuristicLab.Persistence.Core;
40using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
41using HeuristicLab.Persistence.Default.DebugString;
42using HeuristicLab.Persistence.Default.Xml;
43using HeuristicLab.Persistence.Tests;
44using HeuristicLab.Problems.TestFunctions;
45using HeuristicLab.Tests;
46using Microsoft.VisualStudio.TestTools.UnitTesting;
47
48namespace HeuristicLab.PersistenceNew.Tests {
49  public static class EnumerableTimeSpanExtensions {
50    public static TimeSpan Average(this IEnumerable<TimeSpan> span) {
51      var avg = (long)Math.Round(span.Select(x => x.Ticks).Average());
52      return new TimeSpan(avg);
53    }
54  }
55
56  #region Test Classes
57  [StorableType("7D9672BD-703D-42BB-9080-9929885D4580")]
58  public class NumberTest {
59    [Storable]
60    private bool _bool = true;
61    [Storable]
62    private byte _byte = 0xFF;
63    [Storable]
64    private sbyte _sbyte = 0xF;
65    [Storable]
66    private short _short = -123;
67    [Storable]
68    private ushort _ushort = 123;
69    [Storable]
70    private int _int = -123;
71    [Storable]
72    private uint _uint = 123;
73    [Storable]
74    private long _long = 123456;
75    [Storable]
76    private ulong _ulong = 123456;
77    public override bool Equals(object obj) {
78      NumberTest nt = obj as NumberTest;
79      if (nt == null)
80        throw new NotSupportedException();
81      return
82        nt._bool == _bool &&
83        nt._byte == _byte &&
84        nt._sbyte == _sbyte &&
85        nt._short == _short &&
86        nt._ushort == _ushort &&
87        nt._int == _int &&
88        nt._uint == _uint &&
89        nt._long == _long &&
90        nt._ulong == _ulong;
91    }
92    public override int GetHashCode() {
93      return
94        _bool.GetHashCode() ^
95        _byte.GetHashCode() ^
96        _sbyte.GetHashCode() ^
97        _short.GetHashCode() ^
98        _short.GetHashCode() ^
99        _int.GetHashCode() ^
100        _uint.GetHashCode() ^
101        _long.GetHashCode() ^
102        _ulong.GetHashCode();
103    }
104  }
105
106  [StorableType("EEB19599-D5AC-48ED-A56B-CF213DFAF2E4")]
107  public class NonDefaultConstructorClass {
108    [Storable]
109    int value;
110    public NonDefaultConstructorClass(int value) {
111      this.value = value;
112    }
113  }
114
115  [StorableType("EE43FE7A-6D07-4D52-9338-C21B3485F82A")]
116  public class IntWrapper {
117
118    [Storable]
119    public int Value;
120
121    private IntWrapper() { }
122
123    public IntWrapper(int value) {
124      this.Value = value;
125    }
126
127    public override bool Equals(object obj) {
128      if (obj as IntWrapper == null)
129        return false;
130      return Value.Equals(((IntWrapper)obj).Value);
131    }
132    public override int GetHashCode() {
133      return Value.GetHashCode();
134    }
135
136  }
137
138  [StorableType("00A8E48E-8E8A-443C-A327-9F6ACCBE7E80")]
139  public class PrimitivesTest : NumberTest {
140    [Storable]
141    private char c = 'e';
142    [Storable]
143    private long[,] _long_array =
144      new long[,] { { 123, 456, }, { 789, 123 } };
145    [Storable]
146    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
147    [Storable]
148    private object o = new object();
149    public override bool Equals(object obj) {
150      PrimitivesTest pt = obj as PrimitivesTest;
151      if (pt == null)
152        throw new NotSupportedException();
153      return base.Equals(obj) &&
154        c == pt.c &&
155        _long_array == pt._long_array &&
156        list == pt.list &&
157        o == pt.o;
158    }
159    public override int GetHashCode() {
160      return base.GetHashCode() ^
161        c.GetHashCode() ^
162        _long_array.GetHashCode() ^
163        list.GetHashCode() ^
164        o.GetHashCode();
165    }
166  }
167
168  [StorableType("c15e3ac3-2681-48a1-9171-d97321cd60bb")]
169  public enum TestEnum { va1, va2, va3, va8 };
170
171  [StorableType("26BA37F6-926D-4665-A10A-1F39E1CF6468")]
172  public class RootBase {
173    [Storable]
174    private string baseString = "   Serial  ";
175    [Storable]
176    public TestEnum myEnum = TestEnum.va3;
177    public override bool Equals(object obj) {
178      RootBase rb = obj as RootBase;
179      if (rb == null)
180        throw new NotSupportedException();
181      return baseString == rb.baseString &&
182        myEnum == rb.myEnum;
183    }
184    public override int GetHashCode() {
185      return baseString.GetHashCode() ^
186        myEnum.GetHashCode();
187    }
188  }
189
190  [StorableType("F6BCB436-B5F2-40F6-8E2F-7A018CD1CBA0")]
191  public class Root : RootBase {
192    [Storable]
193    public Stack<int> intStack = new Stack<int>();
194    [Storable]
195    public int[] i = new[] { 3, 4, 5, 6 };
196    [Storable(Name = "Test String")]
197    public string s;
198    [Storable]
199    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
200    [Storable]
201    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
202    [Storable]
203    public Custom c;
204    [Storable]
205    public List<Root> selfReferences;
206    [Storable]
207    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
208    [Storable]
209    public bool boolean = true;
210    [Storable]
211    public DateTime dateTime;
212    [Storable]
213    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
214    [Storable]
215    public Dictionary<string, int> dict = new Dictionary<string, int>();
216    [Storable(DefaultValue = "default")]
217    public string uninitialized;
218  }
219
220  [StorableType("a6bd45c2-bf18-47d7-9f66-c130222f2f00")]
221  public enum SimpleEnum { one, two, three }
222  [StorableType("b5c8285e-5c1b-457e-a5a3-e25eb588c283")]
223  public enum ComplexEnum { one = 1, two = 2, three = 3 }
224  [FlagsAttribute]
225  [StorableType("c2ee7205-0a3a-443a-87d6-68568c4f4153")]
226  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
227
228  [StorableType("2F6326ED-023A-415F-B5C7-9F9241940D05")]
229  public class EnumTest {
230    [Storable]
231    public SimpleEnum simpleEnum = SimpleEnum.one;
232    [Storable]
233    public ComplexEnum complexEnum = (ComplexEnum)2;
234    [Storable]
235    public TrickyEnum trickyEnum = (TrickyEnum)15;
236  }
237
238  [StorableType("92365E2A-1184-4280-B763-4853C7ADF3E3")]
239  public class Custom {
240    [Storable]
241    public int i;
242    [Storable]
243    public Root r;
244    [Storable]
245    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
246  }
247
248  [StorableType("7CF19EBC-1EC4-4FBE-BCA9-DA48E3CFE30D")]
249  public class Manager {
250
251    public DateTime lastLoadTime;
252    [Storable]
253    private DateTime lastLoadTimePersistence {
254      get { return lastLoadTime; }
255      set { lastLoadTime = DateTime.Now; }
256    }
257    [Storable]
258    public double? dbl;
259  }
260
261  [StorableType("9092C705-F5E9-4BA9-9750-4357DB29AABF")]
262  public class C {
263    [Storable]
264    public C[][] allCs;
265    [Storable]
266    public KeyValuePair<List<C>, C> kvpList;
267  }
268
269  [StorableType("6494ee1d-877b-4e78-83df-f3f55a77b9b4")]
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      public TestStruct(int value)
1384        : this() {
1385        this.value = value;
1386        PropertyValue = value;
1387      }
1388    }
1389
1390    [TestMethod]
1391    [TestCategory("Persistence4")]
1392    [TestProperty("Time", "short")]
1393    public void StructTest() {
1394      ProtoBufSerializer serializer = new ProtoBufSerializer();
1395      TestStruct s = new TestStruct(10);
1396      serializer.Serialize(s, tempFile);
1397      TestStruct newS = (TestStruct)serializer.Deserialize(tempFile);
1398      Assert.AreEqual(s, newS);
1399    }
1400
1401    [TestMethod]
1402    [TestCategory("Persistence4")]
1403    [TestProperty("Time", "short")]
1404    public void PointTest() {
1405      ProtoBufSerializer serializer = new ProtoBufSerializer();
1406      Point p = new Point(12, 34);
1407      serializer.Serialize(p, tempFile);
1408      Point newP = (Point)serializer.Deserialize(tempFile);
1409      Assert.AreEqual(p, newP);
1410    }
1411
1412    [TestMethod]
1413    [TestCategory("Persistence4")]
1414    [TestProperty("Time", "short")]
1415    public void NullableValueTypes() {
1416      ProtoBufSerializer serializer = new ProtoBufSerializer();
1417      double?[] d = new double?[] { null, 1, 2, 3 };
1418      serializer.Serialize(d, tempFile);
1419      double?[] newD = (double?[])serializer.Deserialize(tempFile);
1420      Assert.AreEqual(d[0], newD[0]);
1421      Assert.AreEqual(d[1], newD[1]);
1422      Assert.AreEqual(d[2], newD[2]);
1423      Assert.AreEqual(d[3], newD[3]);
1424    }
1425
1426    [TestMethod]
1427    [TestCategory("Persistence4")]
1428    [TestProperty("Time", "short")]
1429    public void BitmapTest() {
1430      ProtoBufSerializer serializer = new ProtoBufSerializer();
1431      Icon icon = System.Drawing.SystemIcons.Hand;
1432      Bitmap bitmap = icon.ToBitmap();
1433      serializer.Serialize(bitmap, tempFile);
1434      Bitmap newBitmap = (Bitmap)serializer.Deserialize(tempFile);
1435
1436      Assert.AreEqual(bitmap.Size, newBitmap.Size);
1437      for (int i = 0; i < bitmap.Size.Width; i++)
1438        for (int j = 0; j < bitmap.Size.Height; j++)
1439          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
1440    }
1441
1442    [StorableType("E846BC49-20F3-4D3F-A3F3-73D4F2DB1C2E")]
1443    private class PersistenceHooks {
1444      [Storable]
1445      public int a;
1446      [Storable]
1447      public int b;
1448      public int sum;
1449      public bool WasSerialized { get; private set; }
1450      [StorableHook(HookType.BeforeSerialization)]
1451      void PreSerializationHook() {
1452        WasSerialized = true;
1453      }
1454      [StorableHook(HookType.AfterDeserialization)]
1455      void PostDeserializationHook() {
1456        sum = a + b;
1457      }
1458    }
1459
1460    [TestMethod]
1461    [TestCategory("Persistence4")]
1462    [TestProperty("Time", "short")]
1463    public void HookTest() {
1464      ProtoBufSerializer serializer = new ProtoBufSerializer();
1465      PersistenceHooks hookTest = new PersistenceHooks();
1466      hookTest.a = 2;
1467      hookTest.b = 5;
1468      Assert.IsFalse(hookTest.WasSerialized);
1469      Assert.AreEqual(hookTest.sum, 0);
1470      serializer.Serialize(hookTest, tempFile);
1471      Assert.IsTrue(hookTest.WasSerialized);
1472      Assert.AreEqual(hookTest.sum, 0);
1473      PersistenceHooks newHookTest = (PersistenceHooks)serializer.Deserialize(tempFile);
1474      Assert.AreEqual(newHookTest.a, hookTest.a);
1475      Assert.AreEqual(newHookTest.b, hookTest.b);
1476      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
1477      Assert.IsFalse(newHookTest.WasSerialized);
1478    }
1479
1480    [StorableType("A35D71DF-397F-4910-A950-ED6923BE9483")]
1481    private class CustomConstructor {
1482      public string Value = "none";
1483      public CustomConstructor() {
1484        Value = "default";
1485      }
1486      [StorableConstructor]
1487      private CustomConstructor(bool deserializing) {
1488        Assert.IsTrue(deserializing);
1489        Value = "persistence";
1490      }
1491    }
1492
1493    [TestMethod]
1494    [TestCategory("Persistence4")]
1495    [TestProperty("Time", "short")]
1496    public void TestCustomConstructor() {
1497      ProtoBufSerializer serializer = new ProtoBufSerializer();
1498      CustomConstructor cc = new CustomConstructor();
1499      Assert.AreEqual(cc.Value, "default");
1500      serializer.Serialize(cc, tempFile);
1501      CustomConstructor newCC = (CustomConstructor)serializer.Deserialize(tempFile);
1502      Assert.AreEqual(newCC.Value, "persistence");
1503    }
1504
1505    [StorableType("D276E825-1F35-4BAC-8937-9ABC91D5C316")]
1506    public class ExplodingDefaultConstructor {
1507      public ExplodingDefaultConstructor() {
1508        throw new Exception("this constructor will always fail");
1509      }
1510      public ExplodingDefaultConstructor(string password) {
1511      }
1512    }
1513
1514    [TestMethod]
1515    [TestCategory("Persistence4")]
1516    [TestProperty("Time", "short")]
1517    public void TestConstructorExceptionUnwrapping() {
1518      ProtoBufSerializer serializer = new ProtoBufSerializer();
1519      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
1520      serializer.Serialize(x, tempFile);
1521      try {
1522        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)serializer.Deserialize(tempFile);
1523        Assert.Fail("Exception expected");
1524      } catch (PersistenceException pe) {
1525        Assert.AreEqual(pe.InnerException.Message, "this constructor will always fail");
1526      }
1527    }
1528
1529    [TestMethod]
1530    [TestCategory("Persistence4")]
1531    [TestProperty("Time", "short")]
1532    public void TestStreaming() {
1533      ProtoBufSerializer serializer = new ProtoBufSerializer();
1534      using (MemoryStream stream = new MemoryStream()) {
1535        Root r = InitializeComplexStorable();
1536        serializer.Serialize(r, stream);
1537        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
1538          Root newR = (Root)serializer.Deserialize(stream2);
1539          CompareComplexStorables(r, newR);
1540        }
1541      }
1542    }
1543
1544    [StorableType("4921031B-CB61-4677-97AD-9236A4CEC200")]
1545    public class HookInheritanceTestBase {
1546      [Storable]
1547      public object a;
1548      public object link;
1549      [StorableHook(HookType.AfterDeserialization)]
1550      private void relink() {
1551        link = a;
1552      }
1553    }
1554
1555    [StorableType("321CEE0A-5201-4CE2-B135-2343890D96BF")]
1556    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
1557      [Storable]
1558      public object b;
1559      [StorableHook(HookType.AfterDeserialization)]
1560      private void relink() {
1561        Assert.AreSame(a, link);
1562        link = b;
1563      }
1564    }
1565
1566    [TestMethod]
1567    [TestCategory("Persistence4")]
1568    [TestProperty("Time", "short")]
1569    public void TestLinkInheritance() {
1570      ProtoBufSerializer serializer = new ProtoBufSerializer();
1571      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
1572      c.a = new object();
1573      serializer.Serialize(c, tempFile);
1574      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)serializer.Deserialize(tempFile);
1575      Assert.AreSame(c.b, c.link);
1576    }
1577
1578    [StorableType(StorableMemberSelection.AllFields, "B9AB42E8-1932-425B-B4CF-F31F07EAC599")]
1579    public class AllFieldsStorable {
1580      public int Value1 = 1;
1581      [Storable]
1582      public int Value2 = 2;
1583      public int Value3 { get; private set; }
1584      public int Value4 { get; private set; }
1585      [StorableConstructor]
1586      public AllFieldsStorable(bool isDeserializing) {
1587        if (!isDeserializing) {
1588          Value1 = 12;
1589          Value2 = 23;
1590          Value3 = 34;
1591          Value4 = 56;
1592        }
1593      }
1594    }
1595
1596    [TestMethod]
1597    [TestCategory("Persistence4")]
1598    [TestProperty("Time", "short")]
1599    public void TestStorableTypeDiscoveryAllFields() {
1600      ProtoBufSerializer serializer = new ProtoBufSerializer();
1601      AllFieldsStorable afs = new AllFieldsStorable(false);
1602      serializer.Serialize(afs, tempFile);
1603      AllFieldsStorable newAfs = (AllFieldsStorable)serializer.Deserialize(tempFile);
1604      Assert.AreEqual(afs.Value1, newAfs.Value1);
1605      Assert.AreEqual(afs.Value2, newAfs.Value2);
1606      Assert.AreEqual(0, newAfs.Value3);
1607      Assert.AreEqual(0, newAfs.Value4);
1608    }
1609
1610    [StorableType(StorableMemberSelection.AllProperties, "CB7DC31C-AEF3-4EB8-91CA-248B767E9F92")]
1611    public class AllPropertiesStorable {
1612      public int Value1 = 1;
1613      [Storable]
1614      public int Value2 = 2;
1615      public int Value3 { get; private set; }
1616      public int Value4 { get; private set; }
1617      [StorableConstructor]
1618      public AllPropertiesStorable(bool isDeserializing) {
1619        if (!isDeserializing) {
1620          Value1 = 12;
1621          Value2 = 23;
1622          Value3 = 34;
1623          Value4 = 56;
1624        }
1625      }
1626    }
1627
1628    [TestMethod]
1629    [TestCategory("Persistence4")]
1630    [TestProperty("Time", "short")]
1631    public void TestStorableTypeDiscoveryAllProperties() {
1632      ProtoBufSerializer serializer = new ProtoBufSerializer();
1633      AllPropertiesStorable afs = new AllPropertiesStorable(false);
1634      serializer.Serialize(afs, tempFile);
1635      AllPropertiesStorable newAfs = (AllPropertiesStorable)serializer.Deserialize(tempFile);
1636      Assert.AreEqual(1, newAfs.Value1);
1637      Assert.AreEqual(2, newAfs.Value2);
1638      Assert.AreEqual(afs.Value3, newAfs.Value3);
1639      Assert.AreEqual(afs.Value4, newAfs.Value4);
1640
1641    }
1642
1643    [StorableType(StorableMemberSelection.AllFieldsAndAllProperties, "0AD8D68F-E0FF-4FA8-8A72-1148CD91A2B9")]
1644    public class AllFieldsAndAllPropertiesStorable {
1645      public int Value1 = 1;
1646      [Storable]
1647      public int Value2 = 2;
1648      public int Value3 { get; private set; }
1649      public int Value4 { get; private set; }
1650      [StorableConstructor]
1651      public AllFieldsAndAllPropertiesStorable(bool isDeserializing) {
1652        if (!isDeserializing) {
1653          Value1 = 12;
1654          Value2 = 23;
1655          Value3 = 34;
1656          Value4 = 56;
1657        }
1658      }
1659    }
1660
1661    [TestMethod]
1662    [TestCategory("Persistence4")]
1663    [TestProperty("Time", "short")]
1664    public void TestStorableTypeDiscoveryAllFieldsAndAllProperties() {
1665      ProtoBufSerializer serializer = new ProtoBufSerializer();
1666      AllFieldsAndAllPropertiesStorable afs = new AllFieldsAndAllPropertiesStorable(false);
1667      serializer.Serialize(afs, tempFile);
1668      AllFieldsAndAllPropertiesStorable newAfs = (AllFieldsAndAllPropertiesStorable)serializer.Deserialize(tempFile);
1669      Assert.AreEqual(afs.Value1, newAfs.Value1);
1670      Assert.AreEqual(afs.Value2, newAfs.Value2);
1671      Assert.AreEqual(afs.Value3, newAfs.Value3);
1672      Assert.AreEqual(afs.Value4, newAfs.Value4);
1673    }
1674
1675    [StorableType(StorableMemberSelection.MarkedOnly, "0D94E6D4-64E3-4637-B1EE-DEF2B3F6E2E0")]
1676    public class MarkedOnlyStorable {
1677      public int Value1 = 1;
1678      [Storable]
1679      public int Value2 = 2;
1680      public int Value3 { get; private set; }
1681      public int Value4 { get; private set; }
1682      [StorableConstructor]
1683      public MarkedOnlyStorable(bool isDeserializing) {
1684        if (!isDeserializing) {
1685          Value1 = 12;
1686          Value2 = 23;
1687          Value3 = 34;
1688          Value4 = 56;
1689        }
1690      }
1691    }
1692
1693    [TestMethod]
1694    [TestCategory("Persistence4")]
1695    [TestProperty("Time", "short")]
1696    public void TestStorableTypeDiscoveryMarkedOnly() {
1697      ProtoBufSerializer serializer = new ProtoBufSerializer();
1698      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
1699      serializer.Serialize(afs, tempFile);
1700      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)serializer.Deserialize(tempFile);
1701      Assert.AreEqual(1, newAfs.Value1);
1702      Assert.AreEqual(afs.Value2, newAfs.Value2);
1703      Assert.AreEqual(0, newAfs.Value3);
1704      Assert.AreEqual(0, newAfs.Value4);
1705    }
1706
1707    [TestMethod]
1708    [TestCategory("Persistence4")]
1709    [TestProperty("Time", "short")]
1710    public void TestLineEndings() {
1711      ProtoBufSerializer serializer = new ProtoBufSerializer();
1712      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
1713      List<string> lines = new List<string>();
1714      foreach (var br in lineBreaks)
1715        lines.Add("line1" + br + "line2");
1716      serializer.Serialize(lines, tempFile);
1717      List<string> newLines = (List<string>)serializer.Deserialize(tempFile);
1718      Assert.AreEqual(lines.Count, newLines.Count);
1719      for (int i = 0; i < lineBreaks.Count; i++) {
1720        Assert.AreEqual(lines[i], newLines[i]);
1721      }
1722    }
1723
1724    [TestMethod]
1725    [TestCategory("Persistence4")]
1726    [TestProperty("Time", "short")]
1727    public void TestSpecialNumbers() {
1728      ProtoBufSerializer serializer = new ProtoBufSerializer();
1729      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
1730      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
1731      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
1732      Assert.IsTrue(double.IsNaN(specials[2]));
1733      serializer.Serialize(specials, tempFile);
1734      List<double> newSpecials = (List<double>)serializer.Deserialize(tempFile);
1735      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
1736      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
1737      Assert.IsTrue(double.IsNaN(newSpecials[2]));
1738    }
1739
1740    [TestMethod]
1741    [TestCategory("Persistence4")]
1742    [TestProperty("Time", "short")]
1743    public void TestStringSplit() {
1744      string s = "1.2;2.3;3.4;;;4.9";
1745      var l = s.EnumerateSplit(';').ToList();
1746      Assert.AreEqual("1.2", l[0]);
1747      Assert.AreEqual("2.3", l[1]);
1748      Assert.AreEqual("3.4", l[2]);
1749      Assert.AreEqual("4.9", l[3]);
1750    }
1751
1752    [StorableType("B13CB1B0-D2DA-47B8-A715-B166A28B1F03")]
1753    private class IdentityComparer<T> : IEqualityComparer<T> {
1754
1755      public bool Equals(T x, T y) {
1756        return x.Equals(y);
1757      }
1758
1759      public int GetHashCode(T obj) {
1760        return obj.GetHashCode();
1761      }
1762    }
1763
1764    [TestMethod]
1765    [TestCategory("Persistence4")]
1766    [TestProperty("Time", "short")]
1767    public void TestHashSetSerializer() {
1768      ProtoBufSerializer serializer = new ProtoBufSerializer();
1769      var hashSets = new List<HashSet<int>>() {
1770        new HashSet<int>(new[] { 1, 2, 3 }),
1771        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1772      };
1773      serializer.Serialize(hashSets, tempFile);
1774      var newHashSets = (List<HashSet<int>>)serializer.Deserialize(tempFile);
1775      Assert.IsTrue(newHashSets[0].Contains(1));
1776      Assert.IsTrue(newHashSets[0].Contains(2));
1777      Assert.IsTrue(newHashSets[0].Contains(3));
1778      Assert.IsTrue(newHashSets[1].Contains(4));
1779      Assert.IsTrue(newHashSets[1].Contains(5));
1780      Assert.IsTrue(newHashSets[1].Contains(6));
1781      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1782      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1783    }
1784
1785    [TestMethod]
1786    [TestCategory("Persistence4")]
1787    [TestProperty("Time", "short")]
1788    public void TestConcreteDictionarySerializer() {
1789      ProtoBufSerializer serializer = new ProtoBufSerializer();
1790      var dictionaries = new List<Dictionary<int, int>>() {
1791        new Dictionary<int, int>(),
1792        new Dictionary<int, int>(new IdentityComparer<int>()),
1793      };
1794      dictionaries[0].Add(1, 1);
1795      dictionaries[0].Add(2, 2);
1796      dictionaries[0].Add(3, 3);
1797      dictionaries[1].Add(4, 4);
1798      dictionaries[1].Add(5, 5);
1799      dictionaries[1].Add(6, 6);
1800      serializer.Serialize(dictionaries, tempFile);
1801      var newDictionaries = (List<Dictionary<int, int>>)serializer.Deserialize(tempFile);
1802      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1803      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1804      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1805      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1806      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1807      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1808      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1809      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1810      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1811      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1812      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1813      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1814      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1815      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1816    }
1817
1818    [StorableType("A9B0D7FB-0CAF-4DD7-9045-EA136F9176F7")]
1819    public class ReadOnlyFail {
1820      [Storable]
1821      public string ReadOnly {
1822        get { return "fail"; }
1823      }
1824    }
1825
1826    [TestMethod]
1827    [TestCategory("Persistence4")]
1828    [TestProperty("Time", "short")]
1829    public void TestReadOnlyFail() {
1830      ProtoBufSerializer serializer = new ProtoBufSerializer();
1831      try {
1832        serializer.Serialize(new ReadOnlyFail(), tempFile);
1833        Assert.Fail("Exception expected");
1834      } catch (PersistenceException) {
1835      } catch {
1836        Assert.Fail("PersistenceException expected");
1837      }
1838    }
1839
1840
1841    [StorableType("2C9CC576-6823-4784-817B-37C8AF0B1C29")]
1842    public class WriteOnlyFail {
1843      [Storable]
1844      public string WriteOnly {
1845        set { throw new InvalidOperationException("this property should never be set."); }
1846      }
1847    }
1848
1849    [TestMethod]
1850    [TestCategory("Persistence4")]
1851    [TestProperty("Time", "short")]
1852    public void TestWriteOnlyFail() {
1853      ProtoBufSerializer serializer = new ProtoBufSerializer();
1854      try {
1855        serializer.Serialize(new WriteOnlyFail(), tempFile);
1856        Assert.Fail("Exception expected");
1857      } catch (PersistenceException) {
1858      } catch {
1859        Assert.Fail("PersistenceException expected.");
1860      }
1861    }
1862
1863    [StorableType("8052D9E3-6DDD-4AE1-9B5B-67C6D5436512")]
1864    public class OneWayTest {
1865      public OneWayTest() { this.value = "default"; }
1866      public string value;
1867      [Storable(AllowOneWay = true)]
1868      public string ReadOnly {
1869        get { return "ReadOnly"; }
1870      }
1871      [Storable(AllowOneWay = true)]
1872      public string WriteOnly {
1873        set { this.value = value; }
1874      }
1875    }
1876
1877    //TODO
1878    /* [TestMethod]
1879     [TestCategory("Persistence4")]
1880     [TestProperty("Time", "short")]
1881     public void TestTypeCacheExport() {
1882       ProtoBufSerializer serializer = new ProtoBufSerializer();
1883       var test = new List<List<int>>();
1884       test.Add(new List<int>() { 1, 2, 3 });
1885       IEnumerable<Type> types;
1886       using (var stream = new MemoryStream()) {
1887         XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1888       }
1889       List<Type> t = new List<Type>(types);
1890       // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1891       Assert.IsTrue(t.Contains(typeof(List<int>)));
1892       Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1893       Assert.AreEqual(t.Count, 2);
1894     }*/
1895
1896    [TestMethod]
1897    [TestCategory("Persistence4")]
1898    [TestProperty("Time", "short")]
1899    public void TupleTest() {
1900      var t1 = Tuple.Create(1);
1901      var t2 = Tuple.Create('1', "2");
1902      var t3 = Tuple.Create(3.0, 3f, 5);
1903      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1904      var tuple = Tuple.Create(t1, t2, t3, t4);
1905      SerializeNew(tuple);
1906      var newTuple = DeserializeNew();
1907      Assert.AreEqual(tuple, newTuple);
1908    }
1909
1910    [TestMethod]
1911    [TestCategory("Persistence4")]
1912    [TestProperty("Time", "short")]
1913    public void FontTest() {
1914      ProtoBufSerializer serializer = new ProtoBufSerializer();
1915      List<Font> fonts = new List<Font>() {
1916        new Font(FontFamily.GenericSansSerif, 12),
1917        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
1918        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
1919        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
1920      };
1921      serializer.Serialize(fonts, tempFile);
1922      var newFonts = (List<Font>)serializer.Deserialize(tempFile);
1923      Assert.AreEqual(fonts[0], newFonts[0]);
1924      Assert.AreEqual(fonts[1], newFonts[1]);
1925      Assert.AreEqual(fonts[2], newFonts[2]);
1926      Assert.AreEqual(fonts[3], newFonts[3]);
1927    }
1928
1929    [TestMethod]
1930    [TestCategory("Persistence4")]
1931    [TestProperty("Time", "medium")]
1932    public void ConcurrencyTest() {
1933      ProtoBufSerializer serializer = new ProtoBufSerializer();
1934      int n = 20;
1935      Task[] tasks = new Task[n];
1936      for (int i = 0; i < n; i++) {
1937        tasks[i] = Task.Factory.StartNew((idx) => {
1938          byte[] data;
1939          using (var stream = new MemoryStream()) {
1940            serializer.Serialize(new GeneticAlgorithm(), stream);
1941            data = stream.ToArray();
1942          }
1943        }, i);
1944      }
1945      Task.WaitAll(tasks);
1946    }
1947
1948    [TestMethod]
1949    [TestCategory("Persistence4")]
1950    [TestProperty("Time", "medium")]
1951    public void ConcurrentBitmapTest() {
1952      ProtoBufSerializer serializer = new ProtoBufSerializer();
1953      Bitmap b = new Bitmap(300, 300);
1954      System.Random r = new System.Random();
1955      for (int x = 0; x < b.Height; x++) {
1956        for (int y = 0; y < b.Width; y++) {
1957          b.SetPixel(x, y, Color.FromArgb(r.Next()));
1958        }
1959      }
1960      Task[] tasks = new Task[20];
1961      byte[][] datas = new byte[tasks.Length][];
1962      for (int i = 0; i < tasks.Length; i++) {
1963        tasks[i] = Task.Factory.StartNew((idx) => {
1964          using (var stream = new MemoryStream()) {
1965            serializer.Serialize(b, stream);
1966            datas[(int)idx] = stream.ToArray();
1967          }
1968        }, i);
1969      }
1970      Task.WaitAll(tasks);
1971    }
1972
1973    [StorableType("4b4f6317-30c9-4ccd-ad5f-01775f728fbc")]
1974    public class G<T, T2> {
1975      [StorableType("dad331ad-dfc5-4ea5-b044-3e582fcc648d")]
1976      public class S { }
1977      [StorableType("171d3a18-d0ce-498a-a85f-7107a8a198ef")]
1978      public class S2<T3, T4> { }
1979    }
1980
1981
1982    [TestMethod]
1983    [TestCategory("Persistence4")]
1984    [TestProperty("Time", "short")]
1985    public void TestSpecialCharacters() {
1986      ProtoBufSerializer serializer = new ProtoBufSerializer();
1987      var s = "abc" + "\x15" + "def";
1988      serializer.Serialize(s, tempFile);
1989      var newS = serializer.Deserialize(tempFile);
1990      Assert.AreEqual(s, newS);
1991    }
1992
1993    [TestMethod]
1994    [TestCategory("Persistence4")]
1995    [TestProperty("Time", "short")]
1996    public void TestByteArray() {
1997      ProtoBufSerializer serializer = new ProtoBufSerializer();
1998      var b = new byte[3];
1999      b[0] = 0;
2000      b[1] = 200;
2001      b[2] = byte.MaxValue;
2002      serializer.Serialize(b, tempFile);
2003      var newB = (byte[])serializer.Deserialize(tempFile);
2004      CollectionAssert.AreEqual(b, newB);
2005    }
2006
2007    [TestMethod]
2008    [TestCategory("Persistence4")]
2009    [TestProperty("Time", "short")]
2010    public void TestOptionalNumberEnumerable() {
2011      ProtoBufSerializer serializer = new ProtoBufSerializer();
2012      var values = new List<double?> { 0, null, double.NaN, double.PositiveInfinity, double.MaxValue, 1 };
2013      serializer.Serialize(values, tempFile);
2014      var newValues = (List<double?>)serializer.Deserialize(tempFile);
2015      CollectionAssert.AreEqual(values, newValues);
2016    }
2017
2018    [TestMethod]
2019    [TestCategory("Persistence4")]
2020    [TestProperty("Time", "short")]
2021    public void TestOptionalDateTimeEnumerable() {
2022      ProtoBufSerializer serializer = new ProtoBufSerializer();
2023      var values = new List<DateTime?> { DateTime.MinValue, null, DateTime.Now, DateTime.Now.Add(TimeSpan.FromDays(1)),
2024        DateTime.ParseExact("10.09.2014 12:21", "dd.MM.yyyy hh:mm", CultureInfo.InvariantCulture), DateTime.MaxValue};
2025      serializer.Serialize(values, tempFile);
2026      var newValues = (List<DateTime?>)serializer.Deserialize(tempFile);
2027      CollectionAssert.AreEqual(values, newValues);
2028    }
2029
2030    [TestMethod]
2031    [TestCategory("Persistence4")]
2032    [TestProperty("Time", "short")]
2033    public void TestStringEnumerable() {
2034      ProtoBufSerializer serializer = new ProtoBufSerializer();
2035      var values = new List<string> { "", null, "s", "string", string.Empty, "123", "<![CDATA[nice]]>", "<![CDATA[nasty unterminated" };
2036      serializer.Serialize(values, tempFile);
2037      var newValues = (List<String>)serializer.Deserialize(tempFile);
2038      CollectionAssert.AreEqual(values, newValues);
2039    }
2040
2041    [TestMethod]
2042    [TestCategory("Persistence4")]
2043    [TestProperty("Time", "short")]
2044    public void TestUnicodeCharArray() {
2045      ProtoBufSerializer serializer = new ProtoBufSerializer();
2046      var s = Encoding.UTF8.GetChars(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
2047      serializer.Serialize(s, tempFile);
2048      var newS = (char[])serializer.Deserialize(tempFile);
2049      CollectionAssert.AreEqual(s, newS);
2050    }
2051
2052    [TestMethod]
2053    [TestCategory("Persistence4")]
2054    [TestProperty("Time", "short")]
2055    public void TestUnicode() {
2056      ProtoBufSerializer serializer = new ProtoBufSerializer();
2057      var s = Encoding.UTF8.GetString(new byte[] { 0, 1, 2, 03, 04, 05, 06, 07, 08, 09, 0xa, 0xb });
2058      serializer.Serialize(s, tempFile);
2059      var newS = serializer.Deserialize(tempFile);
2060      Assert.AreEqual(s, newS);
2061    }
2062
2063    [TestMethod]
2064    [TestCategory("Persistence4")]
2065    [TestProperty("Time", "short")]
2066    public void TestQueue() {
2067      ProtoBufSerializer serializer = new ProtoBufSerializer();
2068      var q = new Queue<int>(new[] { 1, 2, 3, 4, 0 });
2069      serializer.Serialize(q, tempFile);
2070      var newQ = (Queue<int>)serializer.Deserialize(tempFile);
2071      CollectionAssert.AreEqual(q, newQ);
2072    }
2073    #endregion
2074
2075    [StorableType("6075F1E8-948A-4AD8-8F5A-942B777852EC")]
2076    public class A {
2077      [Storable]
2078      public B B { get; set; }
2079
2080      [Storable]
2081      public int i;
2082    }
2083    [StorableType("287BFEA0-6E27-4839-BCEF-D134FE738AC8")]
2084    public class B {
2085      [Storable]
2086      public A A { get; set; }
2087
2088      [StorableHook(HookType.AfterDeserialization)]
2089      void PostDeserializationHook() {
2090        //Assert.AreEqual(3, A.i);
2091      }
2092    }
2093
2094    [TestMethod]
2095    [TestCategory("Persistence4")]
2096    [TestProperty("Time", "short")]
2097    public void TestCyclicReferencesWithTuple() {
2098      var test = new Func<A>(() => {
2099        var a = new A { i = 4 };
2100        var b = new B { A = a };
2101        a.B = b;
2102        return a;
2103      });
2104
2105      //ProtoBufSerializer serializer = new ProtoBufSerializer();
2106      //serializer.Serialize(test(), tempFile);
2107      //object o = serializer.Deserialize(tempFile);
2108      //A result = (A)o;
2109
2110      XmlGenerator.Serialize(test(), tempFile);
2111      object o = XmlParser.Deserialize(tempFile);
2112
2113      string msg = Profile(test);
2114      Console.WriteLine(msg);
2115    }
2116
2117
2118    #region conversion
2119
2120    [StorableType("F9F51075-490C-48E3-BF64-14514A210149", 1)]
2121    private class OldBaseType {
2122      [Storable]
2123      public ItemCollection<IItem> items;
2124    }
2125    [StorableType("D211A828-6440-4E72-A8C7-AA4F9B4FFA75", 1)]
2126    private class V1 : OldBaseType {
2127      [Storable]
2128      public IntValue a;
2129
2130      [Storable]
2131      public ItemList<IntValue> vals;
2132
2133      [Storable]
2134      public V1 mySelf;
2135
2136      [Storable]
2137      public Tuple<int, int> tup;
2138
2139      [Storable]
2140      public int x;
2141      [Storable]
2142      public int y;
2143    }
2144
2145
2146    [StorableType("B72C58C8-3321-4706-AA94-578F57337070", 2)]
2147    private class NewBaseType {
2148      [Storable]
2149      public DoubleValue[] items;
2150    }
2151    [StorableType("00000000-0000-0000-0000-BADCAFFEE000", 2)] // for testing (version 2)
2152    private partial class V2 : NewBaseType {
2153      [Storable]
2154      public int a;
2155
2156      [Storable]
2157      public int[] val;
2158
2159      [Storable]
2160      public V2 mySelf;
2161
2162      [Storable]
2163      public int TupItem1;
2164
2165      [Storable]
2166      public int TupItem2;
2167
2168      [Storable]
2169      public Point coords;
2170    }
2171
2172    // conversion part
2173    private partial class V2 : NewBaseType {
2174      [StorableConversion(srcVersion: 1)]
2175      private static Dictionary<string, object> ConvertV1(Dictionary<string, object> values) {
2176        var newValues = new Dictionary<string, object>();
2177        var items = (ItemCollection<IItem>)values["OldBaseType.items"];
2178        newValues["NewBaseType.items"] = items.Select(iv => new DoubleValue((double)(((dynamic)iv).Value))).ToArray();
2179        newValues["V2.a"] = ((IntValue)values["V1.a"]).Value;
2180        newValues["V2.val"] = ((ItemList<IntValue>)values["V1.vals"]).Select(iv => iv.Value).ToArray();
2181
2182        newValues["V2.mySelf"] = values["V1.mySelf"]; // myself type will be mapped correctly
2183
2184        var tup = (Tuple<int, int>)values["V1.tup"];
2185        if (tup != null) {
2186          newValues["V2.TupItem1"] = tup.Item1;
2187          newValues["V2.TupItem2"] = tup.Item2;
2188        }
2189
2190        newValues["V2.coords"] = new Point((int)values["V1.x"], (int)values["V1.y"]);
2191
2192        return newValues;
2193      }
2194    }
2195
2196    [StorableType("00000000-0000-0000-0000-BADCAFFEE200", 3)] // for testing (version 3)
2197    private partial class V3 : NewBaseType {
2198      [Storable]
2199      public int a;
2200
2201      [Storable]
2202      public int[] val;
2203
2204      [Storable]
2205      public V3 mySelf;
2206
2207      [Storable]
2208      public Tuple<int, int> tup;
2209
2210      [Storable]
2211      public Point coords;
2212    }
2213
2214    // conversion part
2215    private partial class V3 {
2216      [StorableConversion(srcVersion: 1)]
2217      private static Dictionary<string, object> ConvertV1(Dictionary<string, object> values) {
2218        var newValues = new Dictionary<string, object>();
2219        var items = (ItemCollection<IItem>)values["OldBaseType.items"];
2220        newValues["NewBaseType.items"] = items.Select(iv => new DoubleValue((double)(((dynamic)iv).Value))).ToArray();
2221        newValues["V2.a"] = ((IntValue)values["V1.a"]).Value;
2222        newValues["V2.val"] = ((ItemList<IntValue>)values["V1.vals"]).Select(iv => iv.Value).ToArray();
2223
2224        newValues["V2.mySelf"] = values["V1.mySelf"]; // myself type will be mapped correctly
2225
2226        var tup = (Tuple<int, int>)values["V1.tup"];
2227        if (tup != null) {
2228          newValues["V2.TupItem1"] = tup.Item1;
2229          newValues["V2.TupItem2"] = tup.Item2;
2230        }
2231
2232        newValues["V2.coords"] = new Point((int)values["V1.x"], (int)values["V1.y"]);
2233
2234        return newValues;
2235      }
2236
2237      [StorableConversion(srcVersion: 2)]
2238      private static Dictionary<string, object> ConvertV2(Dictionary<string, object> values) {
2239        var newValues = new Dictionary<string, object>();
2240        newValues["NewBaseType.items"] = values["NewBaseType.items"];
2241        newValues["V3.a"] = values["V2.a"];
2242        newValues["V3.val"] = values["V2.val"];
2243        newValues["V3.mySelf"] = values["V2.mySelf"];
2244
2245        newValues["V3.tup"] = Tuple.Create((int)values["V2.TupItem1"], (int)values["V2.TupItem2"]);
2246        newValues["V3.coords"] = values["V2.coords"];
2247
2248        return newValues;
2249      }
2250    }
2251
2252    [TestMethod]
2253    [TestCategory("Persistence4")]
2254    [TestProperty("Time", "short")]
2255    public void TestConversion() {
2256      var test = new Func<V1>(() => {
2257        var p = new V1();
2258        p.a = new IntValue(1);
2259        p.mySelf = p;
2260        p.vals = new ItemList<IntValue>(new IntValue[] { p.a, new IntValue(2), new IntValue(3) });
2261        p.tup = Tuple.Create(17, 4);
2262        var dv = new DoubleValue(1.0);
2263        p.items = new ItemCollection<IItem>(new IItem[] { dv, dv, p.a });
2264        return p;
2265      });
2266
2267      ProtoBufSerializer serializer = new ProtoBufSerializer();
2268      var old = test();
2269      serializer.Serialize(old, tempFile);
2270      Mapper.StaticCache.DeregisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(V1)).Guid);
2271      Mapper.StaticCache.DeregisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(V2)).Guid);
2272
2273      Mapper.StaticCache.RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(V1)).Guid, typeof(V2));
2274
2275      object o = serializer.Deserialize(tempFile);
2276      var restored = (V2)o;
2277      Assert.AreEqual(restored.a, old.a.Value);
2278      Assert.IsTrue(restored.val.SequenceEqual(old.vals.Select(iv => iv.Value)));
2279      Assert.IsTrue(restored.items.Select(item => item.Value).SequenceEqual(old.items.Select(iv => (double)((dynamic)iv).Value)));
2280      // Assert.AreSame(restored.items[0], restored.items[1]);
2281      Assert.AreSame(restored, restored.mySelf);
2282
2283      //string msg = Profile(test);
2284      //Console.WriteLine(msg);
2285    }
2286
2287    [TestMethod]
2288    [TestCategory("Persistence4")]
2289    [TestProperty("Time", "short")]
2290    public void TestConversion2() {
2291      var test = new Func<V2>(() => {
2292        var p = new V2();
2293        p.a = 1;
2294        p.mySelf = p;
2295        p.val = new int[] { 2, 3, 4 };
2296        p.TupItem1 = 17;
2297        p.TupItem2 = 4;
2298        p.items = new DoubleValue[] { new DoubleValue(1.0), new DoubleValue(2.0) };
2299        return p;
2300      });
2301
2302      ProtoBufSerializer serializer = new ProtoBufSerializer();
2303      var old = test();
2304      serializer.Serialize(old, tempFile);
2305      Mapper.StaticCache.DeregisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(V1)).Guid);
2306      Mapper.StaticCache.DeregisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(V2)).Guid);
2307      Mapper.StaticCache.DeregisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(V3)).Guid);
2308
2309      Mapper.StaticCache.RegisterType(StorableTypeAttribute.GetStorableTypeAttribute(typeof(V2)).Guid, typeof(V3));
2310
2311      object o = serializer.Deserialize(tempFile);
2312      var restored = (V3)o;
2313      Assert.AreEqual(restored.a, old.a);
2314      Assert.IsTrue(restored.val.SequenceEqual(old.val));
2315      Assert.IsTrue(restored.items.Select(item => item.Value).SequenceEqual(old.items.Select(iv => (double)((dynamic)iv).Value)));
2316      // Assert.AreSame(restored.items[0], restored.items[1]);
2317      Assert.AreSame(restored, restored.mySelf);
2318
2319      //string msg = Profile(test);
2320      //Console.WriteLine(msg);
2321    }
2322
2323    #endregion
2324
2325    [TestMethod]
2326    [TestCategory("Persistence4")]
2327    [TestProperty("Time", "short")]
2328    public void TestGASerializeDeserializeExecute() {
2329      var test = new Func<GeneticAlgorithm>(() => {
2330        var ga = new GeneticAlgorithm();
2331        ga.Problem = new SingleObjectiveTestFunctionProblem();
2332        ga.MaximumGenerations.Value = 100;
2333        ga.SetSeedRandomly.Value = false;
2334        return ga;
2335      });
2336      ProtoBufSerializer serializer = new ProtoBufSerializer();
2337      serializer.Serialize(test(), tempFile);
2338      object o = serializer.Deserialize(tempFile);
2339      GeneticAlgorithm result = (GeneticAlgorithm)o;
2340      SamplesUtils.RunAlgorithm(result);
2341      GeneticAlgorithm original = test();
2342      SamplesUtils.RunAlgorithm(original);
2343      //Assert.AreEqual(original.Results[""], result);
2344
2345      //string msg = Profile(test);
2346      //Console.WriteLine(msg);
2347    }
2348    [TestMethod]
2349    [TestCategory("Persistence4")]
2350    [TestProperty("Time", "short")]
2351    public void TestLoadingSamples() {
2352      var path = @"D:\hl\branches\PersistenceReintegration\HeuristicLab.Optimizer\3.3\Documents";
2353      var serializer = new ProtoBufSerializer();
2354      foreach (var fileName in Directory.EnumerateFiles(path, "*.hl")) {
2355        var original = XmlParser.Deserialize(fileName);
2356        var ok = true;
2357        // foreach (var t in original.GetObjectGraphObjects().Select(o => o.GetType())) {
2358        //   if (
2359        //     t.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
2360        //       .Any(ctor => StorableConstructorAttribute.IsStorableConstructor(ctor))) {
2361        //     try {
2362        //       if (t.IsGenericType) {
2363        //         var g = Mapper.StaticCache.GetGuid(t.GetGenericTypeDefinition());
2364        //       } else {
2365        //         var g = Mapper.StaticCache.GetGuid(t);
2366        //       }
2367        //     } catch (Exception e) {
2368        //       Console.WriteLine(t.FullName);
2369        //       ok = false;
2370        //     }
2371        //   }
2372        // }
2373        if (ok) {
2374          serializer.Serialize(original, fileName + ".proto");
2375          // var newVersion = serializer.Deserialize(fileName + ".proto");
2376          var p = Profile(() => original);
2377          Console.WriteLine(p);
2378        }
2379      }
2380    }
2381  }
2382}
Note: See TracBrowser for help on using the repository browser.