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

Last change on this file since 14549 was 14549, checked in by jkarder, 5 years ago

#2520: worked on persistence

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