Merge pull request #82 from Unity-Technologies/master-gc-race
[mono.git] / mcs / class / System.ServiceModel.Web / Test / System.Runtime.Serialization.Json / DataContractJsonSerializerTest.cs
1 //
2 // DataContractJsonSerializerTest.cs
3 //
4 // Author:
5 //      Atsushi Enomoto <atsushi@ximian.com>
6 //      Ankit Jain <JAnkit@novell.com>
7 //
8 // Copyright (C) 2005-2007 Novell, Inc.  http://www.novell.com
9
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 //
32 // This test code contains tests for DataContractJsonSerializer, which is
33 // imported from DataContractSerializerTest.cs.
34 //
35
36 using System;
37 using System.Collections;
38 using System.Collections.Generic;
39 using System.Collections.ObjectModel;
40 using System.IO;
41 using System.Net;
42 using System.Runtime.Serialization;
43 using System.Runtime.Serialization.Json;
44 using System.Text;
45 using System.Xml;
46 using NUnit.Framework;
47
48 namespace MonoTests.System.Runtime.Serialization.Json
49 {
50         [TestFixture]
51         public class DataContractJsonSerializerTest
52         {
53                 static readonly XmlWriterSettings settings;
54
55                 static DataContractJsonSerializerTest ()
56                 {
57                         settings = new XmlWriterSettings ();
58                         settings.OmitXmlDeclaration = true;
59                 }
60
61                 [DataContract]
62                 class Sample1
63                 {
64                         [DataMember]
65                         public string Member1;
66                 }
67
68                 [Test]
69                 [ExpectedException (typeof (ArgumentNullException))]
70                 public void ConstructorTypeNull ()
71                 {
72                         new DataContractJsonSerializer (null);
73                 }
74
75                 [Test]
76                 public void ConstructorKnownTypesNull ()
77                 {
78                         // null knownTypes is allowed.
79                         new DataContractJsonSerializer (typeof (Sample1), (IEnumerable<Type>) null);
80                         new DataContractJsonSerializer (typeof (Sample1), "Foo", null);
81                 }
82
83                 [Test]
84                 [ExpectedException (typeof (ArgumentNullException))]
85                 public void ConstructorNameNull ()
86                 {
87                         new DataContractJsonSerializer (typeof (Sample1), (string) null);
88                 }
89
90                 [Test]
91                 [ExpectedException (typeof (ArgumentOutOfRangeException))]
92                 public void ConstructorNegativeMaxObjects ()
93                 {
94                         new DataContractJsonSerializer (typeof (Sample1), "Sample1",
95                                 null, -1, false, null, false);
96                 }
97
98                 [Test]
99                 public void ConstructorMisc ()
100                 {
101                         new DataContractJsonSerializer (typeof (GlobalSample1)).WriteObject (new MemoryStream (), new GlobalSample1 ());
102                 }
103
104                 [Test]
105                 public void WriteObjectContent ()
106                 {
107                         StringWriter sw = new StringWriter ();
108                         using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
109                                 DataContractJsonSerializer ser =
110                                         new DataContractJsonSerializer (typeof (string));
111                                 xw.WriteStartElement ("my-element");
112                                 ser.WriteObjectContent (xw, "TEST STRING");
113                                 xw.WriteEndElement ();
114                         }
115                         Assert.AreEqual ("<my-element>TEST STRING</my-element>",
116                                 sw.ToString ());
117                 }
118
119                 // int
120
121                 [Test]
122                 public void SerializeIntXml ()
123                 {
124                         StringWriter sw = new StringWriter ();
125                         SerializeInt (XmlWriter.Create (sw, settings));
126                         Assert.AreEqual (
127                                 @"<root type=""number"">1</root>",
128                                 sw.ToString ());
129                 }
130
131                 [Test]
132                 public void SerializeIntJson ()
133                 {
134                         MemoryStream ms = new MemoryStream ();
135                         SerializeInt (JsonReaderWriterFactory.CreateJsonWriter (ms));
136                         Assert.AreEqual (
137                                 "1",
138                                 Encoding.UTF8.GetString (ms.ToArray ()));
139                 }
140
141                 void SerializeInt (XmlWriter writer)
142                 {
143                         DataContractJsonSerializer ser =
144                                 new DataContractJsonSerializer (typeof (int));
145                         using (XmlWriter w = writer) {
146                                 ser.WriteObject (w, 1);
147                         }
148                 }
149
150                 // int, with rootName
151
152                 [Test]
153                 public void SerializeIntXmlWithRootName ()
154                 {
155                         StringWriter sw = new StringWriter ();
156                         SerializeIntWithRootName (XmlWriter.Create (sw, settings));
157                         Assert.AreEqual (
158                                 @"<myroot type=""number"">1</myroot>",
159                                 sw.ToString ());
160                 }
161
162                 [Test]
163                 // since JsonWriter supports only "root" as the root name, using
164                 // XmlWriter from JsonReaderWriterFactory will always fail with
165                 // an explicit rootName.
166                 [ExpectedException (typeof (SerializationException))]
167                 public void SerializeIntJsonWithRootName ()
168                 {
169                         MemoryStream ms = new MemoryStream ();
170                         SerializeIntWithRootName (JsonReaderWriterFactory.CreateJsonWriter (ms));
171                         Assert.AreEqual (
172                                 "1",
173                                 Encoding.UTF8.GetString (ms.ToArray ()));
174                 }
175
176                 void SerializeIntWithRootName (XmlWriter writer)
177                 {
178                         DataContractJsonSerializer ser =
179                                 new DataContractJsonSerializer (typeof (int), "myroot");
180                         using (XmlWriter w = writer) {
181                                 ser.WriteObject (w, 1);
182                         }
183                 }
184
185                 // pass typeof(DCEmpty), serialize int
186
187                 [Test]
188                 public void SerializeIntForDCEmptyXml ()
189                 {
190                         StringWriter sw = new StringWriter ();
191                         SerializeIntForDCEmpty (XmlWriter.Create (sw, settings));
192                         Assert.AreEqual (
193                                 @"<root type=""number"">1</root>",
194                                 sw.ToString ());
195                 }
196
197                 [Test]
198                 public void SerializeIntForDCEmptyJson ()
199                 {
200                         MemoryStream ms = new MemoryStream ();
201                         SerializeIntForDCEmpty (JsonReaderWriterFactory.CreateJsonWriter (ms));
202                         Assert.AreEqual (
203                                 "1",
204                                 Encoding.UTF8.GetString (ms.ToArray ()));
205                 }
206
207                 void SerializeIntForDCEmpty (XmlWriter writer)
208                 {
209                         DataContractJsonSerializer ser =
210                                 new DataContractJsonSerializer (typeof (DCEmpty));
211                         using (XmlWriter w = writer) {
212                                 ser.WriteObject (w, 1);
213                         }
214                 }
215
216                 // DCEmpty
217
218                 [Test]
219                 public void SerializeEmptyClassXml ()
220                 {
221                         StringWriter sw = new StringWriter ();
222                         SerializeEmptyClass (XmlWriter.Create (sw, settings));
223                         Assert.AreEqual (
224                                 @"<root type=""object"" />",
225                                 sw.ToString ());
226                 }
227
228                 [Test]
229                 public void SerializeEmptyClassJson ()
230                 {
231                         MemoryStream ms = new MemoryStream ();
232                         SerializeEmptyClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
233                         Assert.AreEqual (
234                                 "{}",
235                                 Encoding.UTF8.GetString (ms.ToArray ()));
236                 }
237
238                 void SerializeEmptyClass (XmlWriter writer)
239                 {
240                         DataContractJsonSerializer ser =
241                                 new DataContractJsonSerializer (typeof (DCEmpty));
242                         using (XmlWriter w = writer) {
243                                 ser.WriteObject (w, new DCEmpty ());
244                         }
245                 }
246
247                 // string (primitive)
248
249                 [Test]
250                 public void SerializePrimitiveStringXml ()
251                 {
252                         StringWriter sw = new StringWriter ();
253                         SerializePrimitiveString (XmlWriter.Create (sw, settings));
254                         Assert.AreEqual (
255                                 "<root>TEST</root>",
256                                 sw.ToString ());
257                 }
258
259                 [Test]
260                 public void SerializePrimitiveStringJson ()
261                 {
262                         MemoryStream ms = new MemoryStream ();
263                         SerializePrimitiveString (JsonReaderWriterFactory.CreateJsonWriter (ms));
264                         Assert.AreEqual (
265                                 @"""TEST""",
266                                 Encoding.UTF8.GetString (ms.ToArray ()));
267                 }
268
269                 void SerializePrimitiveString (XmlWriter writer)
270                 {
271                         XmlObjectSerializer ser =
272                                 new DataContractJsonSerializer (typeof (string));
273                         using (XmlWriter w = writer) {
274                                 ser.WriteObject (w, "TEST");
275                         }
276                 }
277
278                 // QName (primitive but ...)
279
280                 [Test]
281                 public void SerializePrimitiveQNameXml ()
282                 {
283                         StringWriter sw = new StringWriter ();
284                         SerializePrimitiveQName (XmlWriter.Create (sw, settings));
285                         Assert.AreEqual (
286                                 "<root>foo:urn:foo</root>",
287                                 sw.ToString ());
288                 }
289
290                 [Test]
291                 public void SerializePrimitiveQNameJson ()
292                 {
293                         MemoryStream ms = new MemoryStream ();
294                         SerializePrimitiveQName (JsonReaderWriterFactory.CreateJsonWriter (ms));
295                         Assert.AreEqual (
296                                 @"""foo:urn:foo""",
297                                 Encoding.UTF8.GetString (ms.ToArray ()));
298                 }
299
300                 void SerializePrimitiveQName (XmlWriter writer)
301                 {
302                         XmlObjectSerializer ser =
303                                 new DataContractJsonSerializer (typeof (XmlQualifiedName));
304                         using (XmlWriter w = writer) {
305                                 ser.WriteObject (w, new XmlQualifiedName ("foo", "urn:foo"));
306                         }
307                 }
308
309                 // DBNull (primitive)
310
311                 [Test]
312                 public void SerializeDBNullXml ()
313                 {
314                         StringWriter sw = new StringWriter ();
315                         SerializeDBNull (XmlWriter.Create (sw, settings));
316                         Assert.AreEqual (
317                                 @"<root type=""object"" />",
318                                 sw.ToString ());
319                 }
320
321                 [Test]
322                 public void SerializeDBNullJson ()
323                 {
324                         MemoryStream ms = new MemoryStream ();
325                         SerializeDBNull (JsonReaderWriterFactory.CreateJsonWriter (ms));
326                         Assert.AreEqual (
327                                 "{}",
328                                 Encoding.UTF8.GetString (ms.ToArray ()));
329                 }
330
331                 void SerializeDBNull (XmlWriter writer)
332                 {
333                         DataContractJsonSerializer ser =
334                                 new DataContractJsonSerializer (typeof (DBNull));
335                         using (XmlWriter w = writer) {
336                                 ser.WriteObject (w, DBNull.Value);
337                         }
338                 }
339
340                 // DCSimple1
341
342                 [Test]
343                 public void SerializeSimpleClass1Xml ()
344                 {
345                         StringWriter sw = new StringWriter ();
346                         SerializeSimpleClass1 (XmlWriter.Create (sw, settings));
347                         Assert.AreEqual (
348                                 @"<root type=""object""><Foo>TEST</Foo></root>",
349                                 sw.ToString ());
350                 }
351
352                 [Test]
353                 public void SerializeSimpleClass1Json ()
354                 {
355                         MemoryStream ms = new MemoryStream ();
356                         SerializeSimpleClass1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
357                         Assert.AreEqual (
358                                 @"{""Foo"":""TEST""}",
359                                 Encoding.UTF8.GetString (ms.ToArray ()));
360                 }
361
362                 void SerializeSimpleClass1 (XmlWriter writer)
363                 {
364                         DataContractJsonSerializer ser =
365                                 new DataContractJsonSerializer (typeof (DCSimple1));
366                         using (XmlWriter w = writer) {
367                                 ser.WriteObject (w, new DCSimple1 ());
368                         }
369                 }
370
371                 // NonDC
372
373                 [Test]
374                 // NonDC is not a DataContract type.
375                 public void SerializeNonDCOnlyCtor ()
376                 {
377                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
378                 }
379
380                 [Test]
381                 //[ExpectedException (typeof (InvalidDataContractException))]
382                 // NonDC is not a DataContract type.
383                 // UPDATE: non-DataContract types are became valid in RTM.
384                 public void SerializeNonDC ()
385                 {
386                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
387                         using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
388                                 ser.WriteObject (w, new NonDC ());
389                         }
390                 }
391
392                 // DCHasNonDC
393
394                 [Test]
395                 //[ExpectedException (typeof (InvalidDataContractException))]
396                 // DCHasNonDC itself is a DataContract type whose field is
397                 // marked as DataMember but its type is not DataContract.
398                 // UPDATE: non-DataContract types are became valid in RTM.
399                 public void SerializeDCHasNonDC ()
400                 {
401                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasNonDC));
402                         using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
403                                 ser.WriteObject (w, new DCHasNonDC ());
404                         }
405                 }
406
407                 // DCHasSerializable
408
409                 [Test]
410                 public void SerializeSimpleSerializable1Xml ()
411                 {
412                         StringWriter sw = new StringWriter ();
413                         SerializeSimpleSerializable1 (XmlWriter.Create (sw, settings));
414                         Assert.AreEqual (
415                                 @"<root type=""object""><Ser type=""object""><Doh>doh!</Doh></Ser></root>",
416                                 sw.ToString ());
417                 }
418
419                 [Test]
420                 public void SerializeSimpleSerializable1Json ()
421                 {
422                         MemoryStream ms = new MemoryStream ();
423                         SerializeSimpleSerializable1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
424                         Assert.AreEqual (
425                                 @"{""Ser"":{""Doh"":""doh!""}}",
426                                 Encoding.UTF8.GetString (ms.ToArray ()));
427                 }
428
429                 // DCHasSerializable itself is DataContract and has a field
430                 // whose type is not contract but serializable.
431                 void SerializeSimpleSerializable1 (XmlWriter writer)
432                 {
433                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasSerializable));
434                         using (XmlWriter w = writer) {
435                                 ser.WriteObject (w, new DCHasSerializable ());
436                         }
437                 }
438
439                 [Test]
440                 public void SerializeDCWithNameXml ()
441                 {
442                         StringWriter sw = new StringWriter ();
443                         SerializeDCWithName (XmlWriter.Create (sw, settings));
444                         Assert.AreEqual (
445                                 @"<root type=""object""><FooMember>value</FooMember></root>",
446                                 sw.ToString ());
447                 }
448
449                 [Test]
450                 public void SerializeDCWithNameJson ()
451                 {
452                         MemoryStream ms = new MemoryStream ();
453                         SerializeDCWithName (JsonReaderWriterFactory.CreateJsonWriter (ms));
454                         Assert.AreEqual (
455                                 @"{""FooMember"":""value""}",
456                                 Encoding.UTF8.GetString (ms.ToArray ()));
457                 }
458
459                 void SerializeDCWithName (XmlWriter writer)
460                 {
461                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
462                         using (XmlWriter w = writer) {
463                                 ser.WriteObject (w, new DCWithName ());
464                         }
465                 }
466
467                 [Test]
468                 public void SerializeDCWithEmptyName1 ()
469                 {
470                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyName));
471                         StringWriter sw = new StringWriter ();
472                         DCWithEmptyName dc = new DCWithEmptyName ();
473                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
474                                 try {
475                                         ser.WriteObject (w, dc);
476                                 } catch (InvalidDataContractException) {
477                                         return;
478                                 }
479                         }
480                         Assert.Fail ("Expected InvalidDataContractException");
481                 }
482
483                 [Test]
484                 public void SerializeDCWithEmptyName2 ()
485                 {
486                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
487                         StringWriter sw = new StringWriter ();
488
489                         /* DataContractAttribute.Name == "", not valid */
490                         DCWithEmptyName dc = new DCWithEmptyName ();
491                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
492                                 try {
493                                         ser.WriteObject (w, dc);
494                                 } catch (InvalidDataContractException) {
495                                         return;
496                                 }
497                         }
498                         Assert.Fail ("Expected InvalidDataContractException");
499                 }
500
501                 [Test]
502                 [Category("NotWorking")]
503                 public void SerializeDCWithNullName ()
504                 {
505                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithNullName));
506                         StringWriter sw = new StringWriter ();
507                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
508                                 try {
509                                         /* DataContractAttribute.Name == "", not valid */
510                                         ser.WriteObject (w, new DCWithNullName ());
511                                 } catch (InvalidDataContractException) {
512                                         return;
513                                 }
514                         }
515                         Assert.Fail ("Expected InvalidDataContractException");
516                 }
517
518                 [Test]
519                 public void SerializeDCWithEmptyNamespace1 ()
520                 {
521                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyNamespace));
522                         StringWriter sw = new StringWriter ();
523                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
524                                 ser.WriteObject (w, new DCWithEmptyNamespace ());
525                         }
526                 }
527
528                 [Test]
529                 public void SerializeWrappedClassXml ()
530                 {
531                         StringWriter sw = new StringWriter ();
532                         SerializeWrappedClass (XmlWriter.Create (sw, settings));
533                         Assert.AreEqual (
534                                 @"<root type=""object"" />",
535                                 sw.ToString ());
536                 }
537
538                 [Test]
539                 public void SerializeWrappedClassJson ()
540                 {
541                         MemoryStream ms = new MemoryStream ();
542                         SerializeWrappedClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
543                         Assert.AreEqual (
544                                 "{}",
545                                 Encoding.UTF8.GetString (ms.ToArray ()));
546                 }
547
548                 void SerializeWrappedClass (XmlWriter writer)
549                 {
550                         DataContractJsonSerializer ser =
551                                 new DataContractJsonSerializer (typeof (Wrapper.DCWrapped));
552                         using (XmlWriter w = writer) {
553                                 ser.WriteObject (w, new Wrapper.DCWrapped ());
554                         }
555                 }
556
557                 // CollectionContainer : Items must have a setter. (but became valid in RTM).
558                 [Test]
559                 public void SerializeReadOnlyCollectionMember ()
560                 {
561                         DataContractJsonSerializer ser =
562                                 new DataContractJsonSerializer (typeof (CollectionContainer));
563                         StringWriter sw = new StringWriter ();
564                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
565                                 ser.WriteObject (w, null);
566                         }
567                 }
568
569                 // DataCollectionContainer : Items must have a setter. (but became valid in RTM).
570                 [Test]
571                 public void SerializeReadOnlyDataCollectionMember ()
572                 {
573                         DataContractJsonSerializer ser =
574                                 new DataContractJsonSerializer (typeof (DataCollectionContainer));
575                         StringWriter sw = new StringWriter ();
576                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
577                                 ser.WriteObject (w, null);
578                         }
579                 }
580
581                 [Test]
582                 [Ignore ("https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=409970")]
583                 [ExpectedException (typeof (SerializationException))]
584                 public void DeserializeReadOnlyDataCollection_NullCollection ()
585                 {
586                         DataContractJsonSerializer ser =
587                                 new DataContractJsonSerializer (typeof (CollectionContainer));
588                         StringWriter sw = new StringWriter ();
589                         var c = new CollectionContainer ();
590                         c.Items.Add ("foo");
591                         c.Items.Add ("bar");
592                         using (XmlWriter w = XmlWriter.Create (sw, settings))
593                                 ser.WriteObject (w, c);
594                         // CollectionContainer.Items is null, so it cannot deserialize non-null collection.
595                         using (XmlReader r = XmlReader.Create (new StringReader (sw.ToString ())))
596                                 c = (CollectionContainer) ser.ReadObject (r);
597                 }
598
599                 [Test]
600                 public void SerializeGuidXml ()
601                 {
602                         StringWriter sw = new StringWriter ();
603                         SerializeGuid (XmlWriter.Create (sw, settings));
604                         Assert.AreEqual (
605                                 @"<root>00000000-0000-0000-0000-000000000000</root>",
606                                 sw.ToString ());
607                 }
608
609                 [Test]
610                 public void SerializeGuidJson ()
611                 {
612                         MemoryStream ms = new MemoryStream ();
613                         SerializeGuid (JsonReaderWriterFactory.CreateJsonWriter (ms));
614                         Assert.AreEqual (
615                                 @"""00000000-0000-0000-0000-000000000000""",
616                                 Encoding.UTF8.GetString (ms.ToArray ()));
617                 }
618
619                 void SerializeGuid (XmlWriter writer)
620                 {
621                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Guid));
622                         using (XmlWriter w = writer) {
623                                 ser.WriteObject (w, Guid.Empty);
624                         }
625                 }
626
627                 [Test]
628                 public void SerializeEnumXml ()
629                 {
630                         StringWriter sw = new StringWriter ();
631                         SerializeEnum (XmlWriter.Create (sw, settings));
632                         Assert.AreEqual (
633                                 @"<root type=""number"">0</root>",
634                                 sw.ToString ());
635                 }
636
637                 [Test]
638                 public void SerializeEnumJson ()
639                 {
640                         MemoryStream ms = new MemoryStream ();
641                         SerializeEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
642                         Assert.AreEqual (
643                                 "0",
644                                 Encoding.UTF8.GetString (ms.ToArray ()));
645                 }
646
647                 void SerializeEnum (XmlWriter writer)
648                 {
649                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
650                         using (XmlWriter w = writer) {
651                                 ser.WriteObject (w, new Colors ());
652                         }
653                 }
654
655                 [Test]
656                 public void SerializeEnum2Xml ()
657                 {
658                         StringWriter sw = new StringWriter ();
659                         SerializeEnum2 (XmlWriter.Create (sw, settings));
660                         Assert.AreEqual (
661                                 @"<root type=""number"">0</root>",
662                                 sw.ToString ());
663                 }
664
665                 [Test]
666                 public void SerializeEnum2Json ()
667                 {
668                         MemoryStream ms = new MemoryStream ();
669                         SerializeEnum2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
670                         Assert.AreEqual (
671                                 "0",
672                                 Encoding.UTF8.GetString (ms.ToArray ()));
673                 }
674
675                 void SerializeEnum2 (XmlWriter writer)
676                 {
677                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
678                         using (XmlWriter w = writer) {
679                                 ser.WriteObject (w, 0);
680                         }
681                 }
682
683                 [Test] // so, DataContract does not affect here.
684                 public void SerializeEnumWithDCXml ()
685                 {
686                         StringWriter sw = new StringWriter ();
687                         SerializeEnumWithDC (XmlWriter.Create (sw, settings));
688                         Assert.AreEqual (
689                                 @"<root type=""number"">0</root>",
690                                 sw.ToString ());
691                 }
692
693                 [Test]
694                 public void SerializeEnumWithDCJson ()
695                 {
696                         MemoryStream ms = new MemoryStream ();
697                         SerializeEnumWithDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
698                         Assert.AreEqual (
699                                 "0",
700                                 Encoding.UTF8.GetString (ms.ToArray ()));
701                 }
702
703                 void SerializeEnumWithDC (XmlWriter writer)
704                 {
705                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
706                         using (XmlWriter w = writer) {
707                                 ser.WriteObject (w, new ColorsWithDC ());
708                         }
709                 }
710
711                 [Test]
712                 public void SerializeEnumWithNoDCXml ()
713                 {
714                         StringWriter sw = new StringWriter ();
715                         SerializeEnumWithNoDC (XmlWriter.Create (sw, settings));
716                         Assert.AreEqual (
717                                 @"<root type=""number"">0</root>",
718                                 sw.ToString ());
719                 }
720
721                 [Test]
722                 public void SerializeEnumWithNoDCJson ()
723                 {
724                         MemoryStream ms = new MemoryStream ();
725                         SerializeEnumWithNoDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
726                         Assert.AreEqual (
727                                 "0",
728                                 Encoding.UTF8.GetString (ms.ToArray ()));
729                 }
730
731                 void SerializeEnumWithNoDC (XmlWriter writer)
732                 {
733                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsEnumMemberNoDC));
734                         using (XmlWriter w = writer) {
735                                 ser.WriteObject (w, new ColorsEnumMemberNoDC ());
736                         }
737                 }
738
739                 [Test]
740                 public void SerializeEnumWithDC2Xml ()
741                 {
742                         StringWriter sw = new StringWriter ();
743                         SerializeEnumWithDC2 (XmlWriter.Create (sw, settings));
744                         Assert.AreEqual (
745                                 @"<root type=""number"">3</root>",
746                                 sw.ToString ());
747                 }
748
749                 [Test]
750                 public void SerializeEnumWithDC2Json ()
751                 {
752                         MemoryStream ms = new MemoryStream ();
753                         SerializeEnumWithDC2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
754                         Assert.AreEqual (
755                                 "3",
756                                 Encoding.UTF8.GetString (ms.ToArray ()));
757                 }
758
759                 void SerializeEnumWithDC2 (XmlWriter writer)
760                 {
761                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
762                         using (XmlWriter w = writer) {
763                                 ser.WriteObject (w, 3);
764                         }
765                 }
766
767 /*
768                 [Test]
769                 [ExpectedException (typeof (SerializationException))]
770                 public void SerializeEnumWithDCInvalid ()
771                 {
772                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
773                         StringWriter sw = new StringWriter ();
774                         ColorsWithDC cdc = ColorsWithDC.Blue;
775                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
776                                 ser.WriteObject (w, cdc);
777                         }
778                 }
779 */
780
781                 [Test]
782                 public void SerializeDCWithEnumXml ()
783                 {
784                         StringWriter sw = new StringWriter ();
785                         SerializeDCWithEnum (XmlWriter.Create (sw, settings));
786                         Assert.AreEqual (
787                                 @"<root type=""object""><_colors type=""number"">0</_colors></root>",
788                                 sw.ToString ());
789                 }
790
791                 [Test]
792                 public void SerializeDCWithEnumJson ()
793                 {
794                         MemoryStream ms = new MemoryStream ();
795                         SerializeDCWithEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
796                         Assert.AreEqual (
797                                 @"{""_colors"":0}",
798                                 Encoding.UTF8.GetString (ms.ToArray ()));
799                 }
800
801                 void SerializeDCWithEnum (XmlWriter writer)
802                 {
803                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum));
804                         using (XmlWriter w = writer) {
805                                 ser.WriteObject (w, new DCWithEnum ());
806                         }
807                 }
808
809                 [Test]
810                 public void SerializerDCArrayXml ()
811                 {
812                         StringWriter sw = new StringWriter ();
813                         SerializerDCArray (XmlWriter.Create (sw, settings));
814                         Assert.AreEqual (
815                                 @"<root type=""array""><item type=""object""><_colors type=""number"">0</_colors></item><item type=""object""><_colors type=""number"">1</_colors></item></root>",
816                                 sw.ToString ());
817                 }
818
819                 [Test]
820                 public void SerializerDCArrayJson ()
821                 {
822                         MemoryStream ms = new MemoryStream ();
823                         SerializerDCArray (JsonReaderWriterFactory.CreateJsonWriter (ms));
824                         Assert.AreEqual (
825                                 @"[{""_colors"":0},{""_colors"":1}]",
826                                 Encoding.UTF8.GetString (ms.ToArray ()));
827                 }
828
829                 void SerializerDCArray (XmlWriter writer)
830                 {
831                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum []));
832                         DCWithEnum [] arr = new DCWithEnum [2];
833                         arr [0] = new DCWithEnum (); arr [0].colors = Colors.Red;
834                         arr [1] = new DCWithEnum (); arr [1].colors = Colors.Green;
835                         using (XmlWriter w = writer) {
836                                 ser.WriteObject (w, arr);
837                         }
838                 }
839
840                 [Test]
841                 public void SerializerDCArray2Xml ()
842                 {
843                         StringWriter sw = new StringWriter ();
844                         SerializerDCArray2 (XmlWriter.Create (sw, settings));
845                         Assert.AreEqual (
846                                 @"<root type=""array""><item __type=""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"" type=""object""><_colors type=""number"">0</_colors></item><item __type=""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"" type=""object""><Foo>hello</Foo></item></root>",
847                                 sw.ToString ());
848                 }
849
850                 [Test]
851                 public void SerializerDCArray2Json ()
852                 {
853                         MemoryStream ms = new MemoryStream ();
854                         SerializerDCArray2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
855                         Assert.AreEqual (
856                                 @"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
857                                 Encoding.UTF8.GetString (ms.ToArray ()));
858                 }
859
860                 void SerializerDCArray2 (XmlWriter writer)
861                 {
862                         List<Type> known = new List<Type> ();
863                         known.Add (typeof (DCWithEnum));
864                         known.Add (typeof (DCSimple1));
865                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (object []), known);
866                         object [] arr = new object [2];
867                         arr [0] = new DCWithEnum (); ((DCWithEnum)arr [0]).colors = Colors.Red;
868                         arr [1] = new DCSimple1 (); ((DCSimple1) arr [1]).Foo = "hello";
869
870                         using (XmlWriter w = writer) {
871                                 ser.WriteObject (w, arr);
872                         }
873                 }
874
875                 [Test]
876                 public void SerializerDCArray3Xml ()
877                 {
878                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
879                         StringWriter sw = new StringWriter ();
880                         int [] arr = new int [2];
881                         arr [0] = 1; arr [1] = 2;
882
883                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
884                                 ser.WriteObject (w, arr);
885                         }
886
887                         Assert.AreEqual (
888                                 @"<root type=""array""><item type=""number"">1</item><item type=""number"">2</item></root>",
889                                 sw.ToString ());
890                 }
891
892                 [Test]
893                 public void SerializerDCArray3Json ()
894                 {
895                         MemoryStream ms = new MemoryStream ();
896                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
897                         int [] arr = new int [2];
898                         arr [0] = 1; arr [1] = 2;
899
900                         using (XmlWriter w = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
901                                 ser.WriteObject (w, arr);
902                         }
903
904                         Assert.AreEqual (
905                                 @"[1,2]",
906                                 Encoding.UTF8.GetString (ms.ToArray ()));
907                 }
908
909                 [Test]
910                 // ... so, non-JSON XmlWriter is still accepted.
911                 public void SerializeNonDCArrayXml ()
912                 {
913                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
914                         StringWriter sw = new StringWriter ();
915                         using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
916                                 ser.WriteObject (xw, new SerializeNonDCArrayType ());
917                         }
918                         Assert.AreEqual (@"<root type=""object""><IPAddresses type=""array"" /></root>",
919                                 sw.ToString ());
920                 }
921
922                 [Test]
923                 public void SerializeNonDCArrayJson ()
924                 {
925                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
926                         MemoryStream ms = new MemoryStream ();
927                         using (XmlWriter xw = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
928                                 ser.WriteObject (xw, new SerializeNonDCArrayType ());
929                         }
930                         Assert.AreEqual (@"{""IPAddresses"":[]}",
931                                 Encoding.UTF8.GetString (ms.ToArray ()));
932                 }
933
934                 [Test]
935                 public void SerializeNonDCArrayItems ()
936                 {
937                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
938                         StringWriter sw = new StringWriter ();
939                         using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
940                                 SerializeNonDCArrayType obj = new SerializeNonDCArrayType ();
941                                 obj.IPAddresses = new NonDCItem [] {new NonDCItem () { Data = new byte [] {1, 2, 3, 4} } };
942                                 ser.WriteObject (xw, obj);
943                         }
944
945                         XmlDocument doc = new XmlDocument ();
946                         doc.LoadXml (sw.ToString ());
947                         XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
948                         nsmgr.AddNamespace ("s", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization");
949                         nsmgr.AddNamespace ("n", "http://schemas.datacontract.org/2004/07/System.Net");
950                         nsmgr.AddNamespace ("a", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
951
952                         Assert.AreEqual (1, doc.SelectNodes ("/root/IPAddresses/item", nsmgr).Count, "#1");
953                         XmlElement el = doc.SelectSingleNode ("/root/IPAddresses/item/Data", nsmgr) as XmlElement;
954                         Assert.IsNotNull (el, "#3");
955                         Assert.AreEqual (4, el.SelectNodes ("item", nsmgr).Count, "#4");
956                 }
957
958                 [Test]
959                 public void MaxItemsInObjectGraph1 ()
960                 {
961                         // object count == maximum
962                         DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCEmpty), null, 1, false, null, false);
963                         s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCEmpty ());
964                 }
965
966                 [Test]
967                 [ExpectedException (typeof (SerializationException))]
968                 public void MaxItemsInObjectGraph2 ()
969                 {
970                         // object count > maximum
971                         DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1), null, 1, false, null, false);
972                         s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCSimple1 ());
973                 }
974
975                 [Test]
976                 public void DeserializeString ()
977                 {
978                         Assert.AreEqual ("ABC", Deserialize ("\"ABC\"", typeof (string)));
979                 }
980
981                 [Test]
982                 public void DeserializeInt ()
983                 {
984                         Assert.AreEqual (5, Deserialize ("5", typeof (int)));
985                 }
986
987                 [Test]
988                 public void DeserializeArray ()
989                 {
990                         int [] ret = (int []) Deserialize ("[5,6,7]", typeof (int []));
991                         Assert.AreEqual (5, ret [0], "#1");
992                         Assert.AreEqual (6, ret [1], "#2");
993                         Assert.AreEqual (7, ret [2], "#3");
994                 }
995
996                 [Test]
997                 public void DeserializeArrayUntyped ()
998                 {
999                         object [] ret = (object []) Deserialize ("[5,6,7]", typeof (object []));
1000                         Assert.AreEqual (5, ret [0], "#1");
1001                         Assert.AreEqual (6, ret [1], "#2");
1002                         Assert.AreEqual (7, ret [2], "#3");
1003                 }
1004
1005                 [Test]
1006                 public void DeserializeMixedArray ()
1007                 {
1008                         object [] ret = (object []) Deserialize ("[5,\"6\",false]", typeof (object []));
1009                         Assert.AreEqual (5, ret [0], "#1");
1010                         Assert.AreEqual ("6", ret [1], "#2");
1011                         Assert.AreEqual (false, ret [2], "#3");
1012                 }
1013
1014                 [Test]
1015                 [ExpectedException (typeof (SerializationException))]
1016                 public void DeserializeEmptyAsString ()
1017                 {
1018                         // it somehow expects "root" which should have been already consumed.
1019                         Deserialize ("", typeof (string));
1020                 }
1021
1022                 [Test]
1023                 [ExpectedException (typeof (SerializationException))]
1024                 public void DeserializeEmptyAsInt ()
1025                 {
1026                         // it somehow expects "root" which should have been already consumed.
1027                         Deserialize ("", typeof (int));
1028                 }
1029
1030                 [Test]
1031                 [ExpectedException (typeof (SerializationException))]
1032                 public void DeserializeEmptyAsDBNull ()
1033                 {
1034                         // it somehow expects "root" which should have been already consumed.
1035                         Deserialize ("", typeof (DBNull));
1036                 }
1037
1038                 [Test]
1039                 public void DeserializeEmptyObjectAsString ()
1040                 {
1041                         // looks like it is converted to ""
1042                         Assert.AreEqual (String.Empty, Deserialize ("{}", typeof (string)));
1043                 }
1044
1045                 [Test]
1046                 [ExpectedException (typeof (SerializationException))]
1047                 public void DeserializeEmptyObjectAsInt ()
1048                 {
1049                         Deserialize ("{}", typeof (int));
1050                 }
1051
1052                 [Test]
1053                 public void DeserializeEmptyObjectAsDBNull ()
1054                 {
1055                         Assert.AreEqual (DBNull.Value, Deserialize ("{}", typeof (DBNull)));
1056                 }
1057
1058                 [Test]
1059                 [ExpectedException (typeof (SerializationException))]
1060                 public void DeserializeEnumByName ()
1061                 {
1062                         // enum is parsed into long
1063                         Deserialize (@"""Red""", typeof (Colors));
1064                 }
1065
1066                 [Test]
1067                 public void DeserializeEnum2 ()
1068                 {
1069                         object o = Deserialize ("0", typeof (Colors));
1070
1071                         Assert.AreEqual (typeof (Colors), o.GetType (), "#de3");
1072                         Colors c = (Colors) o;
1073                         Assert.AreEqual (Colors.Red, c, "#de4");
1074                 }
1075                 
1076                 [Test]
1077                 [ExpectedException (typeof (SerializationException))]
1078                 public void DeserializeEnumInvalid ()
1079                 {
1080                         Deserialize ("", typeof (Colors));
1081                 }
1082
1083                 [Test]
1084                 [ExpectedException (typeof (SerializationException))]
1085                 [Category ("NotDotNet")] // 0.0 is an invalid Colors value.
1086                 public void DeserializeEnumInvalid3 ()
1087                 {
1088                         //"0.0" instead of "0"
1089                         Deserialize (
1090                                 "0.0",
1091                                 typeof (Colors));
1092                 }
1093
1094                 [Test]
1095                 public void DeserializeEnumWithDC ()
1096                 {
1097                         object o = Deserialize ("0", typeof (ColorsWithDC));
1098                         
1099                         Assert.AreEqual (typeof (ColorsWithDC), o.GetType (), "#de5");
1100                         ColorsWithDC cdc = (ColorsWithDC) o;
1101                         Assert.AreEqual (ColorsWithDC.Red, o, "#de6");
1102                 }
1103
1104                 [Test]
1105                 [ExpectedException (typeof (SerializationException))]
1106                 [Category ("NotDotNet")] // 4 is an invalid Colors value.
1107                 [Category ("NotWorking")]
1108                 public void DeserializeEnumWithDCInvalid ()
1109                 {
1110                         Deserialize (
1111                                 "4",
1112                                 typeof (ColorsWithDC));
1113                 }
1114
1115                 [Test]
1116                 public void DeserializeDCWithEnum ()
1117                 {
1118                         object o = Deserialize (
1119                                 "{\"_colors\":0}",
1120                                 typeof (DCWithEnum));
1121
1122                         Assert.AreEqual (typeof (DCWithEnum), o.GetType (), "#de7");
1123                         DCWithEnum dc = (DCWithEnum) o;
1124                         Assert.AreEqual (Colors.Red, dc.colors, "#de8");
1125                 }
1126
1127                 [Test]
1128                 public void ReadObjectVerifyObjectNameFalse ()
1129                 {
1130                         string xml = @"<any><Member1>bar</Member1></any>";
1131                         object o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1132                                 .ReadObject (XmlReader.Create (new StringReader (xml)), false);
1133                         Assert.IsTrue (o is VerifyObjectNameTestData, "#1");
1134
1135                         string xml2 = @"<any><x:Member1 xmlns:x=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">bar</x:Member1></any>";
1136                         o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1137                                 .ReadObject (XmlReader.Create (new StringReader (xml2)), false);
1138                         Assert.IsTrue (o is VerifyObjectNameTestData, "#2");
1139                 }
1140
1141                 [Test]
1142                 [ExpectedException (typeof (SerializationException))]
1143                 public void ReadObjectVerifyObjectNameTrue ()
1144                 {
1145                         string xml = @"<any><Member1>bar</Member1></any>";
1146                         new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1147                                 .ReadObject (XmlReader.Create (new StringReader (xml)), true);
1148                 }
1149
1150                 [Test] // member name is out of scope
1151                 public void ReadObjectVerifyObjectNameTrue2 ()
1152                 {
1153                         string xml = @"<root><Member2>bar</Member2></root>";
1154                         new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1155                                 .ReadObject (XmlReader.Create (new StringReader (xml)), true);
1156                 }
1157
1158                 [Test]
1159                 public void ReadTypedObjectJson ()
1160                 {
1161                         object o = Deserialize (@"{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}", typeof (DCWithEnum));
1162                         Assert.AreEqual (typeof (DCWithEnum), o.GetType ());
1163                 }
1164
1165                 [Test]
1166                 public void ReadObjectDCArrayJson ()
1167                 {
1168                         object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}]",
1169                                 typeof (object []), typeof (DCWithEnum));
1170                         Assert.AreEqual (typeof (object []), o.GetType (), "#1");
1171                         object [] arr = (object []) o;
1172                         Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
1173                 }
1174
1175                 [Test]
1176                 public void ReadObjectDCArray2Json ()
1177                 {
1178                         object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
1179                                 typeof (object []), typeof (DCWithEnum), typeof (DCSimple1));
1180                         Assert.AreEqual (typeof (object []), o.GetType (), "#1");
1181                         object [] arr = (object []) o;
1182                         Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
1183                         Assert.AreEqual (typeof (DCSimple1), arr [1].GetType (), "#3");
1184                 }
1185
1186                 private object Deserialize (string xml, Type type, params Type [] knownTypes)
1187                 {
1188                         DataContractJsonSerializer ser = new DataContractJsonSerializer (type, knownTypes);
1189                         XmlReader xr = JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (xml), new XmlDictionaryReaderQuotas ());
1190                         return ser.ReadObject (xr);
1191                 }
1192
1193                 [Test]
1194                 public void IsStartObject ()
1195                 {
1196                         DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1));
1197                         Assert.IsTrue (s.IsStartObject (XmlReader.Create (new StringReader ("<root></root>"))), "#1");
1198                         Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<dummy></dummy>"))), "#2");
1199                         Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<Foo></Foo>"))), "#3");
1200                         Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<root xmlns='urn:foo'></root>"))), "#4");
1201                 }
1202
1203                 [Test]
1204                 public void SerializeNonDC2 ()
1205                 {
1206                         var ser = new DataContractJsonSerializer (typeof (TestData));
1207                         StringWriter sw = new StringWriter ();
1208                         var obj = new TestData () { Foo = "foo", Bar = "bar", Baz = "baz" };
1209
1210                         // XML
1211                         using (var xw = XmlWriter.Create (sw))
1212                                 ser.WriteObject (xw, obj);
1213                         var s = sw.ToString ();
1214                         // since the order is not preserved, we compare only contents.
1215                         Assert.IsTrue (s.IndexOf ("<Foo>foo</Foo>") > 0, "#1-1");
1216                         Assert.IsTrue (s.IndexOf ("<Bar>bar</Bar>") > 0, "#1-2");
1217                         Assert.IsFalse (s.IndexOf ("<Baz>baz</Baz>") > 0, "#1-3");
1218
1219                         // JSON
1220                         MemoryStream ms = new MemoryStream ();
1221                         using (var xw = JsonReaderWriterFactory.CreateJsonWriter (ms))
1222                                 ser.WriteObject (ms, obj);
1223                         s = new StreamReader (new MemoryStream (ms.ToArray ())).ReadToEnd ().Replace ('"', '/');
1224                         // since the order is not preserved, we compare only contents.
1225                         Assert.IsTrue (s.IndexOf ("/Foo/:/foo/") > 0, "#2-1");
1226                         Assert.IsTrue (s.IndexOf ("/Bar/:/bar/") > 0, "#2-2");
1227                         Assert.IsFalse (s.IndexOf ("/Baz/:/baz/") > 0, "#2-3");
1228                 }
1229
1230                 [Test]
1231                 public void AlwaysEmitTypeInformation ()
1232                 {
1233                         var ms = new MemoryStream ();
1234                         var ds = new DataContractJsonSerializer (typeof (string), "root", null, 10, false, null, true);
1235                         ds.WriteObject (ms, "foobar");
1236                         var s = Encoding.UTF8.GetString (ms.ToArray ());
1237                         Assert.AreEqual ("\"foobar\"", s, "#1");
1238                 }
1239
1240                 [Test]
1241                 public void AlwaysEmitTypeInformation2 ()
1242                 {
1243                         var ms = new MemoryStream ();
1244                         var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, true);
1245                         ds.WriteObject (ms, new TestData () { Foo = "foo"});
1246                         var s = Encoding.UTF8.GetString (ms.ToArray ());
1247                         Assert.AreEqual (@"{""__type"":""TestData:#MonoTests.System.Runtime.Serialization.Json"",""Bar"":null,""Foo"":""foo""}", s, "#1");
1248                 }
1249
1250                 [Test]
1251                 public void AlwaysEmitTypeInformation3 ()
1252                 {
1253                         var ms = new MemoryStream ();
1254                         var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, false);
1255                         ds.WriteObject (ms, new TestData () { Foo = "foo"});
1256                         var s = Encoding.UTF8.GetString (ms.ToArray ());
1257                         Assert.AreEqual (@"{""Bar"":null,""Foo"":""foo""}", s, "#1");
1258                 }
1259
1260                 [Test]
1261                 public void TestNonpublicDeserialization ()
1262                 {
1263                         string s1= @"{""Bar"":""bar"", ""Foo"":""foo"", ""Baz"":""baz""}";
1264                         TestData o1 = ((TestData)(new DataContractJsonSerializer (typeof (TestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s1), new XmlDictionaryReaderQuotas ()))));
1265
1266                         Assert.AreEqual (null, o1.Baz, "#1");
1267
1268                         string s2 = @"{""TestData"":[{""key"":""key1"",""value"":""value1""}]}";
1269                         KeyValueTestData o2 = ((KeyValueTestData)(new DataContractJsonSerializer (typeof (KeyValueTestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s2), new XmlDictionaryReaderQuotas ()))));
1270
1271                         Assert.AreEqual (1, o2.TestData.Count, "#2");
1272                         Assert.AreEqual ("key1", o2.TestData[0].Key, "#3");
1273                         Assert.AreEqual ("value1", o2.TestData[0].Value, "#4");
1274                 }
1275
1276                 // [Test] use this case if you want to check lame silverlight parser behavior. Seealso #549756
1277                 public void QuotelessDeserialization ()
1278                 {
1279                         string s1 = @"{FooMember:""value""}";
1280                         var ds = new DataContractJsonSerializer (typeof (DCWithName));
1281                         ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s1)));
1282
1283                         string s2 = @"{FooMember:"" \""{dummy:string}\""""}";
1284                         ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s2)));
1285                 }
1286
1287                 [Test]
1288                 [Category ("NotWorking")]
1289                 public void TypeIsNotPartsOfKnownTypes ()
1290                 {
1291                         var dcs = new DataContractSerializer (typeof (string));
1292                         Assert.AreEqual (0, dcs.KnownTypes.Count, "KnownTypes #1");
1293                         var dcjs = new DataContractJsonSerializer (typeof (string));
1294                         Assert.AreEqual (0, dcjs.KnownTypes.Count, "KnownTypes #2");
1295                 }
1296
1297                 [Test]
1298                 public void ReadWriteNullObject ()
1299                 {
1300                         DataContractJsonSerializer dcjs = new DataContractJsonSerializer (typeof (string));
1301                         using (MemoryStream ms = new MemoryStream ()) {
1302                                 dcjs.WriteObject (ms, null);
1303                                 ms.Position = 0;
1304                                 using (StreamReader sr = new StreamReader (ms)) {
1305                                         string data = sr.ReadToEnd ();
1306                                         Assert.AreEqual ("null", data, "WriteObject(stream,null)");
1307
1308                                         ms.Position = 0;
1309                                         Assert.IsNull (dcjs.ReadObject (ms), "ReadObject(stream)");
1310                                 }
1311                         };
1312                 }
1313
1314                 object ReadWriteObject (Type type, object obj, string expected)
1315                 {
1316                         using (MemoryStream ms = new MemoryStream ()) {
1317                                 DataContractJsonSerializer dcjs = new DataContractJsonSerializer (type);
1318                                 dcjs.WriteObject (ms, obj);
1319                                 ms.Position = 0;
1320                                 using (StreamReader sr = new StreamReader (ms)) {
1321                                         Assert.AreEqual (expected, sr.ReadToEnd (), "WriteObject");
1322
1323                                         ms.Position = 0;
1324                                         return dcjs.ReadObject (ms);
1325                                 }
1326                         }
1327                 }
1328
1329                 [Test]
1330                 [Ignore ("Wrong test case. See bug #573691")]
1331                 public void ReadWriteObject_Single_SpecialCases ()
1332                 {
1333                         Assert.IsTrue (Single.IsNaN ((float) ReadWriteObject (typeof (float), Single.NaN, "NaN")));
1334                         Assert.IsTrue (Single.IsNegativeInfinity ((float) ReadWriteObject (typeof (float), Single.NegativeInfinity, "-INF")));
1335                         Assert.IsTrue (Single.IsPositiveInfinity ((float) ReadWriteObject (typeof (float), Single.PositiveInfinity, "INF")));
1336                 }
1337
1338                 [Test]
1339                 [Ignore ("Wrong test case. See bug #573691")]
1340                 public void ReadWriteObject_Double_SpecialCases ()
1341                 {
1342                         Assert.IsTrue (Double.IsNaN ((double) ReadWriteObject (typeof (double), Double.NaN, "NaN")));
1343                         Assert.IsTrue (Double.IsNegativeInfinity ((double) ReadWriteObject (typeof (double), Double.NegativeInfinity, "-INF")));
1344                         Assert.IsTrue (Double.IsPositiveInfinity ((double) ReadWriteObject (typeof (double), Double.PositiveInfinity, "INF")));
1345                 }
1346
1347                 [Test]
1348                 public void ReadWriteDateTime ()
1349                 {
1350                         var ms = new MemoryStream ();
1351                         DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (Query));
1352                         Query query = new Query () {
1353                                 StartDate = new DateTime (2010, 3, 4, 5, 6, 7),
1354                                 EndDate = new DateTime (2010, 4, 5, 6, 7, 8)
1355                                 };
1356                         serializer.WriteObject (ms, query);
1357                         Assert.AreEqual ("{\"StartDate\":\"\\/Date(1267679167000)\\/\",\"EndDate\":\"\\/Date(1270447628000)\\/\"}", Encoding.UTF8.GetString (ms.ToArray ()), "#1");
1358                         ms.Position = 0;
1359                         Console.WriteLine (new StreamReader (ms).ReadToEnd ());
1360                         ms.Position = 0;
1361                         var q = (Query) serializer.ReadObject(ms);
1362                         Assert.AreEqual (query.StartDate, q.StartDate, "#2");
1363                         Assert.AreEqual (query.EndDate, q.EndDate, "#3");
1364                 }
1365                 
1366                 [Test]
1367                 public void DeserializeNullMember ()
1368                 {
1369                         var ds = new DataContractJsonSerializer (typeof (ClassA));
1370                         var stream = new MemoryStream ();
1371                         var a = new ClassA ();
1372                         ds.WriteObject (stream, a);
1373                         stream.Position = 0;
1374                         a = (ClassA) ds.ReadObject (stream);
1375                         Assert.IsNull (a.B, "#1");
1376                 }
1377
1378                 [Test]
1379                 public void OnDeserializationMethods ()
1380                 {
1381                         var ds = new DataContractJsonSerializer (typeof (GSPlayerListErg));
1382                         var obj = new GSPlayerListErg ();
1383                         var ms = new MemoryStream ();
1384                         ds.WriteObject (ms, obj);
1385                         ms.Position = 0;
1386                         ds.ReadObject (ms);
1387                         Assert.IsTrue (GSPlayerListErg.A, "A");
1388                         Assert.IsTrue (GSPlayerListErg.B, "B");
1389                         Assert.IsTrue (GSPlayerListErg.C, "C");
1390                 }
1391                 
1392                 [Test]
1393                 public void WriteChar ()
1394                 {
1395                         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (CharTest));
1396                         using (MemoryStream ms = new MemoryStream()) {
1397                                 serializer.WriteObject(ms, new CharTest ());
1398                                 ms.Position = 0L;
1399                                 using (StreamReader reader = new StreamReader(ms)) {
1400                                         reader.ReadToEnd();
1401                                 }
1402                         }
1403                 }
1404
1405                 [Test]
1406                 public void DictionarySerialization ()
1407                 {
1408                         var dict = new MyDictionary<string,string> ();
1409                         dict.Add ("key", "value");
1410                         var serializer = new DataContractJsonSerializer (dict.GetType ());
1411                         var stream = new MemoryStream ();
1412                         serializer.WriteObject (stream, dict);
1413                         stream.Position = 0;
1414
1415                         Assert.AreEqual ("[{\"Key\":\"key\",\"Value\":\"value\"}]", new StreamReader (stream).ReadToEnd (), "#1");
1416                         stream.Position = 0;
1417                         dict = (MyDictionary<string,string>) serializer.ReadObject (stream);
1418                         Assert.AreEqual (1, dict.Count, "#2");
1419                         Assert.AreEqual ("value", dict ["key"], "#3");
1420                 }
1421         }
1422         
1423         public class CharTest
1424         {
1425                 public char Foo;
1426         }
1427
1428         public class TestData
1429         {
1430                 public string Foo { get; set; }
1431                 public string Bar { get; set; }
1432                 internal string Baz { get; set; }
1433         }
1434
1435         public enum Colors {
1436                 Red, Green, Blue
1437         }
1438
1439         [DataContract (Name = "_ColorsWithDC")]
1440         public enum ColorsWithDC {
1441
1442                 [EnumMember (Value = "_Red")]
1443                 Red, 
1444                 [EnumMember]
1445                 Green, 
1446                 Blue
1447         }
1448
1449
1450         public enum ColorsEnumMemberNoDC {
1451                 [EnumMember (Value = "_Red")]
1452                 Red, 
1453                 [EnumMember]
1454                 Green, 
1455                 Blue
1456         }
1457
1458         [DataContract]
1459         public class DCWithEnum {
1460                 [DataMember (Name = "_colors")]
1461                 public Colors colors;
1462         }
1463
1464         [DataContract]
1465         public class DCEmpty
1466         {
1467                 // serializer doesn't touch it.
1468                 public string Foo = "TEST";
1469         }
1470
1471         [DataContract]
1472         public class DCSimple1
1473         {
1474                 [DataMember]
1475                 public string Foo = "TEST";
1476         }
1477
1478         [DataContract]
1479         public class DCHasNonDC
1480         {
1481                 [DataMember]
1482                 public NonDC Hoge= new NonDC ();
1483         }
1484
1485         public class NonDC
1486         {
1487                 public string Whee = "whee!";
1488         }
1489
1490         [DataContract]
1491         public class DCHasSerializable
1492         {
1493                 [DataMember]
1494                 public SimpleSer1 Ser = new SimpleSer1 ();
1495         }
1496
1497         [DataContract (Name = "Foo")]
1498         public class DCWithName
1499         {
1500                 [DataMember (Name = "FooMember")]
1501                 public string DMWithName = "value";
1502         }
1503
1504         [DataContract (Name = "")]
1505         public class DCWithEmptyName
1506         {
1507                 [DataMember]
1508                 public string Foo;
1509         }
1510
1511         [DataContract (Name = null)]
1512         public class DCWithNullName
1513         {
1514                 [DataMember]
1515                 public string Foo;
1516         }
1517
1518         [DataContract (Namespace = "")]
1519         public class DCWithEmptyNamespace
1520         {
1521                 [DataMember]
1522                 public string Foo;
1523         }
1524
1525         [Serializable]
1526         public class SimpleSer1
1527         {
1528                 public string Doh = "doh!";
1529         }
1530
1531         public class Wrapper
1532         {
1533                 [DataContract]
1534                 public class DCWrapped
1535                 {
1536                 }
1537         }
1538
1539         [DataContract]
1540         public class CollectionContainer
1541         {
1542                 Collection<string> items = new Collection<string> ();
1543
1544                 [DataMember]
1545                 public Collection<string> Items {
1546                         get { return items; }
1547                 }
1548         }
1549
1550         [CollectionDataContract]
1551         public class DataCollection<T> : Collection<T>
1552         {
1553         }
1554
1555         [DataContract]
1556         public class DataCollectionContainer
1557         {
1558                 DataCollection<string> items = new DataCollection<string> ();
1559
1560                 [DataMember]
1561                 public DataCollection<string> Items {
1562                         get { return items; }
1563                 }
1564         }
1565
1566         [DataContract]
1567         class SerializeNonDCArrayType
1568         {
1569                 [DataMember]
1570                 public NonDCItem [] IPAddresses = new NonDCItem [0];
1571         }
1572
1573         public class NonDCItem
1574         {
1575                 public byte [] Data { get; set; }
1576         }
1577
1578         [DataContract]
1579         public class VerifyObjectNameTestData
1580         {
1581                 [DataMember]
1582                 string Member1 = "foo";
1583         }
1584
1585         [Serializable]
1586         public class KeyValueTestData {
1587                 public List<KeyValuePair<string,string>> TestData = new List<KeyValuePair<string,string>>();
1588         }
1589
1590         [DataContract] // bug #586169
1591         public class Query
1592         {
1593                 [DataMember (Order=1)]
1594                 public DateTime StartDate { get; set; }
1595                 [DataMember (Order=2)]
1596                 public DateTime EndDate { get; set; }
1597         }
1598
1599         public class ClassA {
1600                 public ClassB B { get; set; }
1601         }
1602
1603         public class ClassB
1604         {
1605         }
1606
1607         public class GSPlayerListErg
1608         {
1609                 public GSPlayerListErg ()
1610                 {
1611                         Init ();
1612                 }
1613
1614                 void Init ()
1615                 {
1616                         C = true;
1617                 }
1618
1619                 [OnDeserializing]
1620                 public void OnDeserializing (StreamingContext c)
1621                 {
1622                         A = true;
1623                         Init ();
1624                 }
1625
1626                 [OnDeserialized]
1627                 void OnDeserialized (StreamingContext c)
1628                 {
1629                         B = true;
1630                 }
1631
1632                 public static bool A, B, C;
1633
1634                 [DataMember (Name = "T")]
1635                 public long CodedServerTimeUTC { get; set; }
1636                 public DateTime ServerTimeUTC { get; set; }
1637         }
1638 }
1639
1640 [DataContract]
1641 class GlobalSample1
1642 {
1643 }
1644
1645
1646 public class MyDictionary<K, V> : System.Collections.Generic.IDictionary<K, V>
1647 {
1648         Dictionary<K,V> dic = new Dictionary<K,V> ();
1649
1650         public void Add (K key, V value)
1651         {
1652                 dic.Add (key,  value);
1653         }
1654
1655         public bool ContainsKey (K key)
1656         {
1657                 return dic.ContainsKey (key);
1658         }
1659
1660         public ICollection<K> Keys {
1661                 get { return dic.Keys; }
1662         }
1663
1664         public bool Remove (K key)
1665         {
1666                 return dic.Remove (key);
1667         }
1668
1669         public bool TryGetValue (K key, out V value)
1670         {
1671                 return dic.TryGetValue (key, out value);
1672         }
1673
1674         public ICollection<V> Values {
1675                 get { return dic.Values; }
1676         }
1677
1678         public V this [K key] {
1679                 get { return dic [key]; }
1680                 set { dic [key] = value; }
1681         }
1682
1683         IEnumerator IEnumerable.GetEnumerator ()
1684         {
1685                 return dic.GetEnumerator ();
1686         }
1687
1688         ICollection<KeyValuePair<K,V>> Coll {
1689                 get { return (ICollection<KeyValuePair<K,V>>) dic; }
1690         }
1691
1692         public void Add (KeyValuePair<K, V> item)
1693         {
1694                 Coll.Add (item);
1695         }
1696
1697         public void Clear ()
1698         {
1699                 dic.Clear ();
1700         }
1701
1702         public bool Contains (KeyValuePair<K, V> item)
1703         {
1704                 return Coll.Contains (item);
1705         }
1706
1707         public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
1708         {
1709                 Coll.CopyTo (array, arrayIndex);
1710         }
1711
1712         public int Count {
1713                 get { return dic.Count; }
1714         }
1715
1716         public bool IsReadOnly {
1717                 get { return Coll.IsReadOnly; }
1718         }
1719
1720         public bool Remove (KeyValuePair<K, V> item)
1721         {
1722                 return Coll.Remove (item);
1723         }
1724
1725         public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
1726         {
1727                 return Coll.GetEnumerator ();
1728         }
1729 }
1730