convert ArrayList to array only in case of DeserializeObject()
[mono.git] / mcs / class / System.Web.Extensions / Test / System.Web.Script.Serialization / JavaScriptSerializerTest.cs
1 //
2 // JavaScriptSerializer.cs
3 //
4 // Author:
5 //   Konstantin Triger <kostat@mainsoft.com>
6 //
7 // (C) 2007 Mainsoft, Inc.  http://www.mainsoft.com
8 //
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.Collections.Generic;
32 using System.Text;
33 using NUnit.Framework;
34 using System.Web.Script.Serialization;
35 using System.Reflection;
36 using System.Collections;
37 using System.Drawing;
38 using ComponentModel = System.ComponentModel;
39 using System.Globalization;
40 using System.Threading;
41 using System.Text.RegularExpressions;
42 using System.ComponentModel;
43 using CategoryAttribute = NUnit.Framework.CategoryAttribute;
44 using System.Web.UI.WebControls;
45 using System.Collections.ObjectModel;
46
47
48 namespace Tests.System.Web.Script.Serialization
49 {
50         [TestFixture]
51         public class JavaScriptSerializerTest
52         {
53                 enum MyEnum
54                 {
55                         AAA,
56                         BBB,
57                         CCC
58                 }
59 #pragma warning disable 659
60                 class bug
61                 {
62                         //public DateTime dt;
63                         //public DateTime dt1;
64                         //public DateTime dt2;
65                         public bool bb;
66                         //Hashtable hash;
67
68                         public void Init() {
69                                 //dt = DateTime.MaxValue;
70                                 //dt1 = DateTime.MinValue;
71                                 //dt2 = new DateTime ((DateTime.Now.Ticks / 10000) * 10000);
72                                 bb = true;
73                                 //hash = new Hashtable ();
74                                 //hash.Add ("mykey", 1);
75                         }
76
77                         public override bool Equals (object obj) {
78                                 if (!(obj is bug))
79                                         return false;
80                                 JavaScriptSerializerTest.FieldsEqual (this, obj);
81                                 return true;
82                         }
83                 }
84                 class X
85                 {
86                         int x = 5;
87                         //int y;
88                         ulong _bb;
89                         Y[] _yy;
90                         Y [] _yyy = new Y [] { new Y (), new Y () };
91                         public int z;
92                         public char ch;
93                         public char ch_null;
94                         public string str;
95                         public byte b;
96                         public sbyte sb;
97                         public short sh;
98                         public ushort ush;
99                         public int i;
100                         public uint ui;
101                         public long l;
102                         public ulong ul;
103                         
104                         public float f;
105                         public float f1;
106                         public float f2;
107                         public float f3;
108                         public float f4;
109
110                         public double d;
111                         public double d1;
112                         public double d2;
113                         public double d3;
114                         public double d4;
115
116                         public decimal de;
117                         public decimal de1;
118                         public decimal de2;
119                         public decimal de3;
120                         public decimal de4;
121
122                         
123
124                         public Guid g;
125                         
126                         public Nullable<bool> nb;
127                         public DBNull dbn;
128                         IEnumerable<int> enum_int;
129                         IEnumerable enum_int1;
130                         public Uri uri;
131                         public Dictionary<string, Y> hash;
132                         public Point point;
133
134                         public void Init () {
135                                 //y = 6;
136                                 _bb = ulong.MaxValue - 5;
137                                 _yy = new Y [] { new Y (), new Y () };
138                                 z = 8;
139                                 ch = (char) 0xFF56;
140                                 ch_null = '\0';
141                                 str = "\uFF56\uFF57\uF58FF59g";
142                                 b = 253;
143                                 sb = -48;
144                                 sh = short.MinValue + 28;
145                                 ush = ushort.MaxValue - 24;
146                                 i = -234235453;
147                                 ui = uint.MaxValue - 234234;
148                                 l = long.MinValue + 28;
149                                 ul = ulong.MaxValue - 3;
150
151                                 f = float.NaN;
152                                 f1 = float.NegativeInfinity;
153                                 f2 = float.PositiveInfinity;
154                                 f3 = float.MinValue;
155                                 f4 = float.MaxValue;
156
157                                 d = double.NaN;
158                                 d1 = double.NegativeInfinity;
159                                 d2 = double.PositiveInfinity;
160                                 d3 = double.MinValue;
161                                 d4 = double.MaxValue;
162
163                                 de = decimal.MinusOne;
164                                 de1 = decimal.Zero;
165                                 de2 = decimal.One;
166                                 de3 = decimal.MinValue;
167                                 de4 = decimal.MaxValue;
168
169                                 g = new Guid (234, 2, 354, new byte [] { 1, 2, 3, 4, 5, 6, 7, 8 });
170                                 
171                                 nb = null;
172                                 dbn = null;
173
174                                 enum_int = new List<int> (MyEnum);
175                                 enum_int1 = new ArrayList ();
176                                 foreach (object obj in MyEnum1)
177                                         ((ArrayList) enum_int1).Add (obj);
178                                 uri = new Uri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
179
180                                 hash = new Dictionary<string, Y> ();
181                                 Y y = new Y ();
182                                 hash ["mykey"] = y;
183                                 point = new Point (150, 150);
184                         }
185
186                         public IEnumerable<int> MyEnum {
187                                 get {
188                                         yield return 1;
189                                         yield return 10;
190                                         yield return 345;
191                                 }
192
193                                 set {
194                                         enum_int = value;
195                                 }
196                         }
197
198                         public IEnumerable MyEnum1 {
199                                 get {
200                                         yield return 1;
201                                         yield return 10;
202                                         yield return 345;
203                                 }
204
205                                 set {
206                                         enum_int1 = value;
207                                 }
208                         }
209
210                         public int AA {
211                                 get { return x; }
212                         }
213
214                         public Y[] AA1 {
215                                 get { return _yyy; }
216                         }
217
218                         public ulong BB {
219                                 get { return _bb; }
220                                 set { _bb = value; }
221                         }
222
223                         public Y[] YY {
224                                 get { return _yy; }
225                                 set { _yy = value; }
226                         }
227
228                         public override bool Equals (object obj) {
229                                 if (!(obj is X))
230                                         return false;
231                                 JavaScriptSerializerTest.FieldsEqual (this, obj);
232                                 return true;
233                         }
234                 }
235
236                 class Y
237                 {
238
239                         long _bb = 10;
240
241                         public long BB {
242                                 get { return _bb; }
243                                 set { _bb = value; }
244                         }
245
246                         public override bool Equals (object obj) {
247                                 if (!(obj is Y))
248                                         return false;
249                                 JavaScriptSerializerTest.FieldsEqual(this, obj);
250                                 return true;
251                         }
252                 }
253
254                 class YY
255                 {
256                         public YY () 
257                         {
258                                 Y1 = new Y ();
259                                 Y2 = new Y ();
260                         }
261
262                         public Y Y1;
263                         public Y Y2;
264                 }
265
266                 [TypeConverter (typeof (MyUriConverter))]
267                 class MyUri : Uri
268                 {
269                         public MyUri (string uriString, UriKind uriKind)
270                                 : base (uriString, uriKind) {
271                         }
272
273                         public MyUri (Uri value)
274                                 : base (value.AbsoluteUri) {
275                         }
276                 }
277
278                 class MyUriConverter : UriTypeConverter
279                 {
280                         public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 
281                         {
282                                 return base.ConvertTo (context, culture, value, destinationType);
283                         }
284
285                         public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value) 
286                         {
287                                 Uri convertedUri = (Uri)base.ConvertFrom (context, culture, value);
288                                 return new MyUri (convertedUri);
289                         }
290                 }
291
292                 [TypeConverter(typeof(MyPointConverter))]
293                 class MyPointContainer
294                 {
295                         public MyPointContainer () 
296                         {
297                         }
298
299                         public MyPointContainer (Point v) 
300                         {
301                                 p = v;
302                         }
303
304                         internal Point p;
305                 }
306
307                 class MyPointConverter : TypeConverter
308                 {
309                         public override bool CanConvertTo (ITypeDescriptorContext context, Type destinationType) 
310                         {
311                                 if (destinationType == typeof (string)) {
312                                         return true;
313                                 }
314                                 return base.CanConvertTo (context, destinationType);
315                         }
316
317                         public override object ConvertTo (ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) 
318                         {
319                                 if (destinationType == typeof (string)) {
320                                         MyPointContainer pc = (MyPointContainer) value;
321                                         return pc.p.X + "," + pc.p.Y;
322                                 }
323                                 return base.ConvertTo (context, culture, value, destinationType);
324                         }
325
326                         public override bool CanConvertFrom (ITypeDescriptorContext context, Type sourceType) 
327                         {
328                                 if (sourceType == typeof (string)) {
329                                         return true;
330                                 }
331                                 return base.CanConvertFrom (context, sourceType);
332                         }
333
334                         public override object ConvertFrom (ITypeDescriptorContext context, CultureInfo culture, object value) 
335                         {
336                                 if (value is string) {
337                                         string [] v = ((string) value).Split (new char [] { ',' });
338                                         return new MyPointContainer(new Point (int.Parse (v [0]), int.Parse (v [1])));
339                                 }
340                                 return base.ConvertFrom (context, culture, value);
341                         }
342                 }
343
344 #pragma warning restore 659
345
346                 [Test]
347                 [Category ("NotDotNet")]
348                 public void TestDefaults () {
349                         JavaScriptSerializer ser = new JavaScriptSerializer ();
350                         Assert.AreEqual (102400, ser.MaxJsonLength);
351                         Assert.AreEqual (100, ser.RecursionLimit);
352                         //List<JavaScriptConverter> l = new List<JavaScriptConverter> ();
353                         //l.Add (new MyJavaScriptConverter ());
354                         //ser.RegisterConverters (l);
355                         //string x = ser.Serialize (new X [] { new X (), new X () });
356                         //string s = ser.Serialize (new X());
357                         //"{\"BB\":10,\"__type\":\"Tests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null\"}"
358                         //X x = ser.Deserialize<X> (s);
359                         //object ddd = typeof (Y).GetMember ("BB");
360                         //object x1 = ser.Deserialize<X []> (null);
361                         //object x2 = ser.Deserialize<X []> ("");
362                         //object d = ser.Deserialize<X[]> (x);
363                 }
364
365                 [Test]
366                 public void TestDeserialize () {
367                         JavaScriptSerializer ser = new JavaScriptSerializer ();
368                         Assert.IsNull (ser.Deserialize<X> (""));
369
370                         X s = new X ();
371                         s.Init ();
372                         string x = ser.Serialize (s);
373                         X n = ser.Deserialize<X> (x);
374                         Assert.AreEqual (s, n);
375
376                         //string json = "\\uFF56";
377                         //string result = ser.Deserialize<string> (json);
378                         //Assert.AreEqual ("\uFF56", result);
379
380                         //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
381                 }
382
383                 [Test]
384                 public void TestDeserializeTypeResolver () 
385                 {
386                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
387                         X x = new X ();
388                         x.Init ();
389
390                         string s = ser.Serialize (x);
391                         X x2 = ser.Deserialize<X> (s);
392                         Assert.AreEqual (x, x2);
393                 }
394
395                 [Test]
396                 [Category("NotWorking")]
397                 public void TestDeserializeBugs () {
398                         JavaScriptSerializer ser = new JavaScriptSerializer ();
399
400                         bug s = new bug ();
401                         s.Init ();
402                         string x = ser.Serialize (s);
403                         bug n = ser.Deserialize<bug> (x);
404                         Assert.AreEqual (s, n);
405
406                         // Should check correctness with .Net GA:
407                         //js = ser.Serialize (Color.Red);
408                         //Color ccc = ser.Deserialize<Color> (js);
409                         //string xml = @"<root><node attr=""xxx""/></root>";
410
411                         //XmlDocument doc = new XmlDocument ();
412                         //doc.LoadXml (xml);
413                         //string js = ser.Serialize (doc);
414                         //DataTable table = new DataTable();
415                         //table.Columns.Add ("col1", typeof (int));
416                         //table.Columns.Add ("col2", typeof (float));
417                         //table.Rows.Add (1, 1f);
418                         //table.Rows.Add (234234, 2.4f);
419
420                         //string js = ser.Serialize (table);
421                 }
422
423                 static void FieldsEqual (object expected, object actual) {
424                         Assert.AreEqual (expected.GetType (), actual.GetType ());
425                         FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
426                         foreach (FieldInfo info in infos) {
427                                 object value1 = info.GetValue (expected);
428                                 object value2 = info.GetValue (actual);
429                                 if (value1 is IEnumerable) {
430                                         IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
431                                         int index = -1;
432                                         foreach (object x in (IEnumerable) value1) {
433                                                 if (!yenum.MoveNext ())
434                                                         Assert.Fail (info.Name + " index:" + index);
435                                                 index++;
436                                                 if (x is DictionaryEntry) {
437                                                         DictionaryEntry entry = (DictionaryEntry)x;
438                                                         IDictionary dict = (IDictionary) value2;
439                                                         Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
440                                                 }
441                                                 else
442                                                         Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
443                                         }
444                                         Assert.IsFalse (yenum.MoveNext (), info.Name);
445                                         continue;
446                                 }
447                                 Assert.AreEqual (value1, value2, info.Name);
448                         }
449
450                 }
451
452                 [Test]
453                 [ExpectedException (typeof (ArgumentNullException))]
454                 public void TestDeserialize1 () {
455                         JavaScriptSerializer ser = new JavaScriptSerializer ();
456                         ser.Deserialize<string> (null);
457                 }
458
459                 [Test]
460                 [ExpectedException (typeof (ArgumentNullException))]
461                 public void TestDeserializeNullConverter () {
462                         JavaScriptSerializer ser = new JavaScriptSerializer ();
463                         ser.RegisterConverters (null);
464                 }
465
466                 [Test]
467                 public void TestDeserializeConverter () {
468                         JavaScriptSerializer ser = new JavaScriptSerializer ();
469                         List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
470                         list.Add (new MyJavaScriptConverter ());
471                         list.Add (new CultureInfoConverter ());
472                         ser.RegisterConverters (list);
473                         string result = ser.Serialize (new X [] { new X (), new X () });
474                         Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
475                         result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
476                 }
477
478                 [Test]
479                 public void TestDeserializeConverter1 () {
480                         JavaScriptSerializer serializer = new JavaScriptSerializer ();
481
482                         serializer.RegisterConverters (new JavaScriptConverter [] { 
483             new ListItemCollectionConverter() });
484
485                         ListBox ListBox1 = new ListBox ();
486                         ListBox1.Items.Add ("a1");
487                         ListBox1.Items.Add ("a2");
488                         ListBox1.Items.Add ("a3");
489
490                         string x = serializer.Serialize (ListBox1.Items);
491                         ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
492                         Assert.AreEqual (3, recoveredList.Count);
493                 }
494
495                 [Test]
496                 public void TestSerialize1 () {
497                         JavaScriptSerializer ser = new JavaScriptSerializer ();
498                         Assert.AreEqual("null", ser.Serialize(null));
499
500                         string js = ser.Serialize (1234);
501                         Assert.AreEqual ("1234", js);
502                         Assert.AreEqual (1234, ser.Deserialize<int> (js));
503                         js = ser.Serialize (1.1);
504                         Assert.AreEqual ("1.1", js);
505                         Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
506                         char [] chars = "faskjhfasd0981234".ToCharArray ();
507                         js = ser.Serialize (chars);
508                         char[] actual = ser.Deserialize<char[]> (js);
509                         Assert.AreEqual (chars.Length, actual.Length);
510                         for (int i = 0; i < chars.Length; i++)
511                                 Assert.AreEqual (chars[i], actual[i]);
512
513                         string expected = @"""\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\""#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""";
514                         string data = "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&\u0027()*+,-./0123456789:;\u003c=\u003e?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
515
516                         string serRes = ser.Serialize (data);
517                         Assert.AreEqual (expected, serRes);
518                         string deserRes = ser.Deserialize<string> (serRes);
519                         Assert.AreEqual (data, deserRes);
520                 }
521
522                 [Test]
523                 [ExpectedException (typeof (ArgumentNullException))]
524                 [Category ("NotDotNet")]
525                 public void TestSerialize2 () {
526                         JavaScriptSerializer ser = new JavaScriptSerializer ();
527                         ser.Serialize ("aaa", null);
528                 }
529
530                 static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
531
532                 [Test]
533                 public void TestSerializeDate () {
534                         JavaScriptSerializer ser = new JavaScriptSerializer ();
535                         DateTime now = new DateTime (633213894056010000L);
536
537                         string actual = ser.Serialize (now);
538                         DateTime dateTime = now.ToUniversalTime ();
539                         long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
540
541                         object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
542                         Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
543                         Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
544                 }
545
546                 [Test]
547                 public void TestSerializeEnum () {
548                         JavaScriptSerializer ser = new JavaScriptSerializer ();
549                         string result = ser.Serialize (MyEnum.BBB);
550                         Assert.AreEqual ("1", result);
551                         Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
552                 }
553
554                 class MyJavaScriptConverter : JavaScriptConverter
555                 {
556                         public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
557                                 throw new Exception ("The method or operation is not implemented.");
558                         }
559
560                         public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
561                                 Array a = (Array) obj;
562                                 Dictionary<string, object> d = new Dictionary<string, object> ();
563                                 d.Add ("0", 1);
564                                 d.Add ("1", 2);
565                                 return d;
566                                 //throw new Exception ("The method or operation is not implemented.");
567                         }
568
569                         public override IEnumerable<Type> SupportedTypes {
570                                 get {
571                                         yield return typeof (X[]);
572                                 }
573                         }
574                 }
575
576                 sealed class CultureInfoConverter : JavaScriptConverter
577                 {
578                         static readonly Type typeofCultureInfo = typeof (CultureInfo);
579                         public override IEnumerable<Type> SupportedTypes {
580                                 get { yield return typeofCultureInfo; }
581                         }
582
583                         public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
584                                 throw new NotSupportedException ();
585                         }
586
587                         public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
588                                 CultureInfo ci = (CultureInfo)obj;
589                                 if (ci == null)
590                                         return null;
591                                 Dictionary<string, object> d = new Dictionary<string, object> ();
592                                 d.Add ("name", ci.Name);
593                                 d.Add ("numberFormat", ci.NumberFormat);
594                                 d.Add ("dateTimeFormat", ci.DateTimeFormat);
595                                 return d;
596                         }
597                 }
598
599                 public class ListItemCollectionConverter : JavaScriptConverter
600                 {
601                         public override IEnumerable<Type> SupportedTypes {
602                                 //Define the ListItemCollection as a supported type.
603                                 get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
604                         }
605
606                         public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
607                                 ListItemCollection listType = obj as ListItemCollection;
608
609                                 if (listType != null) {
610                                         // Create the representation.
611                                         Dictionary<string, object> result = new Dictionary<string, object> ();
612                                         ArrayList itemsList = new ArrayList ();
613                                         foreach (ListItem item in listType) {
614                                                 //Add each entry to the dictionary.
615                                                 Dictionary<string, object> listDict = new Dictionary<string, object> ();
616                                                 listDict.Add ("Value", item.Value);
617                                                 listDict.Add ("Text", item.Text);
618                                                 itemsList.Add (listDict);
619                                         }
620                                         result ["List"] = itemsList;
621
622                                         return result;
623                                 }
624                                 return new Dictionary<string, object> ();
625                         }
626
627                         public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
628                                 if (dictionary == null)
629                                         throw new ArgumentNullException ("dictionary");
630
631                                 if (type == typeof (ListItemCollection)) {
632                                         // Create the instance to deserialize into.
633                                         ListItemCollection list = new ListItemCollection ();
634
635                                         // Deserialize the ListItemCollection's items.
636                                         ArrayList itemsList = (ArrayList) dictionary ["List"];
637                                         for (int i = 0; i < itemsList.Count; i++)
638                                                 list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
639
640                                         return list;
641                                 }
642                                 return null;
643                         }
644                 }
645
646                 [Test]
647                 public void DeserializeObject () {
648                         object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
649                         Assert.IsNotNull (o as Dictionary<string, object>, "type");
650                         Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
651                         Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
652                         Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
653                         object [] array = (object []) dictionary ["Array"];
654                         Assert.AreEqual (true, (bool) array [0], "array [0]");
655                         Assert.AreEqual (false, (bool) array [1], "array [1]");
656                         Assert.AreEqual (0, (int) array [2], "array [2]");
657                 }
658
659                 [Test]
660                 public void DeserializeObject2 () 
661                 {
662                         JavaScriptSerializer ser = new JavaScriptSerializer ();
663                         Y y = new Y ();
664                         string s = ser.Serialize (y);
665                         object y2 = ser.DeserializeObject (s);
666                         Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
667                 }
668
669                 [Test]
670                 public void DeserializeObject3 () 
671                 {
672                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
673                         Y y = new Y ();
674                         string s = ser.Serialize (y);
675                         object y2 = ser.DeserializeObject (s);
676                         Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
677                 }
678
679                 [Test]
680                 public void DeserializeObject4 () 
681                 {
682                         JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
683                         Y y = new Y ();
684                         string s = ser.Serialize (y);
685                         object y2 = ser.DeserializeObject (s);
686                         Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
687                         Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
688                         Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
689                         Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
690                         Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
691                 }
692
693                 [Test]
694                 [ExpectedException(typeof(ArgumentNullException))]
695                 public void SerializeWithResolverDeserializeWithout () 
696                 {
697                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
698                         Y y = new Y ();
699                         string s = ser.Serialize (y);
700                         ser = new JavaScriptSerializer ();
701                         object y2 = ser.DeserializeObject (s);
702                 }
703
704                 [Test]
705                 public void SerializeWithoutResolverDeserializeWith ()
706                 {
707                         JavaScriptSerializer ser = new JavaScriptSerializer ();
708                         Y y = new Y ();
709                         string s = ser.Serialize (y);
710                         ser = new JavaScriptSerializer (new SimpleTypeResolver ());
711                         object y2 = ser.DeserializeObject (s);
712                         Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
713                 }
714
715                 class B
716                 {
717                         public int v1 = 15;
718                         public string s1 = "s1";
719                 }
720
721                 class D : B
722                 {
723                         public int v2 = 16;
724                         public string s2 = "s2";
725                 }
726
727                 class C
728                 {
729                         public B b1 = new B ();
730                         public B b2 = new D ();
731                 }
732
733                 [Test]
734                 public void SerializeDerivedType () 
735                 {
736                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
737                         B b = new D ();
738                         string s = ser.Serialize (b);
739                         B b2 = ser.Deserialize<B> (s);
740                         Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
741                 }
742
743                 [Test]
744                 public void SerializeDerivedType2 () 
745                 {
746                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
747                         B b = new D ();
748                         string s = ser.Serialize (b);
749                         B b2 = (B)ser.DeserializeObject (s);
750                         Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
751                 }
752
753                 [Test]
754                 public void SerializeContainedDerivedType () 
755                 {
756                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
757                         C c = new C ();
758                         string s = ser.Serialize (c);
759                         C c2 = ser.Deserialize<C> (s);
760                         Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
761                         Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
762                 }
763
764                 [Test]
765                 public void SerializeContainedDerivedType2 () 
766                 {
767                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
768                         C c = new C ();
769                         string s = ser.Serialize (c);
770                         C c2 = (C)ser.DeserializeObject (s);
771                         Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
772                         Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
773                 }
774
775                 [Test]
776                 public void SerializeWithTypeConverter () 
777                 {
778                         JavaScriptSerializer ser = new JavaScriptSerializer ();
779                         MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
780                         string s = ser.Serialize (uri);
781                         MyUri uri2 = ser.Deserialize<MyUri> (s);
782                         Assert.AreEqual (uri, uri2);
783                 }
784
785                 [Test]
786                 public void SerializeWithTypeConverter2 () 
787                 {
788                         JavaScriptSerializer ser = new JavaScriptSerializer ();
789                         MyPointContainer pc = new MyPointContainer(new Point(15, 16));
790                         string s = ser.Serialize(pc);
791                         MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
792                 }
793
794                 [Test]
795                 public void MaxJsonLengthDeserializeObject () 
796                 {
797                         JavaScriptSerializer ser = new JavaScriptSerializer ();
798                         ser.MaxJsonLength = 16;
799                         object o = ser.DeserializeObject ("{s:'1234567890'}");
800                 }
801
802                 [Test]
803                 [ExpectedException(typeof(ArgumentException))]
804                 public void MaxJsonLengthDeserializeObjectToLong () 
805                 {
806                         JavaScriptSerializer ser = new JavaScriptSerializer ();
807                         ser.MaxJsonLength = 15;
808                         object o = ser.DeserializeObject ("{s:'1234567890'}");
809                 }
810
811                 [Test]
812                 public void MaxJsonLengthSerialize () 
813                 {
814                         JavaScriptSerializer ser = new JavaScriptSerializer ();
815                         ser.MaxJsonLength = 9;
816                         Y y = new Y ();
817                         string s = ser.Serialize (y);
818                 }
819
820                 [Test]
821                 [ExpectedException (typeof (InvalidOperationException))]
822                 public void MaxJsonLengthSerializeToLong () 
823                 {
824                         JavaScriptSerializer ser = new JavaScriptSerializer ();
825                         ser.MaxJsonLength = 8;
826                         Y y = new Y ();
827                         string s = ser.Serialize (y);
828                 }
829
830                 [Test]
831                 public void RecursionLimitDeserialize1 () 
832                 {
833                         JavaScriptSerializer ser = new JavaScriptSerializer ();
834                         ser.RecursionLimit = 3;
835                         YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
836                 }
837
838                 [Test]
839                 public void RecursionLimitDeserialize2 () 
840                 {
841                         JavaScriptSerializer ser = new JavaScriptSerializer ();
842                         ser.RecursionLimit = 2;
843                         YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
844                 }
845
846                 [Test]
847                 public void RecursionLimitDeserialize3 () 
848                 {
849                         JavaScriptSerializer ser = new JavaScriptSerializer ();
850                         ser.RecursionLimit = 1;
851                         object o = ser.DeserializeObject ("\"xxx\"");
852                 }
853
854                 [Test]
855                 [ExpectedException(typeof(ArgumentException))]
856                 public void RecursionLimitDeserializeToDeap () 
857                 {
858                         JavaScriptSerializer ser = new JavaScriptSerializer ();
859                         ser.RecursionLimit = 2;
860                         YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
861                 }
862
863                 [Test]
864                 public void RecursionLimitSerialize () 
865                 {
866                         JavaScriptSerializer ser = new JavaScriptSerializer ();
867                         ser.RecursionLimit = 3;
868                         YY yy = new YY();
869                         string s = ser.Serialize (yy);
870                 }
871
872                 [Test]
873                 [ExpectedException(typeof(ArgumentException))]
874                 public void RecursionLimitSerializeToDeap () 
875                 {
876                         JavaScriptSerializer ser = new JavaScriptSerializer ();
877                         ser.RecursionLimit = 2;
878                         YY yy = new YY ();
879                         string s = ser.Serialize (yy);
880                 }
881
882                 [Test]
883                 public void RecursionLimitSerialize2 () 
884                 {
885                         JavaScriptSerializer ser = new JavaScriptSerializer ();
886                         ser.RecursionLimit = 2;
887                         YY yy = new YY ();
888                         StringBuilder b = new StringBuilder ();
889                         bool caughtException = false;
890                         try {
891                                 ser.Serialize (yy, b);
892                         }
893                         catch {
894                                 caughtException = true;
895                         }
896                         Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
897                         Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
898                 }
899
900                 [Test]
901                 public void SimpleTypeResolver () 
902                 {
903                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
904                         YY yy = new YY ();
905                         string s = ser.Serialize (yy);
906                         string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
907
908                         Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
909                         
910                         expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
911                         Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
912                 }
913
914                 public class CustomResolver : JavaScriptTypeResolver
915                 {
916                         public CustomResolver () 
917                         {
918                                 Reset ();
919                         }
920
921                         public override Type ResolveType (string id) 
922                         {
923                                 ResolvedIds.Add (id);
924
925                                 switch (id) {
926                                 case "YY":
927                                         return typeof(YY);
928
929                                 case "Y":
930                                         return typeof (Y);
931
932                                 case "X":
933                                         return typeof (X);
934
935                                 case "int":
936                                         return typeof (int);
937
938                                 case "long":
939                                         return typeof (long);
940
941                                 case "string":
942                                         return typeof (string);
943
944                                 case "point":
945                                         return typeof(Point);
946                                 }
947                                 return null;
948                         }
949
950                         public override string ResolveTypeId (Type type) 
951                         {
952                                 if (type == null) {
953                                         throw new ArgumentNullException ("type");
954                                 }
955
956                                 ResolvedTypes.Add (type.Name);
957
958                                 if (type == typeof (YY))
959                                         return "YY";
960
961                                 if (type == typeof (Y))
962                                         return "Y";
963
964                                 if (type == typeof (X))
965                                         return "X";
966
967                                 if (type == typeof (int))
968                                         return "int";
969
970                                 if (type == typeof (long))
971                                         return "long";
972
973                                 if (type == typeof (string))
974                                         return "string";
975
976                                 if (type == typeof(Point))
977                                         return "point";
978
979                                 return null;
980                         }
981
982                         public static List<string> ResolvedTypes {
983                                 get {
984                                         if (resolvedTypes == null) {
985                                                 resolvedTypes = new List<string> ();
986                                         }
987                                         return resolvedTypes;
988                                 }
989                         }
990
991                         public static List<string> ResolvedIds {
992                                 get {
993                                         if (resolvedIds == null) {
994                                                 resolvedIds = new List<string> ();
995                                         }
996                                         return resolvedIds;
997                                 }
998                         }
999
1000                         public static void Reset () 
1001                         {
1002                                 resolvedIds = null;
1003                                 resolvedTypes = null;
1004                         }
1005
1006                         private static List<string> resolvedTypes;
1007                         private static List<string> resolvedIds;
1008                 }
1009
1010                 [Test]
1011                 public void CustomTypeResolver ()
1012                 {
1013                         JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
1014                         X x = new X ();
1015                         x.Init ();
1016
1017                         string s = ser.Serialize (x);
1018
1019                         CustomResolver.Reset ();
1020                         X x1 = (X) ser.DeserializeObject (s);
1021                         Assert.IsTrue (x.Equals (x1), "x != x1");
1022
1023                         CustomResolver.Reset ();
1024                         X x2 = ser.Deserialize<X> (s);
1025                         Assert.IsTrue (x.Equals (x2), "x != x2");
1026                 }
1027         }
1028 }