Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2520 introduced StorableConstructorFlag type for StorableConstructors

File size: 84.7 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2015 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections;
24using System.Collections.Generic;
25using System.Diagnostics;
26using System.Drawing;
27using System.Globalization;
28using System.IO;
29using System.Linq;
30using System.Reflection;
31using System.Text;
32using System.Threading;
33using System.Threading.Tasks;
34using HeuristicLab.Algorithms.GeneticAlgorithm;
35using HeuristicLab.Common;
36using HeuristicLab.Core;
37using HeuristicLab.Data;
38using HeuristicLab.Persistence;
39using HeuristicLab.Persistence.Auxiliary;
40using HeuristicLab.Persistence.Core;
41using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
42using HeuristicLab.Persistence.Default.DebugString;
43using HeuristicLab.Persistence.Default.Xml;
44using HeuristicLab.Persistence.Tests;
45using HeuristicLab.Problems.TestFunctions;
46using HeuristicLab.Tests;
47using Microsoft.VisualStudio.TestTools.UnitTesting;
48
49namespace HeuristicLab.PersistenceNew.Tests {
50  public static class EnumerableTimeSpanExtensions {
51    public static TimeSpan Average(this IEnumerable<TimeSpan> span) {
52      var avg = (long)Math.Round(span.Select(x => x.Ticks).Average());
53      return new TimeSpan(avg);
54    }
55  }
56
57  #region Test Classes
58  [StorableType("7D9672BD-703D-42BB-9080-9929885D4580")]
59  public class NumberTest {
60    [Storable]
61    private bool _bool = true;
62    [Storable]
63    private byte _byte = 0xFF;
64    [Storable]
65    private sbyte _sbyte = 0xF;
66    [Storable]
67    private short _short = -123;
68    [Storable]
69    private ushort _ushort = 123;
70    [Storable]
71    private int _int = -123;
72    [Storable]
73    private uint _uint = 123;
74    [Storable]
75    private long _long = 123456;
76    [Storable]
77    private ulong _ulong = 123456;
78    public override bool Equals(object obj) {
79      NumberTest nt = obj as NumberTest;
80      if (nt == null)
81        throw new NotSupportedException();
82      return
83        nt._bool == _bool &&
84        nt._byte == _byte &&
85        nt._sbyte == _sbyte &&
86        nt._short == _short &&
87        nt._ushort == _ushort &&
88        nt._int == _int &&
89        nt._uint == _uint &&
90        nt._long == _long &&
91        nt._ulong == _ulong;
92    }
93    public override int GetHashCode() {
94      return
95        _bool.GetHashCode() ^
96        _byte.GetHashCode() ^
97        _sbyte.GetHashCode() ^
98        _short.GetHashCode() ^
99        _short.GetHashCode() ^
100        _int.GetHashCode() ^
101        _uint.GetHashCode() ^
102        _long.GetHashCode() ^
103        _ulong.GetHashCode();
104    }
105  }
106
107  [StorableType("EEB19599-D5AC-48ED-A56B-CF213DFAF2E4")]
108  public class NonDefaultConstructorClass {
109    [Storable]
110    int value;
111    public NonDefaultConstructorClass(int value) {
112      this.value = value;
113    }
114  }
115
116  [StorableType("EE43FE7A-6D07-4D52-9338-C21B3485F82A")]
117  public class IntWrapper {
118
119    [Storable]
120    public int Value;
121
122    private IntWrapper() { }
123
124    public IntWrapper(int value) {
125      this.Value = value;
126    }
127
128    public override bool Equals(object obj) {
129      if (obj as IntWrapper == null)
130        return false;
131      return Value.Equals(((IntWrapper)obj).Value);
132    }
133    public override int GetHashCode() {
134      return Value.GetHashCode();
135    }
136
137  }
138
139  [StorableType("00A8E48E-8E8A-443C-A327-9F6ACCBE7E80")]
140  public class PrimitivesTest : NumberTest {
141    [Storable]
142    private char c = 'e';
143    [Storable]
144    private long[,] _long_array =
145      new long[,] { { 123, 456, }, { 789, 123 } };
146    [Storable]
147    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
148    [Storable]
149    private object o = new object();
150    public override bool Equals(object obj) {
151      PrimitivesTest pt = obj as PrimitivesTest;
152      if (pt == null)
153        throw new NotSupportedException();
154      return base.Equals(obj) &&
155        c == pt.c &&
156        _long_array == pt._long_array &&
157        list == pt.list &&
158        o == pt.o;
159    }
160    public override int GetHashCode() {
161      return base.GetHashCode() ^
162        c.GetHashCode() ^
163        _long_array.GetHashCode() ^
164        list.GetHashCode() ^
165        o.GetHashCode();
166    }
167  }
168
169  [StorableType("c15e3ac3-2681-48a1-9171-d97321cd60bb")]
170  public enum TestEnum { va1, va2, va3, va8 };
171
172  [StorableType("26BA37F6-926D-4665-A10A-1F39E1CF6468")]
173  public class RootBase {
174    [Storable]
175    private string baseString = "   Serial  ";
176    [Storable]
177    public TestEnum myEnum = TestEnum.va3;
178    public override bool Equals(object obj) {
179      RootBase rb = obj as RootBase;
180      if (rb == null)
181        throw new NotSupportedException();
182      return baseString == rb.baseString &&
183        myEnum == rb.myEnum;
184    }
185    public override int GetHashCode() {
186      return baseString.GetHashCode() ^
187        myEnum.GetHashCode();
188    }
189  }
190
191  [StorableType("F6BCB436-B5F2-40F6-8E2F-7A018CD1CBA0")]
192  public class Root : RootBase {
193    [Storable]
194    public Stack<int> intStack = new Stack<int>();
195    [Storable]
196    public int[] i = new[] { 3, 4, 5, 6 };
197    [Storable(Name = "Test String")]
198    public string s;
199    [Storable]
200    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
201    [Storable]
202    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
203    [Storable]
204    public Custom c;
205    [Storable]
206    public List<Root> selfReferences;
207    [Storable]
208    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
209    [Storable]
210    public bool boolean = true;
211    [Storable]
212    public DateTime dateTime;
213    [Storable]
214    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
215    [Storable]
216    public Dictionary<string, int> dict = new Dictionary<string, int>();
217    [Storable(DefaultValue = "default")]
218    public string uninitialized;
219  }
220
221  [StorableType("a6bd45c2-bf18-47d7-9f66-c130222f2f00")]
222  public enum SimpleEnum { one, two, three }
223  [StorableType("b5c8285e-5c1b-457e-a5a3-e25eb588c283")]
224  public enum ComplexEnum { one = 1, two = 2, three = 3 }
225  [FlagsAttribute]
226  [StorableType("c2ee7205-0a3a-443a-87d6-68568c4f4153")]
227  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
228
229  [StorableType("2F6326ED-023A-415F-B5C7-9F9241940D05")]
230  public class EnumTest {
231    [Storable]
232    public SimpleEnum simpleEnum = SimpleEnum.one;
233    [Storable]
234    public ComplexEnum complexEnum = (ComplexEnum)2;
235    [Storable]
236    public TrickyEnum trickyEnum = (TrickyEnum)15;
237  }
238
239  [StorableType("92365E2A-1184-4280-B763-4853C7ADF3E3")]
240  public class Custom {
241    [Storable]
242    public int i;
243    [Storable]
244    public Root r;
245    [Storable]
246    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
247  }
248
249  [StorableType("7CF19EBC-1EC4-4FBE-BCA9-DA48E3CFE30D")]
250  public class Manager {
251
252    public DateTime lastLoadTime;
253    [Storable]
254    private DateTime lastLoadTimePersistence {
255      get { return lastLoadTime; }
256      set { lastLoadTime = DateTime.Now; }
257    }
258    [Storable]
259    public double? dbl;
260  }
261
262  [StorableType("9092C705-F5E9-4BA9-9750-4357DB29AABF")]
263  public class C {
264    [Storable]
265    public C[][] allCs;
266    [Storable]
267    public KeyValuePair<List<C>, C> kvpList;
268  }
269
270  [StorableType("6494ee1d-877b-4e78-83df-f3f55a77b9b4")]
271  public class NonSerializable {
272    int x = 0;
273    public override bool Equals(object obj) {
274      NonSerializable ns = obj as NonSerializable;
275      if (ns == null)
276        throw new NotSupportedException();
277      return ns.x == x;
278    }
279    public override int GetHashCode() {
280      return x.GetHashCode();
281    }
282  }
283
284  [StorableType("FD953B0A-BDE6-41E6-91A8-CA3D90C91CDB")]
285  public class SimpleClass {
286    [Storable]
287    public double x { get; set; }
288    [Storable]
289    public int y { get; set; }
290  }
291
292  #endregion
293
294  [TestClass]
295  [StorableType("6324d1f6-a82b-4914-937a-21846c4af9e6")]
296  public class UseCasesPersistenceNew {
297    #region Helpers
298    private string tempFile;
299
300    [ClassInitialize]
301    public static void Initialize(TestContext testContext) {
302      ConfigurationService.Instance.Reset();
303    }
304
305    [TestInitialize()]
306    public void CreateTempFile() {
307      tempFile = Path.GetTempFileName();
308    }
309
310    [TestCleanup()]
311    public void ClearTempFile() {
312      StreamReader reader = new StreamReader(tempFile);
313      string s = reader.ReadToEnd();
314      reader.Close();
315      File.Delete(tempFile);
316    }
317    #endregion
318
319    #region Persistence 4.0 Profiling Helpers 
320    [StorableType("f90de8e3-e7d1-43b2-a8f0-6689ec922e87")]
321    public class PerformanceData {
322      public TimeSpan OldSerializingTime { get; set; }
323      public TimeSpan NewSerializingTime { get; set; }
324      public TimeSpan OldDeserializingTime { get; set; }
325      public TimeSpan NewDeserializingTime { get; set; }
326      public long OldFileSize { get; set; }
327      public long NewFileSize { get; set; }
328      public long OldSerializingMemoryConsumed { get; set; }
329      public long NewSerializingMemoryConsumed { get; set; }
330      public long OldDeserializingMemoryConsumed { get; set; }
331      public long NewDeserializingMemoryConsumed { get; set; }
332    }
333
334    private void SerializeNew(object o) {
335      ProtoBufSerializer serializer = new ProtoBufSerializer();
336      serializer.Serialize(o, tempFile);
337    }
338    private void SerializeOld(object o) {
339      XmlGenerator.Serialize(o, tempFile);
340    }
341    private object DeserializeNew() {
342      ProtoBufSerializer serializer = new ProtoBufSerializer();
343      return serializer.Deserialize(tempFile);
344    }
345    private object DeserialiezOld() {
346      return XmlParser.Deserialize(tempFile);
347    }
348
349    private void CollectGarbage() {
350      GC.Collect(GC.MaxGeneration, GCCollectionMode.Forced, true);
351      GC.WaitForPendingFinalizers();
352    }
353
354    public PerformanceData ProfileSingleRun(Func<object> GenerateDataFunc) {
355      PerformanceData performanceData = new PerformanceData();
356      Stopwatch sw = new Stopwatch();
357      object data = GenerateDataFunc();
358      object result = null;
359      long startMem, endMem;
360
361
362      //old file format serializing
363      CollectGarbage();
364      startMem = GC.GetTotalMemory(false);
365      sw.Start();
366      SerializeOld(data);
367      sw.Stop();
368      endMem = GC.GetTotalMemory(false);
369      performanceData.OldSerializingTime = sw.Elapsed;
370      performanceData.OldFileSize = new FileInfo(tempFile).Length;
371      performanceData.OldSerializingMemoryConsumed = endMem - startMem;
372      sw.Reset();
373
374
375      //old file format deserializing
376      CollectGarbage();
377      startMem = GC.GetTotalMemory(false);
378      sw.Start();
379      result = DeserialiezOld();
380      sw.Stop();
381      endMem = GC.GetTotalMemory(false);
382      performanceData.OldDeserializingTime = sw.Elapsed;
383      performanceData.OldDeserializingMemoryConsumed = endMem - startMem;
384      sw.Reset();
385
386
387      //new file format serializing
388      CollectGarbage();
389      startMem = GC.GetTotalMemory(false);
390      sw.Start();
391      SerializeNew(data);
392      sw.Stop();
393      endMem = GC.GetTotalMemory(false);
394      performanceData.NewSerializingTime = sw.Elapsed;
395      performanceData.NewSerializingMemoryConsumed = endMem - startMem;
396      performanceData.NewFileSize = new FileInfo(tempFile).Length;
397      sw.Reset();
398
399
400      //new file format deserializing
401      CollectGarbage();
402      startMem = GC.GetTotalMemory(false);
403      sw.Start();
404      result = DeserializeNew();
405      sw.Stop();
406      endMem = GC.GetTotalMemory(false);
407      performanceData.NewDeserializingTime = sw.Elapsed;
408      performanceData.NewDeserializingMemoryConsumed = endMem - startMem;
409      sw.Reset();
410
411      return performanceData;
412    }
413
414    public string Profile(Func<object> GenerateDataFunc) {
415      int nrOfRepetitions = 30;
416      StringBuilder report = new StringBuilder();
417      List<PerformanceData> dataList = new List<PerformanceData>();
418
419      for (int i = 0; i < nrOfRepetitions; i++) {
420        dataList.Add(ProfileSingleRun(GenerateDataFunc));
421      }
422
423      report.Append("Performance Report for " + GenerateDataFunc.Method.Name + ": " + Environment.NewLine);
424      report.Append(Environment.NewLine);
425      report.AppendFormat("Avg. old vs. new time for serializing a file; {0};{1};{2}",
426              dataList.Select(x => x.OldSerializingTime).Average(),
427              dataList.Select(x => x.NewSerializingTime).Average(),
428              dataList.Select(x => x.OldSerializingTime.TotalMilliseconds).Average() / dataList.Select(x => x.NewSerializingTime.TotalMilliseconds).Average()
429              );
430      report.Append(Environment.NewLine);
431      report.AppendFormat("Avg. old vs. new time for deserializing a file; {0};{1};{2}",
432              dataList.Select(x => x.OldDeserializingTime).Average(),
433              dataList.Select(x => x.NewDeserializingTime).Average(),
434              dataList.Select(x => x.OldDeserializingTime.TotalMilliseconds).Average() / dataList.Select(x => x.NewDeserializingTime.TotalMilliseconds).Average()
435              );
436      report.Append(Environment.NewLine);
437      report.AppendFormat("Avg. old vs. new file size (in bytes); {0};{1};{2}",
438              dataList.Select(x => x.OldFileSize).Average(),
439              dataList.Select(x => x.NewFileSize).Average(),
440              dataList.Select(x => x.OldFileSize).Average() / dataList.Select(x => x.NewFileSize).Average()
441              );
442      report.Append(Environment.NewLine);
443      report.AppendFormat("Avg. old vs. new memory consumption for serializing a file (in bytes); {0};{1};{2}",
444              dataList.Select(x => x.OldSerializingMemoryConsumed).Average(),
445              dataList.Select(x => x.NewSerializingMemoryConsumed).Average(),
446              dataList.Select(x => x.OldSerializingMemoryConsumed).Average() / dataList.Select(x => x.NewSerializingMemoryConsumed).Average()
447              );
448      report.Append(Environment.NewLine);
449      report.AppendFormat("Avg. old vs. new memory consumption for deserializing a file (in bytes); {0};{1};{2}",
450              dataList.Select(x => x.OldDeserializingMemoryConsumed).Average(),
451              dataList.Select(x => x.NewDeserializingMemoryConsumed).Average(),
452              dataList.Select(x => x.OldDeserializingMemoryConsumed).Average() / dataList.Select(x => x.NewDeserializingMemoryConsumed).Average()
453              );
454      report.Append(Environment.NewLine);
455
456
457      return report.ToString();
458    }
459    #endregion
460
461    #region Persistence 4.0 test methods
462    [TestMethod]
463    [TestCategory("Persistence4")]
464    [TestProperty("Time", "short")]
465    public void TestBool() {
466      var test = new Func<object>(() => { return true; });
467      ProtoBufSerializer serializer = new ProtoBufSerializer();
468      serializer.Serialize(test(), tempFile);
469      object o = serializer.Deserialize(tempFile);
470      bool result = (bool)o;
471      Assert.AreEqual(test(), result);
472
473      string msg = Profile(test);
474      Console.WriteLine(msg);
475    }
476
477    [TestMethod]
478    [TestCategory("Persistence4")]
479    [TestProperty("Time", "short")]
480    public void TestInt() {
481      var test = new Func<object>(() => { return (int)42; });
482      ProtoBufSerializer serializer = new ProtoBufSerializer();
483      serializer.Serialize(test(), tempFile);
484      object o = serializer.Deserialize(tempFile);
485      int result = (int)o;
486      Assert.AreEqual(test(), result);
487
488      string msg = Profile(test);
489      Console.WriteLine(msg);
490    }
491
492    [TestMethod]
493    [TestCategory("Persistence4")]
494    [TestProperty("Time", "short")]
495    public void TestDouble() {
496      var test = new Func<object>(() => { return 42.5d; });
497      ProtoBufSerializer serializer = new ProtoBufSerializer();
498      serializer.Serialize(test(), tempFile);
499      object o = serializer.Deserialize(tempFile);
500      double result = (double)o;
501      Assert.AreEqual(test(), result);
502      Assert.IsTrue(o is double);
503
504      string msg = Profile(test);
505      Console.WriteLine(msg);
506    }
507
508    [TestMethod]
509    [TestCategory("Persistence4")]
510    [TestProperty("Time", "short")]
511    public void TestFloat() {
512      var test = new Func<object>(() => { return 42.5f; });
513      ProtoBufSerializer serializer = new ProtoBufSerializer();
514      serializer.Serialize(test(), tempFile);
515      object o = serializer.Deserialize(tempFile);
516      float result = (float)o;
517      Assert.AreEqual(test(), result);
518      Assert.IsTrue(o is float);
519
520      string msg = Profile(test);
521      Console.WriteLine(msg);
522    }
523
524    [TestMethod]
525    [TestCategory("Persistence4")]
526    [TestProperty("Time", "short")]
527    public void TestDecimal() {
528      var test = new Func<object>(() => { return 42.5m; });
529      ProtoBufSerializer serializer = new ProtoBufSerializer();
530      serializer.Serialize(test(), tempFile);
531      object o = serializer.Deserialize(tempFile);
532      decimal result = (decimal)o;
533      Assert.AreEqual(test(), result);
534      Assert.IsTrue(o is decimal);
535
536      string msg = Profile(test);
537      Console.WriteLine(msg);
538    }
539
540    [TestMethod]
541    [TestCategory("Persistence4")]
542    [TestProperty("Time", "short")]
543    public void TestLong() {
544      var test = new Func<object>(() => { return 42l; });
545      ProtoBufSerializer serializer = new ProtoBufSerializer();
546      serializer.Serialize(test(), tempFile);
547      object o = serializer.Deserialize(tempFile);
548      long result = (long)o;
549      Assert.AreEqual(test(), result);
550      Assert.IsTrue(o is long);
551
552      string msg = Profile(test);
553      Console.WriteLine(msg);
554    }
555
556    [TestMethod]
557    [TestCategory("Persistence4")]
558    [TestProperty("Time", "short")]
559    public void TestUInt() {
560      var test = new Func<object>(() => { return 42u; });
561      ProtoBufSerializer serializer = new ProtoBufSerializer();
562      serializer.Serialize(test(), tempFile);
563      object o = serializer.Deserialize(tempFile);
564      uint result = (uint)o;
565      Assert.AreEqual(test(), result);
566      Assert.IsTrue(o is uint);
567
568      string msg = Profile(test);
569      Console.WriteLine(msg);
570    }
571
572    [TestMethod]
573    [TestCategory("Persistence4")]
574    [TestProperty("Time", "short")]
575    public void TestShort() {
576      var test = new Func<object>(() => { short s = 42; return s; });
577      ProtoBufSerializer serializer = new ProtoBufSerializer();
578      serializer.Serialize(test(), tempFile);
579      object o = serializer.Deserialize(tempFile);
580      short result = (short)o;
581      Assert.IsTrue(o is short);
582      Assert.AreEqual(test(), result);
583
584      string msg = Profile(test);
585      Console.WriteLine(msg);
586    }
587
588    [TestMethod]
589    [TestCategory("Persistence4")]
590    [TestProperty("Time", "short")]
591    public void TestByte() {
592      var test = new Func<object>(() => { byte b = 42; return b; });
593      ProtoBufSerializer serializer = new ProtoBufSerializer();
594      serializer.Serialize(test(), tempFile);
595      object o = serializer.Deserialize(tempFile);
596      byte result = (byte)o;
597      Assert.IsTrue(o is byte);
598      Assert.AreEqual(test(), result);
599
600      string msg = Profile(test);
601      Console.WriteLine(msg);
602    }
603
604    [TestMethod]
605    [TestCategory("Persistence4")]
606    [TestProperty("Time", "short")]
607    public void TestEnumSimple() {
608      var test = new Func<object>(() => { return SimpleEnum.two; });
609
610      ProtoBufSerializer serializer = new ProtoBufSerializer();
611      serializer.Serialize(test(), tempFile);
612      object o = serializer.Deserialize(tempFile);
613      SimpleEnum result = (SimpleEnum)o;
614      Assert.AreEqual(test(), result);
615
616      string msg = Profile(test);
617      Console.WriteLine(msg);
618    }
619
620    [TestMethod]
621    [TestCategory("Persistence4")]
622    [TestProperty("Time", "short")]
623    public void TestEnumComplex() {
624      var test = new Func<object>(() => { return ComplexEnum.three; });
625      ProtoBufSerializer serializer = new ProtoBufSerializer();
626      serializer.Serialize(test(), tempFile);
627      object o = serializer.Deserialize(tempFile);
628      ComplexEnum result = (ComplexEnum)o;
629      Assert.AreEqual(test(), result);
630
631      string msg = Profile(test);
632      Console.WriteLine(msg);
633    }
634
635    [TestMethod]
636    [TestCategory("Persistence4")]
637    [TestProperty("Time", "short")]
638    public void TestType() {
639      var test = new Func<object>(() => { return typeof(HeuristicLab.Algorithms.GeneticAlgorithm.GeneticAlgorithm); });
640      ProtoBufSerializer serializer = new ProtoBufSerializer();
641      serializer.Serialize(test(), tempFile);
642      object o = serializer.Deserialize(tempFile);
643      Type result = (Type)o;
644      Assert.AreEqual(test(), result);
645
646      string msg = Profile(test);
647      Console.WriteLine(msg);
648    }
649
650    [TestMethod]
651    [TestCategory("Persistence4")]
652    [TestProperty("Time", "short")]
653    public void TestBytes() {
654      var test = new Func<byte[]>(() => { return new byte[] { 3, 1 }; });
655      ProtoBufSerializer serializer = new ProtoBufSerializer();
656      serializer.Serialize(test(), tempFile);
657      object o = serializer.Deserialize(tempFile);
658      byte[] result = (byte[])o;
659      Assert.AreEqual(test()[0], result[0]);
660      Assert.AreEqual(test()[1], result[1]);
661
662      string msg = Profile(test);
663      Console.WriteLine(msg);
664    }
665
666    [TestMethod]
667    [TestCategory("Persistence4")]
668    [TestProperty("Time", "short")]
669    public void TestSBytes() {
670      var test = new Func<sbyte[]>(() => { return new sbyte[] { 3, 1 }; });
671      ProtoBufSerializer serializer = new ProtoBufSerializer();
672      serializer.Serialize(test(), tempFile);
673      object o = serializer.Deserialize(tempFile);
674      sbyte[] result = (sbyte[])o;
675      Assert.AreEqual(test()[0], result[0]);
676      Assert.AreEqual(test()[1], result[1]);
677
678      string msg = Profile(test);
679      Console.WriteLine(msg);
680    }
681
682    [TestMethod]
683    [TestCategory("Persistence4")]
684    [TestProperty("Time", "short")]
685    public void TestChars() {
686      var test = new Func<char[]>(() => { return new char[] { 'a', 'b' }; });
687      ProtoBufSerializer serializer = new ProtoBufSerializer();
688      serializer.Serialize(test(), tempFile);
689      object o = serializer.Deserialize(tempFile);
690      char[] result = (char[])o;
691      Assert.AreEqual(test()[0], result[0]);
692      Assert.AreEqual(test()[1], result[1]);
693
694      string msg = Profile(test);
695      Console.WriteLine(msg);
696    }
697
698    [TestMethod]
699    [TestCategory("Persistence4")]
700    [TestProperty("Time", "short")]
701    public void TestShorts() {
702      var test = new Func<short[]>(() => { return new short[] { 3, 1 }; });
703      ProtoBufSerializer serializer = new ProtoBufSerializer();
704      serializer.Serialize(test(), tempFile);
705      object o = serializer.Deserialize(tempFile);
706      short[] result = (short[])o;
707      Assert.AreEqual(test()[0], result[0]);
708      Assert.AreEqual(test()[1], result[1]);
709
710      string msg = Profile(test);
711      Console.WriteLine(msg);
712    }
713
714    [TestMethod]
715    [TestCategory("Persistence4")]
716    [TestProperty("Time", "short")]
717    public void TestUShorts() {
718      var test = new Func<ushort[]>(() => { return new ushort[] { 3, 1 }; });
719      ProtoBufSerializer serializer = new ProtoBufSerializer();
720      serializer.Serialize(test(), tempFile);
721      object o = serializer.Deserialize(tempFile);
722      ushort[] result = (ushort[])o;
723      Assert.AreEqual(test()[0], result[0]);
724      Assert.AreEqual(test()[1], result[1]);
725
726      string msg = Profile(test);
727      Console.WriteLine(msg);
728    }
729
730    [TestMethod]
731    [TestCategory("Persistence4")]
732    [TestProperty("Time", "short")]
733    public void TestString() {
734      var test = new Func<object>(() => { return "Hello World!"; });
735      ProtoBufSerializer serializer = new ProtoBufSerializer();
736      serializer.Serialize(test(), tempFile);
737      object o = serializer.Deserialize(tempFile);
738      string result = (string)o;
739      Assert.AreEqual(test(), result);
740
741      string msg = Profile(test);
742      Console.WriteLine(msg);
743    }
744
745    [TestMethod]
746    [TestCategory("Persistence4")]
747    [TestProperty("Time", "short")]
748    public void TestColor() {
749      var test = new Func<object>(() => { return Color.FromArgb(12, 34, 56, 78); });
750      ProtoBufSerializer serializer = new ProtoBufSerializer();
751      serializer.Serialize(test(), tempFile);
752      object o = serializer.Deserialize(tempFile);
753      Color result = (Color)o;
754      Assert.AreEqual(test(), result);
755
756      string msg = Profile(test);
757      Console.WriteLine(msg);
758    }
759
760    [TestMethod]
761    [TestCategory("Persistence4")]
762    [TestProperty("Time", "short")]
763    public void TestPoint() {
764      var test = new Func<object>(() => { return new Point(3, 4); });
765      ProtoBufSerializer serializer = new ProtoBufSerializer();
766      serializer.Serialize(test(), tempFile);
767      object o = serializer.Deserialize(tempFile);
768      Point result = (Point)o;
769      Assert.AreEqual(((Point)test()).X, result.X);
770      Assert.AreEqual(((Point)test()).Y, result.Y);
771
772      string msg = Profile(test);
773      Console.WriteLine(msg);
774    }
775
776    [TestMethod]
777    [TestCategory("Persistence4")]
778    [TestProperty("Time", "short")]
779    public void TestBoolArray() {
780      var test = new Func<bool[]>(() => { return new[] { true, false, true }; });
781      ProtoBufSerializer serializer = new ProtoBufSerializer();
782      serializer.Serialize(test(), tempFile);
783      object o = serializer.Deserialize(tempFile);
784      bool[] result = (bool[])o;
785      Assert.AreEqual(test()[0], result[0]);
786      Assert.AreEqual(test()[1], result[1]);
787      Assert.AreEqual(test()[2], result[2]);
788
789      string msg = Profile(test);
790      Console.WriteLine(msg);
791    }
792
793    [TestMethod]
794    [TestCategory("Persistence4")]
795    [TestProperty("Time", "short")]
796    public void TestIntArray() {
797      var test = new Func<int[]>(() => { return new[] { 41, 22, 13 }; });
798      ProtoBufSerializer serializer = new ProtoBufSerializer();
799      serializer.Serialize(test(), tempFile);
800      object o = serializer.Deserialize(tempFile);
801      int[] result = (int[])o;
802      Assert.AreEqual(test()[0], result[0]);
803      Assert.AreEqual(test()[1], result[1]);
804      Assert.AreEqual(test()[2], result[2]);
805
806      string msg = Profile(test);
807      Console.WriteLine(msg);
808    }
809
810    [TestMethod]
811    [TestCategory("Persistence4")]
812    [TestProperty("Time", "short")]
813    public void TestLongArray() {
814      var test = new Func<long[]>(() => { return new[] { 414481188112191633l, 245488586662l, 13546881335845865l }; });
815      ProtoBufSerializer serializer = new ProtoBufSerializer();
816      serializer.Serialize(test(), tempFile);
817      object o = serializer.Deserialize(tempFile);
818      long[] result = (long[])o;
819      Assert.AreEqual(test()[0], result[0]);
820      Assert.AreEqual(test()[1], result[1]);
821      Assert.AreEqual(test()[2], result[2]);
822
823      string msg = Profile(test);
824      Console.WriteLine(msg);
825    }
826
827    [TestMethod]
828    [TestCategory("Persistence4")]
829    [TestProperty("Time", "short")]
830    public void TestDoubleArray() {
831      var test = new Func<double[]>(() => { return new[] { 41.5, 22.7, 13.8 }; });
832      ProtoBufSerializer serializer = new ProtoBufSerializer();
833      serializer.Serialize(test(), tempFile);
834      object o = serializer.Deserialize(tempFile);
835      double[] result = (double[])o;
836      Assert.AreEqual(test()[0], result[0]);
837      Assert.AreEqual(test()[1], result[1]);
838      Assert.AreEqual(test()[2], result[2]);
839
840      string msg = Profile(test);
841      Console.WriteLine(msg);
842    }
843
844    [TestMethod]
845    [TestCategory("Persistence4")]
846    [TestProperty("Time", "short")]
847    public void TestObjectArray() {
848      var test = new Func<SimpleClass[]>(() => {
849        return new[] { new SimpleClass() { x = 42, y = 43 },
850                       new SimpleClass() { x = 44.44, y = 5677 },
851                       new SimpleClass() { x = 533.33, y = 2345 } };
852      });
853      ProtoBufSerializer serializer = new ProtoBufSerializer();
854      serializer.Serialize(test(), tempFile);
855      object o = serializer.Deserialize(tempFile);
856      SimpleClass[] result = (SimpleClass[])o;
857      Assert.AreEqual(test()[0].x, result[0].x);
858      Assert.AreEqual(test()[0].y, result[0].y);
859      Assert.AreEqual(test()[1].x, result[1].x);
860      Assert.AreEqual(test()[1].y, result[1].y);
861      Assert.AreEqual(test()[2].x, result[2].x);
862      Assert.AreEqual(test()[2].y, result[2].y);
863
864      string msg = Profile(test);
865      Console.WriteLine(msg);
866    }
867
868    [TestMethod]
869    [TestCategory("Persistence4")]
870    [TestProperty("Time", "short")]
871    public void TestStack() {
872      var test = new Func<Stack>(() => {
873        return new Stack(new int[] { 1, 2, 3 });
874      });
875      ProtoBufSerializer serializer = new ProtoBufSerializer();
876      serializer.Serialize(test(), tempFile);
877      object o = serializer.Deserialize(tempFile);
878      Stack result = (Stack)o;
879      var actualStack = test();
880      Assert.AreEqual(actualStack.Pop(), result.Pop());
881      Assert.AreEqual(actualStack.Pop(), result.Pop());
882      Assert.AreEqual(actualStack.Pop(), result.Pop());
883
884      string msg = Profile(test);
885      Console.WriteLine(msg);
886    }
887
888    [TestMethod]
889    [TestCategory("Persistence4")]
890    [TestProperty("Time", "short")]
891    public void TestArrayOfStack() {
892      var test = new Func<object[]>(() => {
893        return new object[] {
894          new Stack(new int[] { 1, 2, 3 }),
895          new Stack<int>(new int[] { 1, 2, 3 }),
896      };
897      });
898      ProtoBufSerializer serializer = new ProtoBufSerializer();
899      serializer.Serialize(test(), tempFile);
900      object o = serializer.Deserialize(tempFile);
901      var result = (object[])o;
902      var firstStack = (Stack)result[0];
903      var secondStack = (Stack<int>)result[1];
904      var actual = test();
905      var actualFirst = (Stack)actual[0];
906      var actualSecond = (Stack<int>)actual[1];
907
908      Assert.AreEqual(actualFirst.Pop(), firstStack.Pop());
909      Assert.AreEqual(actualFirst.Pop(), firstStack.Pop());
910      Assert.AreEqual(actualFirst.Pop(), firstStack.Pop());
911      Assert.AreEqual(actualSecond.Pop(), secondStack.Pop());
912      Assert.AreEqual(actualSecond.Pop(), secondStack.Pop());
913      Assert.AreEqual(actualSecond.Pop(), secondStack.Pop());
914
915      string msg = Profile(test);
916      Console.WriteLine(msg);
917    }
918
919
920    [TestMethod]
921    [TestCategory("Persistence4")]
922    [TestProperty("Time", "short")]
923    public void TestIntValueArray() {
924      var test = new Func<IntValue[]>(() => { return new[] { new IntValue(41), new IntValue(22), new IntValue(13) }; });
925      ProtoBufSerializer serializer = new ProtoBufSerializer();
926      serializer.Serialize(test(), tempFile);
927      object o = serializer.Deserialize(tempFile);
928      IntValue[] result = (IntValue[])o;
929      Assert.AreEqual(test()[0].Value, result[0].Value);
930      Assert.AreEqual(test()[1].Value, result[1].Value);
931      Assert.AreEqual(test()[2].Value, result[2].Value);
932
933      string msg = Profile(test);
934      Console.WriteLine(msg);
935    }
936
937    [TestMethod]
938    [TestCategory("Persistence4")]
939    [TestProperty("Time", "short")]
940    public void TestIntValueArrayArray() {
941      var test = new Func<IntValue[][]>(() => { return new IntValue[][] { new IntValue[] { new IntValue(41), new IntValue(22), new IntValue(13) } }; });
942      ProtoBufSerializer serializer = new ProtoBufSerializer();
943      serializer.Serialize(test(), tempFile);
944      object o = serializer.Deserialize(tempFile);
945      IntValue[][] result = (IntValue[][])o;
946      Assert.AreEqual(test()[0][0].Value, result[0][0].Value);
947      Assert.AreEqual(test()[0][1].Value, result[0][1].Value);
948      Assert.AreEqual(test()[0][2].Value, result[0][2].Value);
949
950      string msg = Profile(test);
951      Console.WriteLine(msg);
952    }
953    #endregion
954
955
956    #region Old persistence test methods
957    [TestMethod]
958    [TestCategory("Persistence4")]
959    [TestProperty("Time", "short")]
960    public void ComplexStorable() {
961      ProtoBufSerializer serializer = new ProtoBufSerializer();
962      Root r = InitializeComplexStorable();
963      serializer.Serialize(r, tempFile);
964      Root newR = (Root)serializer.Deserialize(tempFile);
965      CompareComplexStorables(r, newR);
966    }
967
968    private static void CompareComplexStorables(Root r, Root newR) {
969      Assert.AreEqual(
970        DebugStringGenerator.Serialize(r),
971        DebugStringGenerator.Serialize(newR));
972      Assert.AreSame(newR, newR.selfReferences[0]);
973      Assert.AreNotSame(r, newR);
974      Assert.AreEqual(r.myEnum, TestEnum.va1);
975      Assert.AreEqual(r.i[0], 7);
976      Assert.AreEqual(r.i[1], 5);
977      Assert.AreEqual(r.i[2], 6);
978      Assert.AreEqual(r.s, "new value");
979      Assert.AreEqual(r.intArray[0], 3);
980      Assert.AreEqual(r.intArray[1], 2);
981      Assert.AreEqual(r.intArray[2], 1);
982      Assert.AreEqual(r.intList[0], 9);
983      Assert.AreEqual(r.intList[1], 8);
984      Assert.AreEqual(r.intList[2], 7);
985      Assert.AreEqual(r.multiDimArray[0, 0], 5);
986      Assert.AreEqual(r.multiDimArray[0, 1], 4);
987      Assert.AreEqual(r.multiDimArray[0, 2], 3);
988      Assert.AreEqual(r.multiDimArray[1, 0], 1);
989      Assert.AreEqual(r.multiDimArray[1, 1], 4);
990      Assert.AreEqual(r.multiDimArray[1, 2], 6);
991      Assert.IsFalse(r.boolean);
992      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
993      Assert.AreEqual(r.kvp.Key, "string key");
994      Assert.AreEqual(r.kvp.Value, 321);
995      Assert.IsNull(r.uninitialized);
996      Assert.AreEqual(newR.myEnum, TestEnum.va1);
997      Assert.AreEqual(newR.i[0], 7);
998      Assert.AreEqual(newR.i[1], 5);
999      Assert.AreEqual(newR.i[2], 6);
1000      Assert.AreEqual(newR.s, "new value");
1001      Assert.AreEqual(newR.intArray[0], 3);
1002      Assert.AreEqual(newR.intArray[1], 2);
1003      Assert.AreEqual(newR.intArray[2], 1);
1004      Assert.AreEqual(newR.intList[0], 9);
1005      Assert.AreEqual(newR.intList[1], 8);
1006      Assert.AreEqual(newR.intList[2], 7);
1007      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
1008      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
1009      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
1010      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
1011      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
1012      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
1013      Assert.AreEqual(newR.intStack.Pop(), 3);
1014      Assert.AreEqual(newR.intStack.Pop(), 2);
1015      Assert.AreEqual(newR.intStack.Pop(), 1);
1016      Assert.IsFalse(newR.boolean);
1017      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
1018      Assert.AreEqual(newR.kvp.Key, "string key");
1019      Assert.AreEqual(newR.kvp.Value, 321);
1020      Assert.IsNull(newR.uninitialized);
1021    }
1022
1023    private static Root InitializeComplexStorable() {
1024      Root r = new Root();
1025      r.intStack.Push(1);
1026      r.intStack.Push(2);
1027      r.intStack.Push(3);
1028      r.selfReferences = new List<Root> { r, r };
1029      r.c = new Custom { r = r };
1030      r.dict.Add("one", 1);
1031      r.dict.Add("two", 2);
1032      r.dict.Add("three", 3);
1033      r.myEnum = TestEnum.va1;
1034      r.i = new[] { 7, 5, 6 };
1035      r.s = "new value";
1036      r.intArray = new ArrayList { 3, 2, 1 };
1037      r.intList = new List<int> { 9, 8, 7 };
1038      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
1039      r.boolean = false;
1040      r.dateTime = DateTime.Now;
1041      r.kvp = new KeyValuePair<string, int>("string key", 321);
1042      r.uninitialized = null;
1043
1044      return r;
1045    }
1046
1047    [TestMethod]
1048    [TestCategory("Persistence4")]
1049    [TestProperty("Time", "short")]
1050    public void SelfReferences() {
1051      ProtoBufSerializer serializer = new ProtoBufSerializer();
1052      C c = new C();
1053      C[][] cs = new C[2][];
1054      cs[0] = new C[] { c };
1055      cs[1] = new C[] { c };
1056      c.allCs = cs;
1057      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
1058      serializer.Serialize(cs, tempFile);
1059      object o = serializer.Deserialize(tempFile);
1060      Assert.AreEqual(
1061        DebugStringGenerator.Serialize(cs),
1062        DebugStringGenerator.Serialize(o));
1063      Assert.AreSame(c, c.allCs[0][0]);
1064      Assert.AreSame(c, c.allCs[1][0]);
1065      Assert.AreSame(c, c.kvpList.Key[0]);
1066      Assert.AreSame(c, c.kvpList.Value);
1067      C[][] newCs = (C[][])o;
1068      C newC = newCs[0][0];
1069      Assert.AreSame(newC, newC.allCs[0][0]);
1070      Assert.AreSame(newC, newC.allCs[1][0]);
1071      Assert.AreSame(newC, newC.kvpList.Key[0]);
1072      Assert.AreSame(newC, newC.kvpList.Value);
1073    }
1074
1075    [TestMethod]
1076    [TestCategory("Persistence4")]
1077    [TestProperty("Time", "short")]
1078    public void ArrayCreation() {
1079      ProtoBufSerializer serializer = new ProtoBufSerializer();
1080      ArrayList[] arrayListArray = new ArrayList[4];
1081      arrayListArray[0] = new ArrayList();
1082      arrayListArray[0].Add(arrayListArray);
1083      arrayListArray[0].Add(arrayListArray);
1084      arrayListArray[1] = new ArrayList();
1085      arrayListArray[1].Add(arrayListArray);
1086      arrayListArray[2] = new ArrayList();
1087      arrayListArray[2].Add(arrayListArray);
1088      arrayListArray[2].Add(arrayListArray);
1089      //Array a = Array.CreateInstance(
1090      //                        typeof(object),
1091      //                        new[] { 1, 2 }, new[] { 3, 4 });
1092      //arrayListArray[2].Add(a);
1093      serializer.Serialize(arrayListArray, tempFile);
1094      object o = serializer.Deserialize(tempFile);
1095      Assert.AreEqual(
1096        DebugStringGenerator.Serialize(arrayListArray),
1097        DebugStringGenerator.Serialize(o));
1098      ArrayList[] newArray = (ArrayList[])o;
1099      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
1100      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
1101      Assert.AreSame(newArray, newArray[0][0]);
1102      Assert.AreSame(newArray, newArray[2][1]);
1103    }
1104
1105    [TestMethod]
1106    [TestCategory("Persistence4")]
1107    [TestProperty("Time", "short")]
1108    public void CustomSerializationProperty() {
1109      ProtoBufSerializer serializer = new ProtoBufSerializer();
1110      Manager m = new Manager();
1111      serializer.Serialize(m, tempFile);
1112      Manager newM = (Manager)serializer.Deserialize(tempFile);
1113      Assert.AreNotEqual(
1114        DebugStringGenerator.Serialize(m),
1115        DebugStringGenerator.Serialize(newM));
1116      Assert.AreEqual(m.dbl, newM.dbl);
1117      Assert.AreEqual(m.lastLoadTime, new DateTime());
1118      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
1119      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
1120    }
1121
1122    [TestMethod]
1123    [TestCategory("Persistence4")]
1124    [TestProperty("Time", "short")]
1125    public void Primitives() {
1126      ProtoBufSerializer serializer = new ProtoBufSerializer();
1127      PrimitivesTest sdt = new PrimitivesTest();
1128      serializer.Serialize(sdt, tempFile);
1129      object o = serializer.Deserialize(tempFile);
1130      Assert.AreEqual(
1131        DebugStringGenerator.Serialize(sdt),
1132        DebugStringGenerator.Serialize(o));
1133    }
1134
1135    [TestMethod]
1136    [TestCategory("Persistence4")]
1137    [TestProperty("Time", "short")]
1138    public void MultiDimensionalArray() {
1139      ProtoBufSerializer serializer = new ProtoBufSerializer();
1140      string[,] mDimString = new string[,] {
1141        {"ora", "et", "labora"},
1142        {"Beten", "und", "Arbeiten"}
1143      };
1144      serializer.Serialize(mDimString, tempFile);
1145      object o = serializer.Deserialize(tempFile);
1146      Assert.AreEqual(
1147        DebugStringGenerator.Serialize(mDimString),
1148        DebugStringGenerator.Serialize(o));
1149    }
1150
1151    [StorableType("87A331AF-14DC-48B3-B577-D49065743BE6")]
1152    public class NestedType {
1153      [Storable]
1154      private string value = "value";
1155      public override bool Equals(object obj) {
1156        NestedType nt = obj as NestedType;
1157        if (nt == null)
1158          throw new NotSupportedException();
1159        return nt.value == value;
1160      }
1161      public override int GetHashCode() {
1162        return value.GetHashCode();
1163      }
1164    }
1165
1166    [TestMethod]
1167    [TestCategory("Persistence4")]
1168    [TestProperty("Time", "short")]
1169    public void NestedTypeTest() {
1170      ProtoBufSerializer serializer = new ProtoBufSerializer();
1171      NestedType t = new NestedType();
1172      serializer.Serialize(t, tempFile);
1173      object o = serializer.Deserialize(tempFile);
1174      Assert.AreEqual(
1175        DebugStringGenerator.Serialize(t),
1176        DebugStringGenerator.Serialize(o));
1177      Assert.IsTrue(t.Equals(o));
1178    }
1179
1180
1181    [TestMethod]
1182    [TestCategory("Persistence4")]
1183    [TestProperty("Time", "short")]
1184    public void SimpleArray() {
1185      ProtoBufSerializer serializer = new ProtoBufSerializer();
1186      string[] strings = { "ora", "et", "labora" };
1187      serializer.Serialize(strings, tempFile);
1188      object o = serializer.Deserialize(tempFile);
1189      Assert.AreEqual(
1190        DebugStringGenerator.Serialize(strings),
1191        DebugStringGenerator.Serialize(o));
1192    }
1193
1194    [TestMethod]
1195    [TestCategory("Persistence4")]
1196    [TestProperty("Time", "short")]
1197    public void PrimitiveRoot() {
1198      ProtoBufSerializer serializer = new ProtoBufSerializer();
1199      serializer.Serialize(12.3f, tempFile);
1200      object o = serializer.Deserialize(tempFile);
1201      Assert.AreEqual(
1202        DebugStringGenerator.Serialize(12.3f),
1203        DebugStringGenerator.Serialize(o));
1204    }
1205
1206    private string formatFullMemberName(MemberInfo mi) {
1207      return new StringBuilder()
1208        .Append(mi.DeclaringType.Assembly.GetName().Name)
1209        .Append(": ")
1210        .Append(mi.DeclaringType.Namespace)
1211        .Append('.')
1212        .Append(mi.DeclaringType.Name)
1213        .Append('.')
1214        .Append(mi.Name).ToString();
1215    }
1216
1217    public void CodingConventions() {
1218      List<string> lowerCaseMethodNames = new List<string>();
1219      List<string> lowerCaseProperties = new List<string>();
1220      List<string> lowerCaseFields = new List<string>();
1221      foreach (Assembly a in PluginLoader.Assemblies) {
1222        if (!a.GetName().Name.StartsWith("HeuristicLab"))
1223          continue;
1224        foreach (Type t in a.GetTypes()) {
1225          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
1226            if (mi.DeclaringType.Name.StartsWith("<>"))
1227              continue;
1228            if (char.IsLower(mi.Name[0])) {
1229              if (mi.MemberType == MemberTypes.Field)
1230                lowerCaseFields.Add(formatFullMemberName(mi));
1231              if (mi.MemberType == MemberTypes.Property)
1232                lowerCaseProperties.Add(formatFullMemberName(mi));
1233              if (mi.MemberType == MemberTypes.Method &&
1234                !mi.Name.StartsWith("get_") &&
1235                !mi.Name.StartsWith("set_") &&
1236                !mi.Name.StartsWith("add_") &&
1237                !mi.Name.StartsWith("remove_") &&
1238                !mi.Name.StartsWith("op_"))
1239                lowerCaseMethodNames.Add(formatFullMemberName(mi));
1240            }
1241          }
1242        }
1243      }
1244      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
1245      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
1246      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
1247    }
1248
1249    [TestMethod]
1250    [TestCategory("Persistence4")]
1251    [TestProperty("Time", "short")]
1252    public void Enums() {
1253      ProtoBufSerializer serializer = new ProtoBufSerializer();
1254      EnumTest et = new EnumTest();
1255      et.simpleEnum = SimpleEnum.two;
1256      et.complexEnum = ComplexEnum.three;
1257      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
1258      serializer.Serialize(et, tempFile);
1259      EnumTest newEt = (EnumTest)serializer.Deserialize(tempFile);
1260      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
1261      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
1262      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
1263    }
1264
1265    [TestMethod]
1266    [TestCategory("Persistence4")]
1267    [TestProperty("Time", "short")]
1268    public void TestAliasingWithOverriddenEquals() {
1269      ProtoBufSerializer serializer = new ProtoBufSerializer();
1270      List<IntWrapper> ints = new List<IntWrapper>();
1271      ints.Add(new IntWrapper(1));
1272      ints.Add(new IntWrapper(1));
1273      Assert.AreEqual(ints[0], ints[1]);
1274      Assert.AreNotSame(ints[0], ints[1]);
1275      serializer.Serialize(ints, tempFile);
1276      List<IntWrapper> newInts = (List<IntWrapper>)serializer.Deserialize(tempFile);
1277      Assert.AreEqual(newInts[0].Value, 1);
1278      Assert.AreEqual(newInts[1].Value, 1);
1279      Assert.AreEqual(newInts[0], newInts[1]);
1280      Assert.AreNotSame(newInts[0], newInts[1]);
1281    }
1282
1283    [TestMethod]
1284    [TestCategory("Persistence4")]
1285    [TestProperty("Time", "short")]
1286    public void NonDefaultConstructorTest() {
1287      ProtoBufSerializer serializer = new ProtoBufSerializer();
1288      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
1289      try {
1290        serializer.Serialize(c, tempFile);
1291        Assert.Fail("Exception not thrown");
1292      } catch (PersistenceException) {
1293      }
1294    }
1295
1296    [TestMethod]
1297    [TestCategory("Persistence4")]
1298    [TestProperty("Time", "short")]
1299    public void TestSavingException() {
1300      ProtoBufSerializer serializer = new ProtoBufSerializer();
1301      List<int> list = new List<int> { 1, 2, 3 };
1302      serializer.Serialize(list, tempFile);
1303      NonSerializable s = new NonSerializable();
1304      try {
1305        serializer.Serialize(s, tempFile);
1306        Assert.Fail("Exception expected");
1307      } catch (PersistenceException) { }
1308      List<int> newList = (List<int>)serializer.Deserialize(tempFile);
1309      Assert.AreEqual(list[0], newList[0]);
1310      Assert.AreEqual(list[1], newList[1]);
1311    }
1312
1313    [TestMethod]
1314    [TestCategory("Persistence4")]
1315    [TestProperty("Time", "short")]
1316    public void TestTypeStringConversion() {
1317      string name = typeof(List<int>[]).AssemblyQualifiedName;
1318      string shortName =
1319        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
1320      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
1321      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
1322      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
1323    }
1324
1325    [TestMethod]
1326    [TestCategory("Persistence4")]
1327    [TestProperty("Time", "short")]
1328    public void TestHexadecimalPublicKeyToken() {
1329      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
1330      string shortName = "TestClass, TestAssembly";
1331      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
1332      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
1333    }
1334
1335    [TestMethod]
1336    [TestCategory("Persistence4")]
1337    [TestProperty("Time", "short")]
1338    public void InheritanceTest() {
1339      ProtoBufSerializer serializer = new ProtoBufSerializer();
1340      New n = new New();
1341      serializer.Serialize(n, tempFile);
1342      New nn = (New)serializer.Deserialize(tempFile);
1343      Assert.AreEqual(n.Name, nn.Name);
1344      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
1345    }
1346
1347    [StorableType("B963EF51-12B4-432E-8C54-88F026F9ACE2")]
1348    class Child {
1349      [Storable]
1350      public GrandParent grandParent;
1351    }
1352
1353    [StorableType("E66E9606-967A-4C35-A361-F6F0D21C064A")]
1354    class Parent {
1355      [Storable]
1356      public Child child;
1357    }
1358
1359    [StorableType("34D3893A-57AD-4F72-878B-81D6FA3F14A9")]
1360    class GrandParent {
1361      [Storable]
1362      public Parent parent;
1363    }
1364
1365    [TestMethod]
1366    [TestCategory("Persistence4")]
1367    [TestProperty("Time", "short")]
1368    public void InstantiateParentChainReference() {
1369      ProtoBufSerializer serializer = new ProtoBufSerializer();
1370      GrandParent gp = new GrandParent();
1371      gp.parent = new Parent();
1372      gp.parent.child = new Child();
1373      gp.parent.child.grandParent = gp;
1374      Assert.AreSame(gp, gp.parent.child.grandParent);
1375      serializer.Serialize(gp, tempFile);
1376      GrandParent newGp = (GrandParent)serializer.Deserialize(tempFile);
1377      Assert.AreSame(newGp, newGp.parent.child.grandParent);
1378    }
1379
1380    [StorableType("15DF777F-B12D-4FD4-88C3-8CB4C9CE4F0C")]
1381    struct TestStruct {
1382      int value;
1383      int PropertyValue { get; set; }
1384      public TestStruct(int value)
1385        : this() {
1386        this.value = value;
1387        PropertyValue = value;
1388      }
1389    }
1390
1391    [TestMethod]
1392    [TestCategory("Persistence4")]
1393    [TestProperty("Time", "short")]
1394    public void StructTest() {
1395      ProtoBufSerializer serializer = new ProtoBufSerializer();
1396      TestStruct s = new TestStruct(10);
1397      serializer.Serialize(s, tempFile);
1398      TestStruct newS = (TestStruct)serializer.Deserialize(tempFile);
1399      Assert.AreEqual(s, newS);
1400    }
1401
1402    [TestMethod]
1403    [TestCategory("Persistence4")]
1404    [TestProperty("Time", "short")]
1405    public void PointTest() {
1406      ProtoBufSerializer serializer = new ProtoBufSerializer();
1407      Point p = new Point(12, 34);
1408      serializer.Serialize(p, tempFile);
1409      Point newP = (Point)serializer.Deserialize(tempFile);
1410      Assert.AreEqual(p, newP);
1411    }
1412
1413    [TestMethod]
1414    [TestCategory("Persistence4")]
1415    [TestProperty("Time", "short")]
1416    public void NullableValueTypes() {
1417      ProtoBufSerializer serializer = new ProtoBufSerializer();
1418      double?[] d = new double?[] { null, 1, 2, 3 };
1419      serializer.Serialize(d, tempFile);
1420      double?[] newD = (double?[])serializer.Deserialize(tempFile);
1421      Assert.AreEqual(d[0], newD[0]);
1422      Assert.AreEqual(d[1], newD[1]);
1423      Assert.AreEqual(d[2], newD[2]);
1424      Assert.AreEqual(d[3], newD[3]);
1425    }
1426
1427    [TestMethod]
1428    [TestCategory("Persistence4")]
1429    [TestProperty("Time", "short")]
1430    public void BitmapTest() {
1431      ProtoBufSerializer serializer = new ProtoBufSerializer();
1432      Icon icon = System.Drawing.SystemIcons.Hand;
1433      Bitmap bitmap = icon.ToBitmap();
1434      serializer.Serialize(bitmap, tempFile);
1435      Bitmap newBitmap = (Bitmap)serializer.Deserialize(tempFile);
1436
1437      Assert.AreEqual(bitmap.Size, newBitmap.Size);
1438      for (int i = 0; i < bitmap.Size.Width; i++)
1439        for (int j = 0; j < bitmap.Size.Height; j++)
1440          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
1441    }
1442
1443    [StorableType("E846BC49-20F3-4D3F-A3F3-73D4F2DB1C2E")]
1444    private class PersistenceHooks {
1445      [Storable]
1446      public int a;
1447      [Storable]
1448      public int b;
1449      public int sum;
1450      public bool WasSerialized { get; private set; }
1451      [StorableHook(HookType.BeforeSerialization)]
1452      void PreSerializationHook() {
1453        WasSerialized = true;
1454      }
1455      [StorableHook(HookType.AfterDeserialization)]
1456      void PostDeserializationHook() {
1457        sum = a + b;
1458      }
1459    }
1460
1461    [TestMethod]
1462    [TestCategory("Persistence4")]
1463    [TestProperty("Time", "short")]
1464    public void HookTest() {
1465      ProtoBufSerializer serializer = new ProtoBufSerializer();
1466      PersistenceHooks hookTest = new PersistenceHooks();
1467      hookTest.a = 2;
1468      hookTest.b = 5;
1469      Assert.IsFalse(hookTest.WasSerialized);
1470      Assert.AreEqual(hookTest.sum, 0);
1471      serializer.Serialize(hookTest, tempFile);
1472      Assert.IsTrue(hookTest.WasSerialized);
1473      Assert.AreEqual(hookTest.sum, 0);
1474      PersistenceHooks newHookTest = (PersistenceHooks)serializer.Deserialize(tempFile);
1475      Assert.AreEqual(newHookTest.a, hookTest.a);
1476      Assert.AreEqual(newHookTest.b, hookTest.b);
1477      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
1478      Assert.IsFalse(newHookTest.WasSerialized);
1479    }
1480
1481    [StorableType("A35D71DF-397F-4910-A950-ED6923BE9483")]
1482    private class CustomConstructor {
1483      public string Value = "none";
1484      public CustomConstructor() {
1485        Value = "default";
1486      }
1487      [StorableConstructor]
1488      private CustomConstructor(StorableConstructorFlag 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      GeneticAlgorithm original = test();
2338      serializer.Serialize(original, tempFile);
2339      object o = serializer.Deserialize(tempFile);
2340
2341      // this fails because old persistence didn't handle all IComparer ?
2342      // Assert.AreEqual(DebugStringGenerator.Serialize(original),DebugStringGenerator.Serialize(o));
2343
2344      GeneticAlgorithm result = (GeneticAlgorithm)o;
2345      SamplesUtils.RunAlgorithm(result);
2346      SamplesUtils.RunAlgorithm(original);
2347      Assert.AreEqual(((DoubleValue)result.Results["BestQuality"].Value).Value,
2348        ((DoubleValue)original.Results["BestQuality"].Value).Value);
2349
2350      // Assert.AreEqual(DebugStringGenerator.Serialize(result), DebugStringGenerator.Serialize(result2));
2351    }
2352
2353    [TestMethod]
2354    [TestCategory("Persistence4")]
2355    [TestProperty("Time", "short")]
2356    public void TestLoadingSamples() {
2357      var path = @"D:\hl\branches\PersistenceReintegration\HeuristicLab.Optimizer\3.3\Documents";
2358      var serializer = new ProtoBufSerializer();
2359      foreach (var fileName in Directory.EnumerateFiles(path, "*.hl")) {
2360        var original = XmlParser.Deserialize(fileName);
2361        var ok = true;
2362        // foreach (var t in original.GetObjectGraphObjects().Select(o => o.GetType())) {
2363        //   if (
2364        //     t.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
2365        //       .Any(ctor => StorableConstructorAttribute.IsStorableConstructor(ctor))) {
2366        //     try {
2367        //       if (t.IsGenericType) {
2368        //         var g = Mapper.StaticCache.GetGuid(t.GetGenericTypeDefinition());
2369        //       } else {
2370        //         var g = Mapper.StaticCache.GetGuid(t);
2371        //       }
2372        //     } catch (Exception e) {
2373        //       Console.WriteLine(t.FullName);
2374        //       ok = false;
2375        //     }
2376        //   }
2377        // }
2378        if (ok) {
2379          serializer.Serialize(original, fileName + ".proto");
2380          // var newVersion = serializer.Deserialize(fileName + ".proto");
2381          var p = Profile(() => original);
2382          Console.WriteLine(p);
2383        }
2384      }
2385    }
2386  }
2387}
Note: See TracBrowser for help on using the repository browser.