Free cookie consent management tool by TermsFeed Policy Generator

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

Last change on this file since 15509 was 15509, checked in by jkarder, 6 years ago

#2520: worked on new persistence

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