Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PersistenceSpeedUp/HeuristicLab.Persistence/3.3/Tests/UseCases.cs @ 13831

Last change on this file since 13831 was 6760, checked in by epitzer, 13 years ago

#1530 integrate changes from trunk

File size: 42.6 KB
Line 
1#region License Information
2/* HeuristicLab
3 * Copyright (C) 2002-2011 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections;
24using System.Collections.Generic;
25using System.Drawing;
26using System.IO;
27using System.Linq;
28using System.Reflection;
29using System.Text;
30using System.Text.RegularExpressions;
31using HeuristicLab.Persistence.Auxiliary;
32using HeuristicLab.Persistence.Core;
33using HeuristicLab.Persistence.Core.Tokens;
34using HeuristicLab.Persistence.Default.CompositeSerializers;
35using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
36using HeuristicLab.Persistence.Default.DebugString;
37using HeuristicLab.Persistence.Default.Xml;
38using HeuristicLab.Persistence.Default.Xml.Primitive;
39using HeuristicLab.Persistence.Interfaces;
40using Microsoft.VisualStudio.TestTools.UnitTesting;
41using System.Threading.Tasks;
42using HeuristicLab.Algorithms.GeneticAlgorithm;
43
44namespace HeuristicLab.Persistence_33.Tests {
45
46  [StorableClass]
47  public class NumberTest {
48    [Storable]
49    private bool _bool = true;
50    [Storable]
51    private byte _byte = 0xFF;
52    [Storable]
53    private sbyte _sbyte = 0xF;
54    [Storable]
55    private short _short = -123;
56    [Storable]
57    private ushort _ushort = 123;
58    [Storable]
59    private int _int = -123;
60    [Storable]
61    private uint _uint = 123;
62    [Storable]
63    private long _long = 123456;
64    [Storable]
65    private ulong _ulong = 123456;
66    public override bool Equals(object obj) {
67      NumberTest nt = obj as NumberTest;
68      if (nt == null)
69        throw new NotSupportedException();
70      return
71        nt._bool == _bool &&
72        nt._byte == _byte &&
73        nt._sbyte == _sbyte &&
74        nt._short == _short &&
75        nt._ushort == _ushort &&
76        nt._int == _int &&
77        nt._uint == _uint &&
78        nt._long == _long &&
79        nt._ulong == _ulong;
80    }
81    public override int GetHashCode() {
82      return
83        _bool.GetHashCode() ^
84        _byte.GetHashCode() ^
85        _sbyte.GetHashCode() ^
86        _short.GetHashCode() ^
87        _short.GetHashCode() ^
88        _int.GetHashCode() ^
89        _uint.GetHashCode() ^
90        _long.GetHashCode() ^
91        _ulong.GetHashCode();
92    }
93  }
94
95  [StorableClass]
96  public class NonDefaultConstructorClass {
97    [Storable]
98    int value;
99    public NonDefaultConstructorClass(int value) {
100      this.value = value;
101    }
102  }
103
104  [StorableClass]
105  public class IntWrapper {
106
107    [Storable]
108    public int Value;
109
110    private IntWrapper() { }
111
112    public IntWrapper(int value) {
113      this.Value = value;
114    }
115
116    public override bool Equals(object obj) {
117      if (obj as IntWrapper == null)
118        return false;
119      return Value.Equals(((IntWrapper)obj).Value);
120    }
121    public override int GetHashCode() {
122      return Value.GetHashCode();
123    }
124
125  }
126
127  [StorableClass]
128  public class PrimitivesTest : NumberTest {
129    [Storable]
130    private char c = 'e';
131    [Storable]
132    private long[,] _long_array =
133      new long[,] { { 123, 456, }, { 789, 123 } };
134    [Storable]
135    public List<int> list = new List<int> { 1, 2, 3, 4, 5 };
136    [Storable]
137    private object o = new object();
138    public override bool Equals(object obj) {
139      PrimitivesTest pt = obj as PrimitivesTest;
140      if (pt == null)
141        throw new NotSupportedException();
142      return base.Equals(obj) &&
143        c == pt.c &&
144        _long_array == pt._long_array &&
145        list == pt.list &&
146        o == pt.o;
147    }
148    public override int GetHashCode() {
149      return base.GetHashCode() ^
150        c.GetHashCode() ^
151        _long_array.GetHashCode() ^
152        list.GetHashCode() ^
153        o.GetHashCode();
154    }
155  }
156
157  public enum TestEnum { va1, va2, va3, va8 } ;
158
159  [StorableClass]
160  public class RootBase {
161    [Storable]
162    private string baseString = "   Serial  ";
163    [Storable]
164    public TestEnum myEnum = TestEnum.va3;
165    public override bool Equals(object obj) {
166      RootBase rb = obj as RootBase;
167      if (rb == null)
168        throw new NotSupportedException();
169      return baseString == rb.baseString &&
170        myEnum == rb.myEnum;
171    }
172    public override int GetHashCode() {
173      return baseString.GetHashCode() ^
174        myEnum.GetHashCode();
175    }
176  }
177
178  [StorableClass]
179  public class Root : RootBase {
180    [Storable]
181    public Stack<int> intStack = new Stack<int>();
182    [Storable]
183    public int[] i = new[] { 3, 4, 5, 6 };
184    [Storable(Name = "Test String")]
185    public string s;
186    [Storable]
187    public ArrayList intArray = new ArrayList(new[] { 1, 2, 3 });
188    [Storable]
189    public List<int> intList = new List<int>(new[] { 321, 312, 321 });
190    [Storable]
191    public Custom c;
192    [Storable]
193    public List<Root> selfReferences;
194    [Storable]
195    public double[,] multiDimArray = new double[,] { { 1, 2, 3 }, { 3, 4, 5 } };
196    [Storable]
197    public bool boolean = true;
198    [Storable]
199    public DateTime dateTime;
200    [Storable]
201    public KeyValuePair<string, int> kvp = new KeyValuePair<string, int>("Serial", 123);
202    [Storable]
203    public Dictionary<string, int> dict = new Dictionary<string, int>();
204    [Storable(DefaultValue = "default")]
205    public string uninitialized;
206  }
207
208  public enum SimpleEnum { one, two, three }
209  public enum ComplexEnum { one = 1, two = 2, three = 3 }
210  [FlagsAttribute]
211  public enum TrickyEnum { zero = 0, one = 1, two = 2 }
212
213  [StorableClass]
214  public class EnumTest {
215    [Storable]
216    public SimpleEnum simpleEnum = SimpleEnum.one;
217    [Storable]
218    public ComplexEnum complexEnum = (ComplexEnum)2;
219    [Storable]
220    public TrickyEnum trickyEnum = (TrickyEnum)15;
221  }
222
223  [StorableClass]
224  public class Custom {
225    [Storable]
226    public int i;
227    [Storable]
228    public Root r;
229    [Storable]
230    public string name = "<![CDATA[<![CDATA[Serial]]>]]>";
231  }
232
233  [StorableClass]
234  public class Manager {
235
236    public DateTime lastLoadTime;
237    [Storable]
238    private DateTime lastLoadTimePersistence {
239      get { return lastLoadTime; }
240      set { lastLoadTime = DateTime.Now; }
241    }
242    [Storable]
243    public double? dbl;
244  }
245
246  [StorableClass]
247  public class C {
248    [Storable]
249    public C[][] allCs;
250    [Storable]
251    public KeyValuePair<List<C>, C> kvpList;
252  }
253
254  public class NonSerializable {
255    int x = 0;
256    public override bool Equals(object obj) {
257      NonSerializable ns = obj as NonSerializable;
258      if (ns == null)
259        throw new NotSupportedException();
260      return ns.x == x;
261    }
262    public override int GetHashCode() {
263      return x.GetHashCode();
264    }
265  }
266
267
268  [TestClass]
269  public class UseCases {
270
271    private string tempFile;
272
273    [TestInitialize()]
274    public void CreateTempFile() {
275      tempFile = Path.GetTempFileName();
276    }
277
278    [TestCleanup()]
279    public void ClearTempFile() {
280      StreamReader reader = new StreamReader(tempFile);
281      string s = reader.ReadToEnd();
282      reader.Close();
283      File.Delete(tempFile);
284    }
285
286    [TestMethod]
287    public void ComplexStorable() {
288      Root r = InitializeComplexStorable();
289      XmlGenerator.Serialize(r, tempFile);
290      Root newR = (Root)XmlParser.Deserialize(tempFile);
291      CompareComplexStorables(r, newR);
292    }
293
294    [TestMethod]
295    public void ComplexEasyStorable() {
296      Root r = InitializeComplexStorable();
297      ReadableXmlGenerator.Serialize(r, tempFile);
298      using (var reader = new StreamReader(tempFile)) {
299        string text = reader.ReadToEnd();
300        Assert.IsTrue(text.StartsWith("<Root"));
301      }
302    }
303
304    private static void CompareComplexStorables(Root r, Root newR) {
305      Assert.AreEqual(
306        DebugStringGenerator.Serialize(r),
307        DebugStringGenerator.Serialize(newR));
308      Assert.AreSame(newR, newR.selfReferences[0]);
309      Assert.AreNotSame(r, newR);
310      Assert.AreEqual(r.myEnum, TestEnum.va1);
311      Assert.AreEqual(r.i[0], 7);
312      Assert.AreEqual(r.i[1], 5);
313      Assert.AreEqual(r.i[2], 6);
314      Assert.AreEqual(r.s, "new value");
315      Assert.AreEqual(r.intArray[0], 3);
316      Assert.AreEqual(r.intArray[1], 2);
317      Assert.AreEqual(r.intArray[2], 1);
318      Assert.AreEqual(r.intList[0], 9);
319      Assert.AreEqual(r.intList[1], 8);
320      Assert.AreEqual(r.intList[2], 7);
321      Assert.AreEqual(r.multiDimArray[0, 0], 5);
322      Assert.AreEqual(r.multiDimArray[0, 1], 4);
323      Assert.AreEqual(r.multiDimArray[0, 2], 3);
324      Assert.AreEqual(r.multiDimArray[1, 0], 1);
325      Assert.AreEqual(r.multiDimArray[1, 1], 4);
326      Assert.AreEqual(r.multiDimArray[1, 2], 6);
327      Assert.IsFalse(r.boolean);
328      Assert.IsTrue((DateTime.Now - r.dateTime).TotalSeconds < 10);
329      Assert.AreEqual(r.kvp.Key, "string key");
330      Assert.AreEqual(r.kvp.Value, 321);
331      Assert.IsNull(r.uninitialized);
332      Assert.AreEqual(newR.myEnum, TestEnum.va1);
333      Assert.AreEqual(newR.i[0], 7);
334      Assert.AreEqual(newR.i[1], 5);
335      Assert.AreEqual(newR.i[2], 6);
336      Assert.AreEqual(newR.s, "new value");
337      Assert.AreEqual(newR.intArray[0], 3);
338      Assert.AreEqual(newR.intArray[1], 2);
339      Assert.AreEqual(newR.intArray[2], 1);
340      Assert.AreEqual(newR.intList[0], 9);
341      Assert.AreEqual(newR.intList[1], 8);
342      Assert.AreEqual(newR.intList[2], 7);
343      Assert.AreEqual(newR.multiDimArray[0, 0], 5);
344      Assert.AreEqual(newR.multiDimArray[0, 1], 4);
345      Assert.AreEqual(newR.multiDimArray[0, 2], 3);
346      Assert.AreEqual(newR.multiDimArray[1, 0], 1);
347      Assert.AreEqual(newR.multiDimArray[1, 1], 4);
348      Assert.AreEqual(newR.multiDimArray[1, 2], 6);
349      Assert.AreEqual(newR.intStack.Pop(), 3);
350      Assert.AreEqual(newR.intStack.Pop(), 2);
351      Assert.AreEqual(newR.intStack.Pop(), 1);
352      Assert.IsFalse(newR.boolean);
353      Assert.IsTrue((DateTime.Now - newR.dateTime).TotalSeconds < 10);
354      Assert.AreEqual(newR.kvp.Key, "string key");
355      Assert.AreEqual(newR.kvp.Value, 321);
356      Assert.IsNull(newR.uninitialized);
357    }
358
359    private static Root InitializeComplexStorable() {
360      Root r = new Root();
361      r.intStack.Push(1);
362      r.intStack.Push(2);
363      r.intStack.Push(3);
364      r.selfReferences = new List<Root> { r, r };
365      r.c = new Custom { r = r };
366      r.dict.Add("one", 1);
367      r.dict.Add("two", 2);
368      r.dict.Add("three", 3);
369      r.myEnum = TestEnum.va1;
370      r.i = new[] { 7, 5, 6 };
371      r.s = "new value";
372      r.intArray = new ArrayList { 3, 2, 1 };
373      r.intList = new List<int> { 9, 8, 7 };
374      r.multiDimArray = new double[,] { { 5, 4, 3 }, { 1, 4, 6 } };
375      r.boolean = false;
376      r.dateTime = DateTime.Now;
377      r.kvp = new KeyValuePair<string, int>("string key", 321);
378      r.uninitialized = null;
379
380      return r;
381    }
382
383    [TestMethod]
384    public void SelfReferences() {
385      C c = new C();
386      C[][] cs = new C[2][];
387      cs[0] = new C[] { c };
388      cs[1] = new C[] { c };
389      c.allCs = cs;
390      c.kvpList = new KeyValuePair<List<C>, C>(new List<C> { c }, c);
391      XmlGenerator.Serialize(cs, tempFile);
392      object o = XmlParser.Deserialize(tempFile);
393      Assert.AreEqual(
394        DebugStringGenerator.Serialize(cs),
395        DebugStringGenerator.Serialize(o));
396      Assert.AreSame(c, c.allCs[0][0]);
397      Assert.AreSame(c, c.allCs[1][0]);
398      Assert.AreSame(c, c.kvpList.Key[0]);
399      Assert.AreSame(c, c.kvpList.Value);
400      C[][] newCs = (C[][])o;
401      C newC = newCs[0][0];
402      Assert.AreSame(newC, newC.allCs[0][0]);
403      Assert.AreSame(newC, newC.allCs[1][0]);
404      Assert.AreSame(newC, newC.kvpList.Key[0]);
405      Assert.AreSame(newC, newC.kvpList.Value);
406    }
407
408    [TestMethod]
409    public void ArrayCreation() {
410      ArrayList[] arrayListArray = new ArrayList[4];
411      arrayListArray[0] = new ArrayList();
412      arrayListArray[0].Add(arrayListArray);
413      arrayListArray[0].Add(arrayListArray);
414      arrayListArray[1] = new ArrayList();
415      arrayListArray[1].Add(arrayListArray);
416      arrayListArray[2] = new ArrayList();
417      arrayListArray[2].Add(arrayListArray);
418      arrayListArray[2].Add(arrayListArray);
419      Array a = Array.CreateInstance(
420                              typeof(object),
421                              new[] { 1, 2 }, new[] { 3, 4 });
422      arrayListArray[2].Add(a);
423      XmlGenerator.Serialize(arrayListArray, tempFile);
424      object o = XmlParser.Deserialize(tempFile);
425      Assert.AreEqual(
426        DebugStringGenerator.Serialize(arrayListArray),
427        DebugStringGenerator.Serialize(o));
428      ArrayList[] newArray = (ArrayList[])o;
429      Assert.AreSame(arrayListArray, arrayListArray[0][0]);
430      Assert.AreSame(arrayListArray, arrayListArray[2][1]);
431      Assert.AreSame(newArray, newArray[0][0]);
432      Assert.AreSame(newArray, newArray[2][1]);
433    }
434
435    [TestMethod]
436    public void CustomSerializationProperty() {
437      Manager m = new Manager();
438      XmlGenerator.Serialize(m, tempFile);
439      Manager newM = (Manager)XmlParser.Deserialize(tempFile);
440      Assert.AreNotEqual(
441        DebugStringGenerator.Serialize(m),
442        DebugStringGenerator.Serialize(newM));
443      Assert.AreEqual(m.dbl, newM.dbl);
444      Assert.AreEqual(m.lastLoadTime, new DateTime());
445      Assert.AreNotEqual(newM.lastLoadTime, new DateTime());
446      Assert.IsTrue((DateTime.Now - newM.lastLoadTime).TotalSeconds < 10);
447    }
448
449    [TestMethod]
450    public void Primitives() {
451      PrimitivesTest sdt = new PrimitivesTest();
452      XmlGenerator.Serialize(sdt, tempFile);
453      object o = XmlParser.Deserialize(tempFile);
454      Assert.AreEqual(
455        DebugStringGenerator.Serialize(sdt),
456        DebugStringGenerator.Serialize(o));
457    }
458
459    [TestMethod]
460    public void MultiDimensionalArray() {
461      string[,] mDimString = new string[,] {
462        {"ora", "et", "labora"},
463        {"Beten", "und", "Arbeiten"}
464      };
465      XmlGenerator.Serialize(mDimString, tempFile);
466      object o = XmlParser.Deserialize(tempFile);
467      Assert.AreEqual(
468        DebugStringGenerator.Serialize(mDimString),
469        DebugStringGenerator.Serialize(o));
470    }
471
472    [StorableClass]
473    public class NestedType {
474      [Storable]
475      private string value = "value";
476      public override bool Equals(object obj) {
477        NestedType nt = obj as NestedType;
478        if (nt == null)
479          throw new NotSupportedException();
480        return nt.value == value;
481      }
482      public override int GetHashCode() {
483        return value.GetHashCode();
484      }
485    }
486
487    [TestMethod]
488    public void NestedTypeTest() {
489      NestedType t = new NestedType();
490      XmlGenerator.Serialize(t, tempFile);
491      object o = XmlParser.Deserialize(tempFile);
492      Assert.AreEqual(
493        DebugStringGenerator.Serialize(t),
494        DebugStringGenerator.Serialize(o));
495      Assert.IsTrue(t.Equals(o));
496    }
497
498
499    [TestMethod]
500    public void SimpleArray() {
501      string[] strings = { "ora", "et", "labora" };
502      XmlGenerator.Serialize(strings, tempFile);
503      object o = XmlParser.Deserialize(tempFile);
504      Assert.AreEqual(
505        DebugStringGenerator.Serialize(strings),
506        DebugStringGenerator.Serialize(o));
507    }
508
509    [TestMethod]
510    public void PrimitiveRoot() {
511      XmlGenerator.Serialize(12.3f, tempFile);
512      object o = XmlParser.Deserialize(tempFile);
513      Assert.AreEqual(
514        DebugStringGenerator.Serialize(12.3f),
515        DebugStringGenerator.Serialize(o));
516    }
517
518    private string formatFullMemberName(MemberInfo mi) {
519      return new StringBuilder()
520        .Append(mi.DeclaringType.Assembly.GetName().Name)
521        .Append(": ")
522        .Append(mi.DeclaringType.Namespace)
523        .Append('.')
524        .Append(mi.DeclaringType.Name)
525        .Append('.')
526        .Append(mi.Name).ToString();
527    }
528
529    [TestMethod]
530    public void CodingConventions() {
531      List<string> lowerCaseMethodNames = new List<string>();
532      List<string> lowerCaseProperties = new List<string>();
533      List<string> lowerCaseFields = new List<string>();
534      foreach (Assembly a in AppDomain.CurrentDomain.GetAssemblies()) {
535        if (!a.GetName().Name.StartsWith("HeuristicLab"))
536          continue;
537        foreach (Type t in a.GetTypes()) {
538          foreach (MemberInfo mi in t.GetMembers(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)) {
539            if (mi.DeclaringType.Name.StartsWith("<>"))
540              continue;
541            if (char.IsLower(mi.Name[0])) {
542              if (mi.MemberType == MemberTypes.Field)
543                lowerCaseFields.Add(formatFullMemberName(mi));
544              if (mi.MemberType == MemberTypes.Property)
545                lowerCaseProperties.Add(formatFullMemberName(mi));
546              if (mi.MemberType == MemberTypes.Method &&
547                !mi.Name.StartsWith("get_") &&
548                !mi.Name.StartsWith("set_") &&
549                !mi.Name.StartsWith("add_") &&
550                !mi.Name.StartsWith("remove_"))
551                lowerCaseMethodNames.Add(formatFullMemberName(mi));
552            }
553          }
554        }
555      }
556      //Assert.AreEqual("", lowerCaseFields.Aggregate("", (a, b) => a + "\r\n" + b));
557      Assert.AreEqual("", lowerCaseMethodNames.Aggregate("", (a, b) => a + "\r\n" + b));
558      Assert.AreEqual("", lowerCaseProperties.Aggregate("", (a, b) => a + "\r\n" + b));
559    }
560
561    [TestMethod]
562    public void Number2StringDecomposer() {
563      NumberTest sdt = new NumberTest();
564      XmlGenerator.Serialize(sdt, tempFile,
565        new Configuration(new XmlFormat(),
566          new List<IPrimitiveSerializer> { new String2XmlSerializer() },
567          new List<ICompositeSerializer> {
568            new StorableSerializer(),
569            new Number2StringSerializer() }));
570      object o = XmlParser.Deserialize(tempFile);
571      Assert.AreEqual(
572        DebugStringGenerator.Serialize(sdt),
573        DebugStringGenerator.Serialize(o));
574      Assert.IsTrue(sdt.Equals(o));
575    }
576
577    [TestMethod]
578    public void Enums() {
579      EnumTest et = new EnumTest();
580      et.simpleEnum = SimpleEnum.two;
581      et.complexEnum = ComplexEnum.three;
582      et.trickyEnum = TrickyEnum.two | TrickyEnum.one;
583      XmlGenerator.Serialize(et, tempFile);
584      EnumTest newEt = (EnumTest)XmlParser.Deserialize(tempFile);
585      Assert.AreEqual(et.simpleEnum, SimpleEnum.two);
586      Assert.AreEqual(et.complexEnum, ComplexEnum.three);
587      Assert.AreEqual(et.trickyEnum, (TrickyEnum)3);
588    }
589
590    [TestMethod]
591    public void TestAliasingWithOverriddenEquals() {
592      List<IntWrapper> ints = new List<IntWrapper>();
593      ints.Add(new IntWrapper(1));
594      ints.Add(new IntWrapper(1));
595      Assert.AreEqual(ints[0], ints[1]);
596      Assert.AreNotSame(ints[0], ints[1]);
597      XmlGenerator.Serialize(ints, tempFile);
598      List<IntWrapper> newInts = (List<IntWrapper>)XmlParser.Deserialize(tempFile);
599      Assert.AreEqual(newInts[0].Value, 1);
600      Assert.AreEqual(newInts[1].Value, 1);
601      Assert.AreEqual(newInts[0], newInts[1]);
602      Assert.AreNotSame(newInts[0], newInts[1]);
603    }
604
605    [TestMethod]
606    public void NonDefaultConstructorTest() {
607      NonDefaultConstructorClass c = new NonDefaultConstructorClass(1);
608      try {
609        XmlGenerator.Serialize(c, tempFile);
610        Assert.Fail("Exception not thrown");
611      } catch (PersistenceException) {
612      }
613    }
614
615    [TestMethod]
616    public void TestSavingException() {
617      List<int> list = new List<int> { 1, 2, 3 };
618      XmlGenerator.Serialize(list, tempFile);
619      NonSerializable s = new NonSerializable();
620      try {
621        XmlGenerator.Serialize(s, tempFile);
622        Assert.Fail("Exception expected");
623      } catch (PersistenceException) { }
624      List<int> newList = (List<int>)XmlParser.Deserialize(tempFile);
625      Assert.AreEqual(list[0], newList[0]);
626      Assert.AreEqual(list[1], newList[1]);
627    }
628
629    [TestMethod]
630    public void TestTypeStringConversion() {
631      string name = typeof(List<int>[]).AssemblyQualifiedName;
632      string shortName =
633        "System.Collections.Generic.List`1[[System.Int32, mscorlib]][], mscorlib";
634      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
635      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
636      Assert.AreEqual(shortName, typeof(List<int>[]).VersionInvariantName());
637    }
638
639    [TestMethod]
640    public void TestHexadecimalPublicKeyToken() {
641      string name = "TestClass, TestAssembly, Version=1.2.3.4, PublicKey=1234abc";
642      string shortName = "TestClass, TestAssembly";
643      Assert.AreEqual(name, TypeNameParser.Parse(name).ToString());
644      Assert.AreEqual(shortName, TypeNameParser.Parse(name).ToString(false));
645    }
646
647    [TestMethod]
648    public void TestMultipleFailure() {
649      List<NonSerializable> l = new List<NonSerializable>();
650      l.Add(new NonSerializable());
651      l.Add(new NonSerializable());
652      l.Add(new NonSerializable());
653      try {
654        Serializer s = new Serializer(l,
655          ConfigurationService.Instance.GetConfiguration(new XmlFormat()),
656          "ROOT", true);
657        StringBuilder tokens = new StringBuilder();
658        foreach (var token in s) {
659          tokens.Append(token.ToString());
660        }
661        Assert.Fail("Exception expected");
662      } catch (PersistenceException px) {
663        Assert.AreEqual(3, px.Data.Count);
664      }
665    }
666
667    [TestMethod]
668    public void TestAssemblyVersionCheck() {
669      IntWrapper i = new IntWrapper(1);
670      Serializer s = new Serializer(i, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
671      XmlGenerator g = new XmlGenerator();
672      StringBuilder dataString = new StringBuilder();
673      foreach (var token in s) {
674        dataString.Append(g.Format(token));
675      }
676      StringBuilder typeString = new StringBuilder();
677      foreach (var line in g.Format(s.TypeCache))
678        typeString.Append(line);
679      Deserializer d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(typeString.ToString())));
680      XmlParser p = new XmlParser(new StringReader(dataString.ToString()));
681      IntWrapper newI = (IntWrapper)d.Deserialize(p);
682      Assert.AreEqual(i.Value, newI.Value);
683
684      string newTypeString = Regex.Replace(typeString.ToString(),
685        "Version=\\d+\\.\\d+\\.\\d+\\.\\d+",
686        "Version=0.0.9999.9999");
687      try {
688        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
689        Assert.Fail("Exception expected");
690      } catch (PersistenceException x) {
691        Assert.IsTrue(x.Message.Contains("incompatible"));
692      }
693      newTypeString = Regex.Replace(typeString.ToString(),
694        "Version=(\\d+\\.\\d+)\\.\\d+\\.\\d+",
695        "Version=$1.9999.9999");
696      try {
697        d = new Deserializer(XmlParser.ParseTypeCache(new StringReader(newTypeString)));
698        Assert.Fail("Exception expected");
699      } catch (PersistenceException x) {
700        Assert.IsTrue(x.Message.Contains("newer"));
701      }
702    }
703
704    [TestMethod]
705    public void InheritanceTest() {
706      New n = new New();
707      XmlGenerator.Serialize(n, tempFile);
708      New nn = (New)XmlParser.Deserialize(tempFile);
709      Assert.AreEqual(n.Name, nn.Name);
710      Assert.AreEqual(((Override)n).Name, ((Override)nn).Name);
711    }
712
713    [StorableClass]
714    class Child {
715      [Storable]
716      public GrandParent grandParent;
717    }
718
719    [StorableClass]
720    class Parent {
721      [Storable]
722      public Child child;
723    }
724
725    [StorableClass]
726    class GrandParent {
727      [Storable]
728      public Parent parent;
729    }
730
731    [TestMethod]
732    public void InstantiateParentChainReference() {
733      GrandParent gp = new GrandParent();
734      gp.parent = new Parent();
735      gp.parent.child = new Child();
736      gp.parent.child.grandParent = gp;
737      Assert.AreSame(gp, gp.parent.child.grandParent);
738      XmlGenerator.Serialize(gp, tempFile);
739      GrandParent newGp = (GrandParent)XmlParser.Deserialize(tempFile);
740      Assert.AreSame(newGp, newGp.parent.child.grandParent);
741    }
742
743    struct TestStruct {
744      int value;
745      int PropertyValue { get; set; }
746      public TestStruct(int value)
747        : this() {
748        this.value = value;
749        PropertyValue = value;
750      }
751    }
752
753    [TestMethod]
754    public void StructTest() {
755      TestStruct s = new TestStruct(10);
756      XmlGenerator.Serialize(s, tempFile);
757      TestStruct newS = (TestStruct)XmlParser.Deserialize(tempFile);
758      Assert.AreEqual(s, newS);
759    }
760
761    [TestMethod]
762    public void PointTest() {
763      Point p = new Point(12, 34);
764      XmlGenerator.Serialize(p, tempFile);
765      Point newP = (Point)XmlParser.Deserialize(tempFile);
766      Assert.AreEqual(p, newP);
767    }
768
769    [TestMethod]
770    public void NullableValueTypes() {
771      double?[] d = new double?[] { null, 1, 2, 3 };
772      XmlGenerator.Serialize(d, tempFile);
773      double?[] newD = (double?[])XmlParser.Deserialize(tempFile);
774      Assert.AreEqual(d[0], newD[0]);
775      Assert.AreEqual(d[1], newD[1]);
776      Assert.AreEqual(d[2], newD[2]);
777      Assert.AreEqual(d[3], newD[3]);
778    }
779
780    [TestMethod]
781    public void BitmapTest() {
782      Icon icon = System.Drawing.SystemIcons.Hand;
783      Bitmap bitmap = icon.ToBitmap();
784      XmlGenerator.Serialize(bitmap, tempFile);
785      Bitmap newBitmap = (Bitmap)XmlParser.Deserialize(tempFile);
786
787      Assert.AreEqual(bitmap.Size, newBitmap.Size);
788      for (int i = 0; i < bitmap.Size.Width; i++)
789        for (int j = 0; j < bitmap.Size.Height; j++)
790          Assert.AreEqual(bitmap.GetPixel(i, j), newBitmap.GetPixel(i, j));
791    }
792
793    [StorableClass]
794    private class PersistenceHooks {
795      [Storable]
796      public int a;
797      [Storable]
798      public int b;
799      public int sum;
800      public bool WasSerialized { get; private set; }
801      [StorableHook(HookType.BeforeSerialization)]
802      void BeforeSerialization() {
803        WasSerialized = true;
804      }
805      [StorableHook(HookType.AfterDeserialization)]
806      void AfterDeserialization() {
807        sum = a + b;
808      }
809    }
810
811    [TestMethod]
812    public void HookTest() {
813      PersistenceHooks hookTest = new PersistenceHooks();
814      hookTest.a = 2;
815      hookTest.b = 5;
816      Assert.IsFalse(hookTest.WasSerialized);
817      Assert.AreEqual(hookTest.sum, 0);
818      XmlGenerator.Serialize(hookTest, tempFile);
819      Assert.IsTrue(hookTest.WasSerialized);
820      Assert.AreEqual(hookTest.sum, 0);
821      PersistenceHooks newHookTest = (PersistenceHooks)XmlParser.Deserialize(tempFile);
822      Assert.AreEqual(newHookTest.a, hookTest.a);
823      Assert.AreEqual(newHookTest.b, hookTest.b);
824      Assert.AreEqual(newHookTest.sum, newHookTest.a + newHookTest.b);
825      Assert.IsFalse(newHookTest.WasSerialized);
826    }
827
828    [StorableClass]
829    private class CustomConstructor {
830      public string Value = "none";
831      public CustomConstructor() {
832        Value = "default";
833      }
834      [StorableConstructor]
835      private CustomConstructor(bool deserializing) {
836        Assert.IsTrue(deserializing);
837        Value = "persistence";
838      }
839    }
840
841    [TestMethod]
842    public void TestCustomConstructor() {
843      CustomConstructor cc = new CustomConstructor();
844      Assert.AreEqual(cc.Value, "default");
845      XmlGenerator.Serialize(cc, tempFile);
846      CustomConstructor newCC = (CustomConstructor)XmlParser.Deserialize(tempFile);
847      Assert.AreEqual(newCC.Value, "persistence");
848    }
849
850    [StorableClass]
851    public class ExplodingDefaultConstructor {
852      public ExplodingDefaultConstructor() {
853        throw new Exception("this constructor will always fail");
854      }
855      public ExplodingDefaultConstructor(string password) {
856      }
857    }
858
859    [TestMethod]
860    public void TestConstructorExceptionUnwrapping() {
861      ExplodingDefaultConstructor x = new ExplodingDefaultConstructor("password");
862      XmlGenerator.Serialize(x, tempFile);
863      try {
864        ExplodingDefaultConstructor newX = (ExplodingDefaultConstructor)XmlParser.Deserialize(tempFile);
865        Assert.Fail("Exception expected");
866      } catch (PersistenceException pe) {
867        Assert.AreEqual("this constructor will always fail", pe.InnerException.Message);
868      }
869    }
870
871    [TestMethod]
872    public void TestRejectionJustifications() {
873      NonSerializable ns = new NonSerializable();
874      try {
875        XmlGenerator.Serialize(ns, tempFile);
876        Assert.Fail("PersistenceException expected");
877      } catch (PersistenceException x) {
878        Assert.IsTrue(x.Message.Contains(new StorableSerializer().JustifyRejection(typeof(NonSerializable))));
879      }
880    }
881
882    [TestMethod]
883    public void TestStreaming() {
884      using (MemoryStream stream = new MemoryStream()) {
885        Root r = InitializeComplexStorable();
886        XmlGenerator.Serialize(r, stream);
887        using (MemoryStream stream2 = new MemoryStream(stream.ToArray())) {
888          Root newR = (Root)XmlParser.Deserialize(stream2);
889          CompareComplexStorables(r, newR);
890        }
891      }
892    }
893
894    [StorableClass]
895    public class HookInheritanceTestBase {
896      [Storable]
897      public object a;
898      public object link;
899      [StorableHook(HookType.AfterDeserialization)]
900      private void AfterDeserialization() {
901        link = a;
902      }
903    }
904
905    [StorableClass]
906    public class HookInheritanceTestDerivedClass : HookInheritanceTestBase {
907      [Storable]
908      public object b;
909      [StorableHook(HookType.AfterDeserialization)]
910      private void AfterDeserialization() {
911        Assert.AreSame(a, link);
912        link = b;
913      }
914    }
915
916    [TestMethod]
917    public void TestLinkInheritance() {
918      HookInheritanceTestDerivedClass c = new HookInheritanceTestDerivedClass();
919      c.a = new object();
920      XmlGenerator.Serialize(c, tempFile);
921      HookInheritanceTestDerivedClass newC = (HookInheritanceTestDerivedClass)XmlParser.Deserialize(tempFile);
922      Assert.AreSame(c.b, c.link);
923    }
924
925
926    [StorableClass]
927    public class MarkedOnlyStorable {
928      public int Value1 = 1;
929      [Storable]
930      public int Value2 = 2;
931      public int Value3 { get; private set; }
932      public int Value4 { get; private set; }
933      [StorableConstructor]
934      public MarkedOnlyStorable(bool isDeserializing) {
935        if (!isDeserializing) {
936          Value1 = 12;
937          Value2 = 23;
938          Value3 = 34;
939          Value4 = 56;
940        }
941      }
942    }
943
944    [TestMethod]
945    public void TestStorableClassDiscoveryMarkedOnly() {
946      MarkedOnlyStorable afs = new MarkedOnlyStorable(false);
947      XmlGenerator.Serialize(afs, tempFile);
948      MarkedOnlyStorable newAfs = (MarkedOnlyStorable)XmlParser.Deserialize(tempFile);
949      Assert.AreEqual(1, newAfs.Value1);
950      Assert.AreEqual(afs.Value2, newAfs.Value2);
951      Assert.AreEqual(0, newAfs.Value3);
952      Assert.AreEqual(0, newAfs.Value4);
953    }
954
955    [TestMethod]
956    public void TestLineEndings() {
957      List<string> lineBreaks = new List<string> { "\r\n", "\n", "\r", "\n\r", Environment.NewLine };
958      List<string> lines = new List<string>();
959      foreach (var br in lineBreaks)
960        lines.Add("line1" + br + "line2");
961      XmlGenerator.Serialize(lines, tempFile);
962      List<string> newLines = XmlParser.Deserialize<List<string>>(tempFile);
963      Assert.AreEqual(lines.Count, newLines.Count);
964      for (int i = 0; i < lineBreaks.Count; i++) {
965        Assert.AreEqual(lines[i], newLines[i]);
966      }
967    }
968
969    [TestMethod]
970    public void TestSpecialNumbers() {
971      List<double> specials = new List<double>() { 1.0 / 0, -1.0 / 0, 0.0 / 0 };
972      Assert.IsTrue(double.IsPositiveInfinity(specials[0]));
973      Assert.IsTrue(double.IsNegativeInfinity(specials[1]));
974      Assert.IsTrue(double.IsNaN(specials[2]));
975      XmlGenerator.Serialize(specials, tempFile);
976      List<double> newSpecials = XmlParser.Deserialize<List<double>>(tempFile);
977      Assert.IsTrue(double.IsPositiveInfinity(newSpecials[0]));
978      Assert.IsTrue(double.IsNegativeInfinity(newSpecials[1]));
979      Assert.IsTrue(double.IsNaN(newSpecials[2]));
980    }
981
982    [TestMethod]
983    public void TestStringSplit() {
984      string s = "1.2;2.3;3.4;;;4.9";
985      var l = s.EnumerateSplit(';').ToList();
986      Assert.AreEqual("1.2", l[0]);
987      Assert.AreEqual("2.3", l[1]);
988      Assert.AreEqual("3.4", l[2]);
989      Assert.AreEqual("4.9", l[3]);
990    }
991
992    [TestMethod]
993    public void TestCompactNumberArraySerializer() {
994      Random r = new Random();
995      double[] a = new double[CompactNumberArray2StringSerializer.SPLIT_THRESHOLD * 2 + 1];
996      for (int i = 0; i < a.Length; i++)
997        a[i] = r.Next(10);
998      var config = ConfigurationService.Instance.GetDefaultConfig(new XmlFormat());
999      config = new Configuration(config.Format,
1000        config.PrimitiveSerializers.Where(s => s.SourceType != typeof(double[])),
1001        config.CompositeSerializers);
1002      XmlGenerator.Serialize(a, tempFile, config);
1003      double[] newA = XmlParser.Deserialize<double[]>(tempFile);
1004      Assert.AreEqual(a.Length, newA.Length);
1005      for (int i = 0; i < a.Rank; i++) {
1006        Assert.AreEqual(a.GetLength(i), newA.GetLength(i));
1007        Assert.AreEqual(a.GetLowerBound(i), newA.GetLowerBound(i));
1008      }
1009      for (int i = 0; i < a.Length; i++) {
1010        Assert.AreEqual(a[i], newA[i]);
1011      }
1012    }
1013    private class IdentityComparer<T> : IEqualityComparer<T> {
1014
1015      public bool Equals(T x, T y) {
1016        return x.Equals(y);
1017      }
1018
1019      public int GetHashCode(T obj) {
1020        return obj.GetHashCode();
1021      }
1022    }
1023
1024    [TestMethod]
1025    public void TestHashSetSerializer() {
1026      var hashSets = new List<HashSet<int>>() {
1027        new HashSet<int>(new[] { 1, 2, 3 }),
1028        new HashSet<int>(new[] { 4, 5, 6 }, new IdentityComparer<int>()),
1029      };
1030      XmlGenerator.Serialize(hashSets, tempFile);
1031      var newHashSets = XmlParser.Deserialize<List<HashSet<int>>>(tempFile);
1032      Assert.IsTrue(newHashSets[0].Contains(1));
1033      Assert.IsTrue(newHashSets[0].Contains(2));
1034      Assert.IsTrue(newHashSets[0].Contains(3));
1035      Assert.IsTrue(newHashSets[1].Contains(4));
1036      Assert.IsTrue(newHashSets[1].Contains(5));
1037      Assert.IsTrue(newHashSets[1].Contains(6));
1038      Assert.AreEqual(newHashSets[0].Comparer.GetType(), new HashSet<int>().Comparer.GetType());
1039      Assert.AreEqual(newHashSets[1].Comparer.GetType(), typeof(IdentityComparer<int>));
1040    }
1041
1042    [TestMethod]
1043    public void TestConcreteDictionarySerializer() {
1044      var dictionaries = new List<Dictionary<int, int>>() {
1045        new Dictionary<int, int>(),
1046        new Dictionary<int, int>(new IdentityComparer<int>()),
1047      };
1048      dictionaries[0].Add(1, 1);
1049      dictionaries[0].Add(2, 2);
1050      dictionaries[0].Add(3, 3);
1051      dictionaries[1].Add(4, 4);
1052      dictionaries[1].Add(5, 5);
1053      dictionaries[1].Add(6, 6);
1054      XmlGenerator.Serialize(dictionaries, tempFile, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1055      var newDictionaries = XmlParser.Deserialize<List<Dictionary<int, int>>>(tempFile);
1056      Assert.IsTrue(newDictionaries[0].ContainsKey(1));
1057      Assert.IsTrue(newDictionaries[0].ContainsKey(2));
1058      Assert.IsTrue(newDictionaries[0].ContainsKey(3));
1059      Assert.IsTrue(newDictionaries[1].ContainsKey(4));
1060      Assert.IsTrue(newDictionaries[1].ContainsKey(5));
1061      Assert.IsTrue(newDictionaries[1].ContainsKey(6));
1062      Assert.IsTrue(newDictionaries[0].ContainsValue(1));
1063      Assert.IsTrue(newDictionaries[0].ContainsValue(2));
1064      Assert.IsTrue(newDictionaries[0].ContainsValue(3));
1065      Assert.IsTrue(newDictionaries[1].ContainsValue(4));
1066      Assert.IsTrue(newDictionaries[1].ContainsValue(5));
1067      Assert.IsTrue(newDictionaries[1].ContainsValue(6));
1068      Assert.AreEqual(new Dictionary<int, int>().Comparer.GetType(), newDictionaries[0].Comparer.GetType());
1069      Assert.AreEqual(typeof(IdentityComparer<int>), newDictionaries[1].Comparer.GetType());
1070    }
1071
1072    [StorableClass]
1073    public class ReadOnlyFail {
1074      [Storable]
1075      public string ReadOnly {
1076        get { return "fail"; }
1077      }
1078    }
1079
1080    [TestMethod]
1081    public void TestReadOnlyFail() {
1082      try {
1083        XmlGenerator.Serialize(new ReadOnlyFail(), tempFile);
1084        Assert.Fail("Exception expected");
1085      } catch (PersistenceException) {
1086      } catch {
1087        Assert.Fail("PersistenceException expected");
1088      }
1089    }
1090
1091
1092    [StorableClass]
1093    public class WriteOnlyFail {
1094      [Storable]
1095      public string WriteOnly {
1096        set { throw new InvalidOperationException("this property should never be set."); }
1097      }
1098    }
1099
1100    [TestMethod]
1101    public void TestWriteOnlyFail() {
1102      try {
1103        XmlGenerator.Serialize(new WriteOnlyFail(), tempFile);
1104        Assert.Fail("Exception expected");
1105      } catch (PersistenceException) {
1106      } catch {
1107        Assert.Fail("PersistenceException expected.");
1108      }
1109    }
1110
1111    [StorableClass]
1112    public class OneWayTest {
1113      public OneWayTest() { this.value = "default"; }
1114      public string value;
1115      [Storable(AllowOneWay = true)]
1116      public string ReadOnly {
1117        get { return "ReadOnly"; }
1118      }
1119      [Storable(AllowOneWay = true)]
1120      public string WriteOnly {
1121        set { this.value = value; }
1122      }
1123    }
1124
1125    [TestMethod]
1126    public void TestOneWaySerialization() {
1127      var test = new OneWayTest();
1128      var serializer = new Serializer(test, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1129      var it = serializer.GetEnumerator();
1130      it.MoveNext();
1131      Assert.AreEqual("ROOT", ((BeginToken)it.Current).Name); it.MoveNext();
1132      Assert.AreEqual("ReadOnly", ((PrimitiveToken)it.Current).Name); it.MoveNext();
1133      ReverseTypeCache typeCache = new ReverseTypeCache();
1134      typeCache.AddType(0, typeof(OneWayTest));
1135      typeCache.AddSerializer(0, typeof(StorableSerializer));
1136      typeCache.AddType(1, typeof(string));
1137      typeCache.AddSerializer(1, typeof(String2XmlSerializer));
1138      var deserializer = new Deserializer(typeCache);
1139      var newTest = (OneWayTest)deserializer.Deserialize(new ISerializationToken[] {
1140        new BeginToken("ROOT", 0, 0),
1141        new PrimitiveToken("WriteOnly", 1, 1, new XmlString("<![CDATA[serial data]]>")),
1142        new EndToken()
1143      });
1144      Assert.AreEqual("serial data", newTest.value);
1145    }
1146
1147    [TestMethod]
1148    public void TestTypeCacheExport() {
1149      var test = new List<List<int>>();
1150      test.Add(new List<int>() { 1, 2, 3 });
1151      IEnumerable<Type> types;
1152      using (var stream = new MemoryStream()) {
1153        XmlGenerator.Serialize(test, stream, ConfigurationService.Instance.GetConfiguration(new XmlFormat()), false, out types);
1154      }
1155      List<Type> t = new List<Type>(types);
1156      // Assert.IsTrue(t.Contains(typeof(int))); not serialized as an int list is directly transformed into a string
1157      Assert.IsTrue(t.Contains(typeof(List<int>)));
1158      Assert.IsTrue(t.Contains(typeof(List<List<int>>)));
1159      Assert.AreEqual(t.Count, 2);
1160    }
1161
1162    [TestMethod]
1163    public void TupleTest() {
1164      var t1 = Tuple.Create(1);
1165      var t2 = Tuple.Create('1', "2");
1166      var t3 = Tuple.Create(3.0, 3f, 5);
1167      var t4 = Tuple.Create(Tuple.Create(1, 2, 3), Tuple.Create(4, 5, 6), Tuple.Create(8, 9, 10));
1168      var tuple = Tuple.Create(t1, t2, t3, t4);
1169      XmlGenerator.Serialize(tuple, tempFile);
1170      var newTuple = XmlParser.Deserialize<Tuple<Tuple<int>, Tuple<char, string>, Tuple<double, float, int>, Tuple<Tuple<int, int, int>, Tuple<int, int, int>, Tuple<int, int, int>>>>(tempFile);
1171      Assert.AreEqual(tuple, newTuple);
1172    }
1173
1174    [TestMethod]
1175    public void TestCachedTypeSerializer() {
1176      List<Type> types = new List<Type> { typeof(object), typeof(UseCases), typeof(XmlGenerator) };
1177      var s = new Serializer(types, ConfigurationService.Instance.GetDefaultConfig(new XmlFormat()));
1178      var tokens = s.ToList();
1179      foreach (var type in types)
1180        Assert.IsTrue(s.SerializedTypes.Contains(type));
1181      var d = new Deserializer(s.TypeCache.Reverse());
1182      var newTypes = (List<Type>)d.Deserialize(tokens);
1183      for (int i = 0; i < types.Count; i++)
1184        Assert.AreEqual(types[i], newTypes[i]);
1185    }
1186
1187    [TestMethod]
1188    public void FontTest() {
1189      List<Font> fonts = new List<Font>() {
1190        new Font(FontFamily.GenericSansSerif, 12),
1191        new Font("Times New Roman", 21, FontStyle.Bold, GraphicsUnit.Pixel),
1192        new Font("Courier New", 10, FontStyle.Underline, GraphicsUnit.Document),
1193        new Font("Helvetica", 21, FontStyle.Strikeout, GraphicsUnit.Inch, 0, true),
1194      };
1195      XmlGenerator.Serialize(fonts, tempFile);
1196      var newFonts = XmlParser.Deserialize<List<Font>>(tempFile);
1197      Assert.AreEqual(fonts[0], newFonts[0]);
1198      Assert.AreEqual(fonts[1], newFonts[1]);
1199      Assert.AreEqual(fonts[2], newFonts[2]);
1200      Assert.AreEqual(fonts[3], newFonts[3]);
1201    }
1202
1203    [TestMethod]
1204    public void ConcurrencyTest() {
1205      int n = 20;
1206      Task[] tasks = new Task[n];
1207      for (int i = 0; i < n; i++) {
1208        tasks[i] = Task.Factory.StartNew((idx) => {
1209          byte[] data;
1210          using(var stream = new MemoryStream()) {
1211            XmlGenerator.Serialize(new GeneticAlgorithm(), stream);
1212            data = stream.ToArray();
1213          }
1214        }, i);
1215      }
1216      Task.WaitAll(tasks);
1217    }
1218
1219    [TestMethod]
1220    public void ConcurrentBitmapTest() {
1221      Bitmap b = new Bitmap(300, 300);
1222      Random r = new Random();
1223      for (int x = 0; x<b.Height; x++) {
1224        for (int y = 0; y<b.Width; y++) {
1225          b.SetPixel(x, y, Color.FromArgb(r.Next()));
1226        }
1227      }
1228      Task[] tasks = new Task[20];
1229      byte[][] datas = new byte[tasks.Length][];
1230      for (int i = 0; i<tasks.Length; i++) {
1231        tasks[i] = Task.Factory.StartNew((idx) => {
1232          using (var stream = new MemoryStream()) {
1233            XmlGenerator.Serialize(b, stream);
1234            datas[(int)idx] = stream.ToArray();
1235          }
1236        }, i);
1237      }
1238      Task.WaitAll(tasks);
1239    }
1240
1241    [ClassInitialize]
1242    public static void Initialize(TestContext testContext) {
1243      ConfigurationService.Instance.Reset();
1244    }
1245  }
1246}
Note: See TracBrowser for help on using the repository browser.