Merge pull request #2720 from mono/fix-39325
[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 MonoTests.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 (2097152, 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 TestDeserializeUnquotedKeys ()
367                 {
368                         JavaScriptSerializer ser = new JavaScriptSerializer ();
369                         IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:\"1\",itemTwo:\"2\"}");
370
371                         Assert.AreEqual ("1", dict ["itemOne"], "#A1");
372                         Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
373
374                         dict = ser.Deserialize <Dictionary <string, object>> ("{itemOne:1,itemTwo:2}");
375                         Assert.AreEqual (1, dict ["itemOne"], "#B1");
376                         Assert.AreEqual (2, dict ["itemTwo"], "#B2");
377                 }
378
379                 [Test]
380                 public void TestDeserializeUnquotedKeysWithSpaces ()
381                 {
382                         JavaScriptSerializer ser = new JavaScriptSerializer ();
383                         IDictionary dict = ser.Deserialize <Dictionary <string, object>> ("{ itemOne :\"1\",itemTwo:\"2\"}");
384
385                         Assert.AreEqual ("1", dict ["itemOne"], "#A1");
386                         Assert.AreEqual ("2", dict ["itemTwo"], "#A2");
387
388                         dict = ser.Deserialize <Dictionary <string, object>> ("{   itemOne   :1,   itemTwo   :2}");
389                         Assert.AreEqual (1, dict ["itemOne"], "#B1");
390                         Assert.AreEqual (2, dict ["itemTwo"], "#B2");
391                 }
392                 
393                 [Test]
394                 public void TestDeserialize () {
395                         JavaScriptSerializer ser = new JavaScriptSerializer ();
396                         Assert.IsNull (ser.Deserialize<X> (""));
397
398                         X s = new X ();
399                         s.Init ();
400                         string x = ser.Serialize (s);
401
402                         Assert.AreEqual ("{\"z\":8,\"ch\":\"v\",\"ch_null\":null,\"str\":\"vwF59g\",\"b\":253,\"sb\":-48,\"sh\":-32740,\"ush\":65511,\"i\":-234235453,\"ui\":4294733061,\"l\":-9223372036854775780,\"ul\":18446744073709551612,\"f\":NaN,\"f1\":-Infinity,\"f2\":Infinity,\"f3\":-3.40282347E+38,\"f4\":3.40282347E+38,\"d\":NaN,\"d1\":-Infinity,\"d2\":Infinity,\"d3\":-1.7976931348623157E+308,\"d4\":1.7976931348623157E+308,\"de\":-1,\"de1\":0,\"de2\":1,\"de3\":-79228162514264337593543950335,\"de4\":79228162514264337593543950335,\"g\":\"000000ea-0002-0162-0102-030405060708\",\"nb\":null,\"dbn\":null,\"uri\":\"http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d\",\"hash\":{\"mykey\":{\"BB\":10}},\"point\":{\"IsEmpty\":false,\"X\":150,\"Y\":150},\"MyEnum\":[1,10,345],\"MyEnum1\":[1,10,345],\"AA\":5,\"AA1\":[{\"BB\":10},{\"BB\":10}],\"BB\":18446744073709551610,\"YY\":[{\"BB\":10},{\"BB\":10}]}", x, "#A1");
403                         
404                         X n = ser.Deserialize<X> (x);
405                         Assert.AreEqual (s, n, "#A2");
406
407                         //string json = "\\uFF56";
408                         //string result = ser.Deserialize<string> (json);
409                         //Assert.AreEqual ("\uFF56", result);
410
411                         //object oo = ser.DeserializeObject ("{value:'Purple\\r \\n monkey\\'s:\\tdishwasher'}");
412                 }
413
414                 [Test]
415                 public void TestDeserializeNonGenericOverload()
416                 {
417                         JavaScriptSerializer ser = new JavaScriptSerializer();
418                         Assert.IsNull(ser.Deserialize("", typeof(X)));
419
420                         X s = new X();
421                         s.Init();
422                         string x = ser.Serialize(s);
423
424                         Assert.AreEqual("{\"z\":8,\"ch\":\"v\",\"ch_null\":null,\"str\":\"vwF59g\",\"b\":253,\"sb\":-48,\"sh\":-32740,\"ush\":65511,\"i\":-234235453,\"ui\":4294733061,\"l\":-9223372036854775780,\"ul\":18446744073709551612,\"f\":NaN,\"f1\":-Infinity,\"f2\":Infinity,\"f3\":-3.40282347E+38,\"f4\":3.40282347E+38,\"d\":NaN,\"d1\":-Infinity,\"d2\":Infinity,\"d3\":-1.7976931348623157E+308,\"d4\":1.7976931348623157E+308,\"de\":-1,\"de1\":0,\"de2\":1,\"de3\":-79228162514264337593543950335,\"de4\":79228162514264337593543950335,\"g\":\"000000ea-0002-0162-0102-030405060708\",\"nb\":null,\"dbn\":null,\"uri\":\"http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d\",\"hash\":{\"mykey\":{\"BB\":10}},\"point\":{\"IsEmpty\":false,\"X\":150,\"Y\":150},\"MyEnum\":[1,10,345],\"MyEnum1\":[1,10,345],\"AA\":5,\"AA1\":[{\"BB\":10},{\"BB\":10}],\"BB\":18446744073709551610,\"YY\":[{\"BB\":10},{\"BB\":10}]}", x, "#A1");
425
426                         X n = ser.Deserialize(x, typeof(X)) as X;
427                         Assert.AreEqual(s, n, "#A2");
428                 }
429
430                 [Test]
431                 public void TestDeserializeTypeResolver () 
432                 {
433 #if NET_4_6
434                         string expected = "{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+X, net_4_x_System.Web.Extensions_test, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"z\":8,\"ch\":\"v\",\"ch_null\":null,\"str\":\"vwF59g\",\"b\":253,\"sb\":-48,\"sh\":-32740,\"ush\":65511,\"i\":-234235453,\"ui\":4294733061,\"l\":-9223372036854775780,\"ul\":18446744073709551612,\"f\":NaN,\"f1\":-Infinity,\"f2\":Infinity,\"f3\":-3.40282347E+38,\"f4\":3.40282347E+38,\"d\":NaN,\"d1\":-Infinity,\"d2\":Infinity,\"d3\":-1.7976931348623157E+308,\"d4\":1.7976931348623157E+308,\"de\":-1,\"de1\":0,\"de2\":1,\"de3\":-79228162514264337593543950335,\"de4\":79228162514264337593543950335,\"g\":\"000000ea-0002-0162-0102-030405060708\",\"nb\":null,\"dbn\":null,\"uri\":\"http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d\",\"hash\":{\"mykey\":{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, net_4_x_System.Web.Extensions_test, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}},\"point\":{\"__type\":\"System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\",\"IsEmpty\":false,\"X\":150,\"Y\":150},\"MyEnum\":[1,10,345],\"MyEnum1\":[1,10,345],\"AA\":5,\"AA1\":[{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, net_4_x_System.Web.Extensions_test, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10},{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, net_4_x_System.Web.Extensions_test, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}],\"BB\":18446744073709551610,\"YY\":[{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, net_4_x_System.Web.Extensions_test, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10},{\"__type\":\"MonoTests.System.Web.Script.Serialization.JavaScriptSerializerTest+Y, net_4_x_System.Web.Extensions_test, Version=1.3.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35\",\"BB\":10}]}";
435 #else
436                         #error "Unknown profile"
437 #endif
438                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
439                         X x = new X ();
440                         x.Init ();
441
442                         string s = ser.Serialize (x);
443                         Assert.AreEqual (expected, s, "#A1");
444                         
445                         X x2 = ser.Deserialize<X> (s);
446                         Assert.AreEqual (x, x2, "#A2");
447                 }
448
449                 [Test]
450                 public void TestDeserializeBugs () {
451                         JavaScriptSerializer ser = new JavaScriptSerializer ();
452
453                         bug s = new bug ();
454                         s.Init ();
455                         string x = ser.Serialize (s);
456                         bug n = ser.Deserialize<bug> (x);
457                         Assert.AreEqual (s, n);
458
459                         // Should check correctness with .Net GA:
460                         //js = ser.Serialize (Color.Red);
461                         //Color ccc = ser.Deserialize<Color> (js);
462                         //string xml = @"<root><node attr=""xxx""/></root>";
463
464                         //XmlDocument doc = new XmlDocument ();
465                         //doc.LoadXml (xml);
466                         //string js = ser.Serialize (doc);
467                         //DataTable table = new DataTable();
468                         //table.Columns.Add ("col1", typeof (int));
469                         //table.Columns.Add ("col2", typeof (float));
470                         //table.Rows.Add (1, 1f);
471                         //table.Rows.Add (234234, 2.4f);
472
473                         //string js = ser.Serialize (table);
474                 }
475
476                 static void FieldsEqual (object expected, object actual) {
477                         Assert.AreEqual (expected.GetType (), actual.GetType ());
478                         FieldInfo [] infos = expected.GetType ().GetFields (BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
479                         foreach (FieldInfo info in infos) {
480                                 object value1 = info.GetValue (expected);
481                                 object value2 = info.GetValue (actual);
482                                 if (value1 is IEnumerable) {
483                                         IEnumerator yenum = ((IEnumerable) value2).GetEnumerator ();
484                                         int index = -1;
485                                         foreach (object x in (IEnumerable) value1) {
486                                                 if (!yenum.MoveNext ())
487                                                         Assert.Fail (info.Name + " index:" + index);
488                                                 index++;
489                                                 if (x is DictionaryEntry) {
490                                                         DictionaryEntry entry = (DictionaryEntry)x;
491                                                         IDictionary dict = (IDictionary) value2;
492                                                         Assert.AreEqual (entry.Value, dict [entry.Key], info.Name + ", key:" + entry.Key);
493                                                 }
494                                                 else
495                                                         Assert.AreEqual (x, yenum.Current, info.Name + ", index:" + index);
496                                         }
497                                         Assert.IsFalse (yenum.MoveNext (), info.Name);
498                                         continue;
499                                 }
500                                 Assert.AreEqual (value1, value2, info.Name);
501                         }
502
503                 }
504
505                 [Test]
506                 [ExpectedException (typeof (ArgumentNullException))]
507                 public void TestDeserialize1 () {
508                         JavaScriptSerializer ser = new JavaScriptSerializer ();
509                         ser.Deserialize<string> (null);
510                 }
511
512                 [Test]
513                 [ExpectedException (typeof (ArgumentNullException))]
514                 public void TestDeserializeNullConverter () {
515                         JavaScriptSerializer ser = new JavaScriptSerializer ();
516                         ser.RegisterConverters (null);
517                 }
518
519                 [Test]
520                 [SetCulture ("en-US")]
521                 public void TestDeserializeConverter () {
522                         JavaScriptSerializer ser = new JavaScriptSerializer ();
523                         List<JavaScriptConverter> list = new List<JavaScriptConverter> ();
524                         list.Add (new MyJavaScriptConverter ());
525                         list.Add (new CultureInfoConverter ());
526                         ser.RegisterConverters (list);
527                         string result = ser.Serialize (new X [] { new X (), new X () });
528                         Assert.AreEqual ("{\"0\":1,\"1\":2}", result);
529                         result = ser.Serialize (Thread.CurrentThread.CurrentCulture);
530                 }
531
532                 [Test]
533                 public void TestDeserializeConverter1 () {
534                         JavaScriptSerializer serializer = new JavaScriptSerializer ();
535
536                         serializer.RegisterConverters (new JavaScriptConverter [] {new ListItemCollectionConverter()});
537
538                         ListBox ListBox1 = new ListBox ();
539                         ListBox1.Items.Add ("a1");
540                         ListBox1.Items.Add ("a2");
541                         ListBox1.Items.Add ("a3");
542
543                         string x = serializer.Serialize (ListBox1.Items);
544                         ListItemCollection recoveredList = serializer.Deserialize<ListItemCollection> (x);
545                         Assert.AreEqual (3, recoveredList.Count);
546                 }
547
548                 [Test]
549                 public void TestSerialize1 () {
550                         JavaScriptSerializer ser = new JavaScriptSerializer ();
551                         Assert.AreEqual("null", ser.Serialize(null));
552
553                         string js = ser.Serialize (1234);
554                         Assert.AreEqual ("1234", js);
555                         Assert.AreEqual (1234, ser.Deserialize<int> (js));
556                         js = ser.Serialize (1.1);
557                         Assert.AreEqual ("1.1", js);
558                         Assert.AreEqual (1.1f, ser.Deserialize<float> (js));
559                         char [] chars = "faskjhfasd0981234".ToCharArray ();
560                         js = ser.Serialize (chars);
561                         char[] actual = ser.Deserialize<char[]> (js);
562                         Assert.AreEqual (chars.Length, actual.Length);
563                         for (int i = 0; i < chars.Length; i++)
564                                 Assert.AreEqual (chars[i], actual[i]);
565
566                         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{|}~""";
567                         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{|}~";
568
569                         string serRes = ser.Serialize (data);
570                         Assert.AreEqual (expected, serRes);
571                         string deserRes = ser.Deserialize<string> (serRes);
572                         Assert.AreEqual (data, deserRes);
573                 }
574
575                 [Test]
576                 [ExpectedException (typeof (ArgumentNullException))]
577                 [Category ("NotDotNet")]
578                 public void TestSerialize2 () {
579                         JavaScriptSerializer ser = new JavaScriptSerializer ();
580                         ser.Serialize ("aaa", (StringBuilder)null);
581                 }
582
583                 static readonly long InitialJavaScriptDateTicks = new DateTime (1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).Ticks;
584
585                 [Test]
586                 public void TestSerializeDate () {
587                         JavaScriptSerializer ser = new JavaScriptSerializer ();
588                         DateTime now = new DateTime (633213894056010000L);
589
590                         string actual = ser.Serialize (now);
591                         DateTime dateTime = now.ToUniversalTime ();
592                         long javaScriptTicks = (dateTime.Ticks - InitialJavaScriptDateTicks) / (long) 10000;
593
594                         object dd = ser.DeserializeObject (@"""\/Datte(" + javaScriptTicks + @")\/""");
595                         Assert.AreEqual (@"""\/Date(" + javaScriptTicks + @")\/""", actual);
596                         Assert.AreEqual (now.ToUniversalTime(), ser.DeserializeObject (actual));
597                 }
598
599                 [Test]
600                 public void TestSerializeEnum () {
601                         JavaScriptSerializer ser = new JavaScriptSerializer ();
602                         string result = ser.Serialize (MyEnum.BBB);
603                         Assert.AreEqual ("1", result);
604                         Assert.AreEqual (MyEnum.BBB, ser.Deserialize<MyEnum> (result));
605                 }
606
607                 class MyJavaScriptConverter : JavaScriptConverter
608                 {
609                         public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
610                                 throw new Exception ("The method or operation is not implemented.");
611                         }
612
613                         public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
614                                 Array a = (Array) obj;
615                                 Dictionary<string, object> d = new Dictionary<string, object> ();
616                                 d.Add ("0", 1);
617                                 d.Add ("1", 2);
618                                 return d;
619                                 //throw new Exception ("The method or operation is not implemented.");
620                         }
621
622                         public override IEnumerable<Type> SupportedTypes {
623                                 get {
624                                         yield return typeof (X[]);
625                                 }
626                         }
627                 }
628
629                 sealed class CultureInfoConverter : JavaScriptConverter
630                 {
631                         static readonly Type typeofCultureInfo = typeof (CultureInfo);
632                         public override IEnumerable<Type> SupportedTypes {
633                                 get { yield return typeofCultureInfo; }
634                         }
635
636                         public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
637                                 throw new NotSupportedException ();
638                         }
639
640                         public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
641                                 CultureInfo ci = (CultureInfo)obj;
642                                 if (ci == null)
643                                         return null;
644                                 Dictionary<string, object> d = new Dictionary<string, object> ();
645                                 d.Add ("name", ci.Name);
646                                 d.Add ("numberFormat", ci.NumberFormat);
647                                 d.Add ("dateTimeFormat", ci.DateTimeFormat);
648                                 return d;
649                         }
650                 }
651
652                 public class ListItemCollectionConverter : JavaScriptConverter
653                 {
654                         public override IEnumerable<Type> SupportedTypes {
655                                 //Define the ListItemCollection as a supported type.
656                                 get { return new ReadOnlyCollection<Type> (new Type [] { typeof (ListItemCollection) }); }
657                         }
658
659                         public override IDictionary<string, object> Serialize (object obj, JavaScriptSerializer serializer) {
660                                 ListItemCollection listType = obj as ListItemCollection;
661
662                                 if (listType != null) {
663                                         // Create the representation.
664                                         Dictionary<string, object> result = new Dictionary<string, object> ();
665                                         ArrayList itemsList = new ArrayList ();
666                                         foreach (ListItem item in listType) {
667                                                 //Add each entry to the dictionary.
668                                                 Dictionary<string, object> listDict = new Dictionary<string, object> ();
669                                                 listDict.Add ("Value", item.Value);
670                                                 listDict.Add ("Text", item.Text);
671                                                 itemsList.Add (listDict);
672                                         }
673                                         result ["List"] = itemsList;
674
675                                         return result;
676                                 }
677                                 return new Dictionary<string, object> ();
678                         }
679
680                         public override object Deserialize (IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer) {
681                                 if (dictionary == null)
682                                         throw new ArgumentNullException ("dictionary");
683
684                                 if (type == typeof (ListItemCollection)) {
685                                         // Create the instance to deserialize into.
686                                         ListItemCollection list = new ListItemCollection ();
687
688                                         // Deserialize the ListItemCollection's items.
689                                         ArrayList itemsList = (ArrayList) dictionary ["List"];
690                                         for (int i = 0; i < itemsList.Count; i++)
691                                                 list.Add (serializer.ConvertToType<ListItem> (itemsList [i]));
692
693                                         return list;
694                                 }
695                                 return null;
696                         }
697                 }
698
699                 [Test]
700                 public void DeserializeObject () {
701                         object o = new JavaScriptSerializer ().DeserializeObject ("{\"Numeric\":0,\"Array\":[true,false,0]}");
702                         Assert.IsNotNull (o as Dictionary<string, object>, "type");
703                         Dictionary<string, object> dictionary = (Dictionary<string, object>) o;
704                         Assert.AreEqual (0, (int) dictionary ["Numeric"], "Numeric");
705                         Assert.IsNotNull (dictionary ["Array"] as object [], "Array type");
706                         object [] array = (object []) dictionary ["Array"];
707                         Assert.AreEqual (true, (bool) array [0], "array [0]");
708                         Assert.AreEqual (false, (bool) array [1], "array [1]");
709                         Assert.AreEqual (0, (int) array [2], "array [2]");
710                 }
711
712                 [Test]
713                 public void DeserializeObject2 () 
714                 {
715                         JavaScriptSerializer ser = new JavaScriptSerializer ();
716                         Y y = new Y ();
717                         string s = ser.Serialize (y);
718                         object y2 = ser.DeserializeObject (s);
719                         Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
720                 }
721
722                 [Test]
723                 public void DeserializeObject3 () 
724                 {
725                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver());
726                         Y y = new Y ();
727                         string s = ser.Serialize (y);
728                         object y2 = ser.DeserializeObject (s);
729                         Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
730                 }
731
732                 [Test]
733                 public void DeserializeObject4 () 
734                 {
735                         JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver());
736                         Y y = new Y ();
737                         string s = ser.Serialize (y);
738                         object y2 = ser.DeserializeObject (s);
739                         Assert.AreEqual (typeof (Y), y2.GetType (), "DeserializeObject to Dictionary");
740                         Assert.AreEqual (1, CustomResolver.ResolvedIds.Count, "ResolvedIds Count");
741                         Assert.AreEqual ("Y", CustomResolver.ResolvedIds [0], "ResolvedIds.Y");
742                         Assert.AreEqual (1, CustomResolver.ResolvedTypes.Count, "ResolvedTypes Count");
743                         Assert.AreEqual ("Y", CustomResolver.ResolvedTypes [0], "ResolvedTypes.Y");
744                 }
745
746                 [Test]
747                 [ExpectedException(typeof(ArgumentNullException))]
748                 public void SerializeWithResolverDeserializeWithout () 
749                 {
750                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
751                         Y y = new Y ();
752                         string s = ser.Serialize (y);
753                         ser = new JavaScriptSerializer ();
754                         object y2 = ser.DeserializeObject (s);
755                 }
756
757                 [Test]
758                 public void SerializeWithoutResolverDeserializeWith ()
759                 {
760                         JavaScriptSerializer ser = new JavaScriptSerializer ();
761                         Y y = new Y ();
762                         string s = ser.Serialize (y);
763                         ser = new JavaScriptSerializer (new SimpleTypeResolver ());
764                         object y2 = ser.DeserializeObject (s);
765                         Assert.AreEqual (typeof (Dictionary<string, object>), y2.GetType (), "DeserializeObject to Dictionary");
766                 }
767
768                 class B
769                 {
770                         public int v1 = 15;
771                         public string s1 = "s1";
772                 }
773
774                 class D : B
775                 {
776                         public int v2 = 16;
777                         public string s2 = "s2";
778                 }
779
780                 class C
781                 {
782                         public B b1 = new B ();
783                         public B b2 = new D ();
784                 }
785
786                 [Test]
787                 public void SerializeDerivedType () 
788                 {
789                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
790                         B b = new D ();
791                         string s = ser.Serialize (b);
792                         B b2 = ser.Deserialize<B> (s);
793                         Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
794                 }
795
796                 [Test]
797                 public void SerializeDerivedType2 () 
798                 {
799                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
800                         B b = new D ();
801                         string s = ser.Serialize (b);
802                         B b2 = (B)ser.DeserializeObject (s);
803                         Assert.AreEqual (typeof (D), b2.GetType (), "Deserialize Derived Type");
804                 }
805
806                 [Test]
807                 public void SerializeContainedDerivedType () 
808                 {
809                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
810                         C c = new C ();
811                         string s = ser.Serialize (c);
812                         C c2 = ser.Deserialize<C> (s);
813                         Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
814                         Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
815                 }
816
817                 [Test]
818                 public void SerializeContainedDerivedType2 () 
819                 {
820                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
821                         C c = new C ();
822                         string s = ser.Serialize (c);
823                         C c2 = (C)ser.DeserializeObject (s);
824                         Assert.AreEqual (typeof (C), c2.GetType (), "Deserialize Derived Type");
825                         Assert.AreEqual (typeof (D), c2.b2.GetType (), "Deserialize Derived Type");
826                 }
827
828                 [Test]
829                 public void SerializeWithTypeConverter () 
830                 {
831                         JavaScriptSerializer ser = new JavaScriptSerializer ();
832                         MyUri uri = new MyUri ("http://kostat@mainsoft/adfasdf/asdfasdf.aspx/asda/ads?a=b&c=d", UriKind.RelativeOrAbsolute);
833                         string s = ser.Serialize (uri);
834                         MyUri uri2 = ser.Deserialize<MyUri> (s);
835                         Assert.AreEqual (uri, uri2);
836                 }
837
838                 [Test]
839                 public void SerializeWithTypeConverter2 () 
840                 {
841                         JavaScriptSerializer ser = new JavaScriptSerializer ();
842                         MyPointContainer pc = new MyPointContainer(new Point(15, 16));
843                         string s = ser.Serialize(pc);
844                         MyPointContainer pc2 = ser.Deserialize<MyPointContainer>(s);
845                 }
846                 
847                 [Test]
848                 public void MaxJsonLengthDeserializeObject () 
849                 {
850                         JavaScriptSerializer ser = new JavaScriptSerializer ();
851                         ser.MaxJsonLength = 16;
852                         object o = ser.DeserializeObject ("{s:'1234567890'}");
853                 }
854
855                 [Test]
856                 [ExpectedException(typeof(ArgumentException))]
857                 public void MaxJsonLengthDeserializeObjectToLong () 
858                 {
859                         JavaScriptSerializer ser = new JavaScriptSerializer ();
860                         ser.MaxJsonLength = 15;
861                         object o = ser.DeserializeObject ("{s:'1234567890'}");
862                 }
863
864                 [Test]
865                 public void MaxJsonLengthSerialize () 
866                 {
867                         JavaScriptSerializer ser = new JavaScriptSerializer ();
868                         ser.MaxJsonLength = 9;
869                         Y y = new Y ();
870                         string s = ser.Serialize (y);
871                 }
872
873                 [Test]
874                 [ExpectedException (typeof (InvalidOperationException))]
875                 public void MaxJsonLengthSerializeToLong () 
876                 {
877                         JavaScriptSerializer ser = new JavaScriptSerializer ();
878                         ser.MaxJsonLength = 8;
879                         Y y = new Y ();
880                         string s = ser.Serialize (y);
881                 }
882
883                 [Test]
884                 public void RecursionLimitDeserialize1 () 
885                 {
886                         JavaScriptSerializer ser = new JavaScriptSerializer ();
887                         ser.RecursionLimit = 3;
888                         YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
889                 }
890
891                 [Test]
892                 public void RecursionLimitDeserialize2 () 
893                 {
894                         JavaScriptSerializer ser = new JavaScriptSerializer ();
895                         ser.RecursionLimit = 2;
896                         YY yy = ser.Deserialize<YY> ("{\"Y1\":{},\"Y2\":{}}");
897                 }
898
899                 [Test]
900                 public void RecursionLimitDeserialize3 () 
901                 {
902                         JavaScriptSerializer ser = new JavaScriptSerializer ();
903                         ser.RecursionLimit = 1;
904                         object o = ser.DeserializeObject ("\"xxx\"");
905                 }
906
907                 [Test]
908                 [ExpectedException(typeof(ArgumentException))]
909                 public void RecursionLimitDeserializeToDeep () 
910                 {
911                         JavaScriptSerializer ser = new JavaScriptSerializer ();
912                         ser.RecursionLimit = 2;
913                         YY yy = ser.Deserialize<YY> ("{\"Y1\":{\"BB\":10},\"Y2\":{\"BB\":10}}");
914                 }
915
916                 [Test]
917                 public void RecursionLimitSerialize () 
918                 {
919                         JavaScriptSerializer ser = new JavaScriptSerializer ();
920                         ser.RecursionLimit = 3;
921                         YY yy = new YY();
922                         string s = ser.Serialize (yy);
923                 }
924
925                 [Test]
926                 [ExpectedException(typeof(ArgumentException))]
927                 public void RecursionLimitSerializeToDeep () 
928                 {
929                         JavaScriptSerializer ser = new JavaScriptSerializer ();
930                         ser.RecursionLimit = 2;
931                         YY yy = new YY ();
932                         string s = ser.Serialize (yy);
933                 }
934
935                 [Test]
936                 public void RecursionLimitSerialize2 () 
937                 {
938                         JavaScriptSerializer ser = new JavaScriptSerializer ();
939                         ser.RecursionLimit = 2;
940                         YY yy = new YY ();
941                         StringBuilder b = new StringBuilder ();
942                         bool caughtException = false;
943                         try {
944                                 ser.Serialize (yy, b);
945                         }
946                         catch {
947                                 caughtException = true;
948                         }
949                         Assert.IsTrue (caughtException, "RecursionLimitSerialize2 Expected an exception!");
950                         Assert.AreEqual ("{\"Y1\":{\"BB\":", b.ToString (), "RecursionLimitSerialize2");
951                 }
952
953                 [Test]
954                 public void SimpleTypeResolver () 
955                 {
956                         JavaScriptSerializer ser = new JavaScriptSerializer (new SimpleTypeResolver ());
957                         YY yy = new YY ();
958                         string s = ser.Serialize (yy);
959                         string expected = String.Format("\"__type\":\"{0}\"", yy.GetType().AssemblyQualifiedName);
960
961                         Assert.IsTrue (s.Contains (expected), "YY: expected {0} to contain {1}", s, expected);
962                         
963                         expected = String.Format ("\"__type\":\"{0}\"", yy.Y1.GetType ().AssemblyQualifiedName);
964                         Assert.IsTrue (s.Contains (expected), "Y: expected {0} to contain {1}", s, expected);
965                 }
966
967                 public class CustomResolver : JavaScriptTypeResolver
968                 {
969                         public CustomResolver () 
970                         {
971                                 Reset ();
972                         }
973
974                         public override Type ResolveType (string id) 
975                         {
976                                 ResolvedIds.Add (id);
977
978                                 switch (id) {
979                                 case "YY":
980                                         return typeof(YY);
981
982                                 case "Y":
983                                         return typeof (Y);
984
985                                 case "X":
986                                         return typeof (X);
987
988                                 case "int":
989                                         return typeof (int);
990
991                                 case "long":
992                                         return typeof (long);
993
994                                 case "string":
995                                         return typeof (string);
996
997                                 case "point":
998                                         return typeof(Point);
999                                 }
1000                                 return null;
1001                         }
1002
1003                         public override string ResolveTypeId (Type type) 
1004                         {
1005                                 if (type == null) {
1006                                         throw new ArgumentNullException ("type");
1007                                 }
1008
1009                                 ResolvedTypes.Add (type.Name);
1010
1011                                 if (type == typeof (YY))
1012                                         return "YY";
1013
1014                                 if (type == typeof (Y))
1015                                         return "Y";
1016
1017                                 if (type == typeof (X))
1018                                         return "X";
1019
1020                                 if (type == typeof (int))
1021                                         return "int";
1022
1023                                 if (type == typeof (long))
1024                                         return "long";
1025
1026                                 if (type == typeof (string))
1027                                         return "string";
1028
1029                                 if (type == typeof(Point))
1030                                         return "point";
1031
1032                                 return null;
1033                         }
1034
1035                         public static List<string> ResolvedTypes {
1036                                 get {
1037                                         if (resolvedTypes == null) {
1038                                                 resolvedTypes = new List<string> ();
1039                                         }
1040                                         return resolvedTypes;
1041                                 }
1042                         }
1043
1044                         public static List<string> ResolvedIds {
1045                                 get {
1046                                         if (resolvedIds == null) {
1047                                                 resolvedIds = new List<string> ();
1048                                         }
1049                                         return resolvedIds;
1050                                 }
1051                         }
1052
1053                         public static void Reset () 
1054                         {
1055                                 resolvedIds = null;
1056                                 resolvedTypes = null;
1057                         }
1058
1059                         private static List<string> resolvedTypes;
1060                         private static List<string> resolvedIds;
1061                 }
1062
1063                 [Test]
1064                 [NUnit.Framework.Category ("NotWorking")]
1065                 public void CustomTypeResolver ()
1066                 {
1067                         JavaScriptSerializer ser = new JavaScriptSerializer (new CustomResolver ());
1068                         X x = new X ();
1069                         x.Init ();
1070
1071                         string s = ser.Serialize (x);
1072
1073                         CustomResolver.Reset ();
1074                         X x1 = (X) ser.DeserializeObject (s);
1075                         Assert.IsTrue (x.Equals (x1), "x != x1");
1076
1077                         CustomResolver.Reset ();
1078                         X x2 = ser.Deserialize<X> (s);
1079                         Assert.IsTrue (x.Equals (x2), "x != x2");
1080                 }
1081
1082                 [Test]
1083                 public void InfinityAndNaN ()
1084                 {
1085                         JavaScriptSerializer ser = new JavaScriptSerializer ();
1086
1087                         double nan = Double.NaN;
1088                         string s = ser.Serialize (nan);
1089                         Assert.AreEqual (s, "NaN", "#A1");
1090                         nan = (double)ser.DeserializeObject (s);
1091                         Assert.AreEqual (Double.NaN, nan, "#A2");
1092                         nan = (double)ser.Deserialize <double> (s);
1093                         Assert.AreEqual (Double.NaN, nan, "#A3");
1094                         
1095                         double infinity = Double.PositiveInfinity;
1096                         s = ser.Serialize (infinity);
1097                         Assert.AreEqual (s, "Infinity", "#B1");
1098                         infinity = (double)ser.DeserializeObject (s);
1099                         Assert.AreEqual (Double.PositiveInfinity, infinity, "#B2");
1100                         infinity = ser.Deserialize <double> (s);
1101                         Assert.AreEqual (Double.PositiveInfinity, infinity, "#B3");
1102                         
1103                         infinity = Double.NegativeInfinity;
1104                         s = ser.Serialize (infinity);
1105                         Assert.AreEqual (s, "-Infinity", "#C1");
1106                         infinity = (double)ser.DeserializeObject (s);
1107                         Assert.AreEqual (Double.NegativeInfinity, infinity, "#C2");
1108                         infinity = ser.Deserialize <double> (s);
1109                         Assert.AreEqual (Double.NegativeInfinity, infinity, "#C3");
1110
1111                         var dict = new Dictionary <string, object> ();
1112                         dict.Add ("A", Double.NaN);
1113                         dict.Add ("B", Double.PositiveInfinity);
1114                         dict.Add ("C", Double.NegativeInfinity);
1115                         s = ser.Serialize (dict);
1116                         Assert.AreEqual ("{\"A\":NaN,\"B\":Infinity,\"C\":-Infinity}", s, "#D1");
1117                         
1118                         dict = (Dictionary <string, object>)ser.DeserializeObject (s);
1119                         Assert.AreEqual (Double.NaN, dict ["A"], "#D2");
1120                         Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D3");
1121                         Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D4");
1122
1123                         dict = (Dictionary <string, object>)ser.Deserialize <Dictionary <string, object>> (s);
1124                         Assert.AreEqual (Double.NaN, dict ["A"], "#D5");
1125                         Assert.AreEqual (Double.PositiveInfinity, dict ["B"], "#D6");
1126                         Assert.AreEqual (Double.NegativeInfinity, dict ["C"], "#D7");
1127
1128                         var arr = new ArrayList () {
1129                                         Double.NaN,
1130                                         Double.PositiveInfinity,
1131                                         Double.NegativeInfinity};
1132                         s = ser.Serialize (arr);
1133                         Assert.AreEqual ("[NaN,Infinity,-Infinity]", s, "#E1");
1134
1135                         object[] arr2 = (object[])ser.DeserializeObject (s);
1136                         Assert.AreEqual (3, arr2.Length, "#E2");
1137                         Assert.AreEqual (Double.NaN, arr2 [0], "#E3");
1138                         Assert.AreEqual (Double.PositiveInfinity, arr2 [1], "#E4");
1139                         Assert.AreEqual (Double.NegativeInfinity, arr2 [2], "#E5");
1140
1141                         arr = ser.Deserialize <ArrayList> (s);
1142                         Assert.AreEqual (3, arr.Count, "#E6");
1143                         Assert.AreEqual (Double.NaN, arr [0], "#E7");
1144                         Assert.AreEqual (Double.PositiveInfinity, arr [1], "#E8");
1145                         Assert.AreEqual (Double.NegativeInfinity, arr [2], "#E9");
1146                 }
1147
1148                 [Test]
1149                 public void StandalonePrimitives ()
1150                 {
1151                         JavaScriptSerializer ser = new JavaScriptSerializer ();
1152
1153                         object o;
1154                         int i;
1155                         
1156                         o = ser.DeserializeObject ("1");
1157                         Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A1");
1158                         i = (int)o;
1159                         Assert.AreEqual (1, i, "#A2");
1160                         o =ser.DeserializeObject ("-1");
1161                         Assert.AreEqual (typeof (global::System.Int32), o.GetType (), "#A3");
1162                         i = (int)o;
1163                         Assert.AreEqual (-1, i, "#A4");
1164                         
1165                         o = ser.DeserializeObject ("2147483649");
1166                         Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B1");
1167                         long l = (long)o;
1168                         Assert.AreEqual (2147483649, l, "#B2");
1169                         o = ser.DeserializeObject ("-2147483649");
1170                         Assert.AreEqual (typeof (global::System.Int64), o.GetType (), "#B3");
1171                         l = (long)o;
1172                         Assert.AreEqual (-2147483649, l, "#B4");
1173
1174                         o = ser.DeserializeObject ("9223372036854775808");
1175                         Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C1");
1176                         decimal d = (decimal)o;
1177                         Assert.AreEqual (9223372036854775808m, d, "#C2");
1178                         o = ser.DeserializeObject ("-9223372036854775809");
1179                         Assert.AreEqual (typeof (global::System.Decimal), o.GetType (), "#C3");
1180                         d = (decimal)o;
1181                         Assert.AreEqual (-9223372036854775809m, d, "#C4");
1182
1183                         o = ser.DeserializeObject ("79228162514264337593543950336");
1184                         Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D1");
1185                         double db = (double)o;
1186                         Assert.AreEqual (79228162514264337593543950336.0, db, "#D2");
1187                         o = ser.DeserializeObject ("-79228162514264337593543950336");
1188                         Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#D3");
1189                         db = (double)o;
1190                         Assert.AreEqual (-79228162514264337593543950336.0, db, "#D4");
1191                         
1192                         o = ser.DeserializeObject ("\"test string\"");
1193                         Assert.AreEqual (typeof (global::System.String), o.GetType (), "#E1");
1194                         string s = (string)o;
1195                         Assert.AreEqual ("test string", s, "#E2");
1196
1197                         o = ser.DeserializeObject ("true");
1198                         Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F1");
1199                         bool b = (bool)o;
1200                         Assert.AreEqual (true, b, "#F2");
1201
1202                         o = ser.DeserializeObject ("false");
1203                         Assert.AreEqual (typeof (global::System.Boolean), o.GetType (), "#F3");
1204                         b = (bool)o;
1205                         Assert.AreEqual (false, b, "#F4");
1206
1207                         o = ser.DeserializeObject ("-1.7976931348623157E+308");
1208                         Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G1");
1209                         db = (double)o;
1210                         Assert.AreEqual (Double.MinValue, db, "#G2");
1211
1212                         o = ser.DeserializeObject ("1.7976931348623157E+308");
1213                         Assert.AreEqual (typeof (global::System.Double), o.GetType (), "#G3");
1214                         db = (double)o;
1215                         Assert.AreEqual (Double.MaxValue, db, "#G4");
1216                 }
1217
1218                 class SomeDict : IDictionary<string, object>
1219                 {
1220                         void IDictionary<string, object>.Add (string key, object value) {
1221                                 throw new NotSupportedException ();
1222                         }
1223
1224                         bool IDictionary<string, object>.ContainsKey (string key) {
1225                                 throw new NotSupportedException ();
1226                         }
1227
1228                         ICollection<string> IDictionary<string, object>.Keys {
1229                                 get { throw new NotSupportedException (); }
1230                         }
1231
1232                         bool IDictionary<string, object>.Remove (string key) {
1233                                 throw new NotSupportedException ();
1234                         }
1235
1236                         bool IDictionary<string, object>.TryGetValue (string key, out object value) {
1237                                 throw new NotSupportedException ();
1238                         }
1239
1240                         ICollection<object> IDictionary<string, object>.Values {
1241                                 get { throw new NotSupportedException (); }
1242                         }
1243
1244                         object IDictionary<string, object>.this [string key] {
1245                                 get { throw new NotSupportedException (); }
1246                                 set { throw new NotSupportedException (); }
1247                         }
1248
1249                         void ICollection<KeyValuePair<string, object>>.Add (KeyValuePair<string, object> item) {
1250                                 throw new NotSupportedException ();
1251                         }
1252
1253                         void ICollection<KeyValuePair<string, object>>.Clear () {
1254                                 throw new NotSupportedException ();
1255                         }
1256
1257                         bool ICollection<KeyValuePair<string, object>>.Contains (KeyValuePair<string, object> item) {
1258                                 throw new NotSupportedException ();
1259                         }
1260
1261                         void ICollection<KeyValuePair<string, object>>.CopyTo (KeyValuePair<string, object> [] array, int arrayIndex) {
1262                                 throw new NotSupportedException ();
1263                         }
1264
1265                         int ICollection<KeyValuePair<string, object>>.Count {
1266                                 get { throw new NotSupportedException (); }
1267                         }
1268
1269                         bool ICollection<KeyValuePair<string, object>>.IsReadOnly {
1270                                 get { throw new NotSupportedException (); }
1271                         }
1272
1273                         bool ICollection<KeyValuePair<string, object>>.Remove (KeyValuePair<string, object> item) {
1274                                 throw new NotSupportedException ();
1275                         }
1276
1277                         IEnumerator<KeyValuePair<string, object>> IEnumerable<KeyValuePair<string, object>>.GetEnumerator () {
1278                                 return GetEnumerator ();
1279                         }
1280
1281                         IEnumerator IEnumerable.GetEnumerator () {
1282                                 return ((IEnumerable<KeyValuePair<string, object>>) this).GetEnumerator ();
1283                         }
1284
1285                         protected IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
1286                                 yield return new KeyValuePair<string, object> ("hello", "world");
1287                         }
1288                 }
1289
1290                 [Test] //bug #424704
1291                 public void NonGenericClassImplementingClosedGenericIDictionary ()
1292                 {
1293                         JavaScriptSerializer ser = new JavaScriptSerializer ();
1294
1295                         SomeDict dictIn = new SomeDict ();
1296
1297                         string s = ser.Serialize (dictIn);
1298
1299                         Dictionary<string, object> dictOut = ser.Deserialize<Dictionary<string, object>> (s);
1300                         Assert.AreEqual (dictOut.Count, 1, "#1");
1301                         Assert.AreEqual (dictOut["hello"], "world", "#2");
1302                 }
1303
1304                 [Test]
1305                 public void ConvertToIDictionary ()
1306                 {
1307                         JavaScriptSerializer jss = new JavaScriptSerializer ();
1308                         string json = "{\"node\":{\"Text\":\"Root Node\",\"Value\":null,\"ExpandMode\":3,\"NavigateUrl\":null,\"PostBack\":true,\"DisabledCssClass\":null,\"SelectedCssClass\":null,\"HoveredCssClass\":null,\"ImageUrl\":null,\"HoveredImageUrl\":null,\"DisabledImageUrl\":null,\"ExpandedImageUrl\":null,\"ContextMenuID\":\"\"},\"context\":{\"NumberOfNodes\":1000}}";
1309                         object input = jss.Deserialize<IDictionary>(json);
1310                         IDictionary o = jss.ConvertToType<IDictionary>(input);
1311
1312                         Assert.IsTrue (o != null, "#A1");
1313                         Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1314                 }
1315
1316                 [Test]
1317                 public void ConvertToGenericIDictionary ()
1318                 {
1319                         JavaScriptSerializer jss = new JavaScriptSerializer ();
1320                         string json = "{\"node\":{\"Text\":\"Root Node\",\"Value\":null,\"ExpandMode\":3,\"NavigateUrl\":null,\"PostBack\":true,\"DisabledCssClass\":null,\"SelectedCssClass\":null,\"HoveredCssClass\":null,\"ImageUrl\":null,\"HoveredImageUrl\":null,\"DisabledImageUrl\":null,\"ExpandedImageUrl\":null,\"ContextMenuID\":\"\"},\"context\":{\"NumberOfNodes\":1000}}";
1321
1322                         object input = jss.Deserialize<IDictionary>(json);
1323                         
1324                         IDictionary <string, object> o = jss.ConvertToType<IDictionary <string, object>>(input);
1325                         Assert.IsTrue (o != null, "#A1");
1326                         Assert.AreEqual (typeof (Dictionary <string, object>), o.GetType (), "#A2");
1327
1328                         IDictionary <object, object> o1 = jss.ConvertToType<IDictionary <object, object>>(input);
1329                         Assert.IsTrue (o1 != null, "#B1");
1330                         Assert.AreEqual (typeof (Dictionary <object, object>), o1.GetType (), "#B2");
1331                 }
1332
1333                 [Test]
1334                 [ExpectedException (typeof (InvalidOperationException))]
1335                 public void ConvertToGenericIDictionary_InvalidDefinition ()
1336                 {
1337                         JavaScriptSerializer jss = new JavaScriptSerializer ();
1338                         string json = "{\"node\":{\"Text\":\"Root Node\",\"Value\":null,\"ExpandMode\":3,\"NavigateUrl\":null,\"PostBack\":true,\"DisabledCssClass\":null,\"SelectedCssClass\":null,\"HoveredCssClass\":null,\"ImageUrl\":null,\"HoveredImageUrl\":null,\"DisabledImageUrl\":null,\"ExpandedImageUrl\":null,\"ContextMenuID\":\"\"},\"context\":{\"NumberOfNodes\":1000}}";
1339
1340                         object input = jss.Deserialize<IDictionary>(json);
1341                         IDictionary <int, object> o = jss.ConvertToType<IDictionary <int, object>>(input);
1342                 }
1343
1344                 [Test (Description="Bug #655474")]
1345                 public void TestRelativeUri()
1346                 {
1347                         JavaScriptSerializer ser = new JavaScriptSerializer();
1348                         Uri testUri = new Uri("/lala/123", UriKind.Relative);
1349                         StringBuilder sb = new StringBuilder();
1350
1351                         ser.Serialize(testUri, sb);
1352                         Assert.AreEqual ("\"/lala/123\"", sb.ToString ());
1353                 }
1354                 
1355                 [Test]
1356                 public void DeserializeDictionaryOfArrayList ()
1357                 {
1358                         var ser = new JavaScriptSerializer ();
1359                         string test1 = "{\"key\":{\"subkey\":\"subval\"}}";
1360                         string test2 = "{\"key\":[{\"subkey\":\"subval\"}]}";
1361
1362                         var ret1 = ser.Deserialize<Dictionary<string, object>>(test1);
1363                         Assert.AreEqual (typeof (Dictionary<string, object>), ret1.GetType (), "#1.1");
1364                         var ret1v = ret1 ["key"];
1365                         Assert.AreEqual (typeof (Dictionary<string, object>), ret1v.GetType (), "#1.2");
1366                         var ret1vd = (IDictionary<string,object>) ret1v;
1367                         Assert.AreEqual ("subval", ret1vd ["subkey"], "#1.3");
1368
1369                         var ret2 = ser.Deserialize<Dictionary<string, object>>(test2);
1370                         Assert.AreEqual (typeof (Dictionary<string, object>), ret2.GetType (), "#2.1");
1371                         var ret2v = ret2 ["key"];
1372                         Assert.AreEqual (typeof (ArrayList), ret2v.GetType (), "#2.2");
1373                         var ret2va = (ArrayList) ret2v;
1374                         Assert.AreEqual (typeof (Dictionary<string, object>), ret2va [0].GetType (), "#2.3");
1375                         var ret2vad = (IDictionary<string,object>) ret2va [0];
1376                         Assert.AreEqual ("subval", ret2vad ["subkey"], "#2.4");
1377                 }
1378                 
1379                 class ClassWithNullableEnum
1380                 {
1381                         public MyEnum? Value { get; set; }
1382                 }
1383                 
1384                 [Test]
1385                 public void DeserializeNullableEnum ()
1386                 {               
1387                         var jsonValues = new Dictionary<string, MyEnum?> {
1388                                 { "{\"Value\":0}", MyEnum.AAA},
1389                                 { "{\"Value\":\"0\"}", MyEnum.AAA},
1390                                 { "{\"Value\":null}", null}
1391                         };
1392                         
1393                         var ser = new JavaScriptSerializer ();
1394                         
1395                         foreach (var kv in jsonValues)
1396                         {
1397                                 var obj = ser.Deserialize<ClassWithNullableEnum> (kv.Key);
1398                                 Assert.AreEqual (kv.Value, obj.Value);
1399                         }
1400                 }
1401
1402                 [Test]
1403                 public void DeserializeStringWithNewline ()
1404                 {
1405                         JavaScriptSerializer serializer = new JavaScriptSerializer ();
1406                         string json_with_newline = @"
1407         [
1408           {
1409           content:""      
1410 <div id=\""calendar\""><div>   
1411         ""   
1412           }
1413         ]
1414     ";
1415                         serializer.DeserializeObject (json_with_newline);
1416                 }
1417
1418                 class Dummy
1419                 {
1420                         public bool t;
1421                         public bool f;
1422                         public string s;
1423                         public int i;
1424                         public double d;
1425                         public object o;
1426                 }
1427                 
1428                 [Test]
1429                 public void DeserializeWhiteSpaces ()
1430                 {
1431                         string json = "{\"t\" : true , \"f\" : false , \"s\" : \"s\" , \"i\" : 1337 , \"d\" : 1337.0 , \"o\" : null }";
1432                         
1433                         var obj = (new JavaScriptSerializer ()).Deserialize<Dummy>(json);
1434                         
1435                         Assert.IsTrue (obj.t);
1436                         Assert.IsFalse (obj.f);
1437                         Assert.AreEqual ("s", obj.s);
1438                         Assert.AreEqual (1337, obj.i);
1439                         Assert.AreEqual (1337.0, obj.d);
1440                         Assert.AreEqual (null, obj.o);
1441                 }
1442
1443                 [Test]
1444                 public void DeserializeInCultureWithCommaSeparator ()
1445                 {
1446                         var origCulture = Thread.CurrentThread.CurrentCulture;
1447
1448                         try {
1449                                 Thread.CurrentThread.CurrentCulture = new CultureInfo ("en-US");
1450                                 CommaSeparatorTest ();
1451
1452                                 Thread.CurrentThread.CurrentCulture = new CultureInfo ("fi-FI");
1453                                 CommaSeparatorTest ();
1454                         } finally {
1455                                 Thread.CurrentThread.CurrentCulture = origCulture;
1456                         }
1457                 }
1458
1459                 public class DoubleTest
1460                 {
1461                         public double[] value { get; set; }
1462                 }
1463
1464                 void CommaSeparatorTest()
1465                 {
1466                         JavaScriptSerializer serializer = new JavaScriptSerializer ();
1467
1468                         DoubleTest array = new DoubleTest ();
1469                         array.value = new[] { 123.345, 0.69 };
1470
1471                         string arrayJson = serializer.Serialize (array);
1472                         Console.WriteLine (arrayJson);
1473
1474                         // This throwed incorrectly a "System.ArgumentException: Invalid JSON primitive: 123.345" with a CurrentThread.CultureInfo that has a comma as the number separator.
1475                         DoubleTest obj = serializer.Deserialize<DoubleTest> (arrayJson);
1476
1477                         Assert.AreEqual (123.345, obj.value[0], "#1");
1478                         Assert.AreEqual (0.69, obj.value[1], "#2");
1479                 }
1480         }
1481 }