Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2520

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