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

Last change on this file since 14537 was 14537, checked in by jkarder, 4 years ago

#2520: worked on persistence

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