Changed UploadStringAsync to handle UploadString encapsulated exceptions.
[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 //      Antoine Cailliau <antoinecailliau@gmail.com>
8 //
9 // Copyright (C) 2005-2007 Novell, Inc.  http://www.novell.com
10
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 //
33 // This test code contains tests for DataContractJsonSerializer, which is
34 // imported from DataContractSerializerTest.cs.
35 //
36
37 using System;
38 using System.Collections;
39 using System.Collections.Generic;
40 using System.Collections.ObjectModel;
41 using System.IO;
42 using System.Net;
43 using System.Runtime.Serialization;
44 using System.Runtime.Serialization.Json;
45 using System.Text;
46 using System.Xml;
47 using NUnit.Framework;
48
49 namespace MonoTests.System.Runtime.Serialization.Json
50 {
51         [TestFixture]
52         public class DataContractJsonSerializerTest
53         {
54                 static readonly XmlWriterSettings settings;
55
56                 static DataContractJsonSerializerTest ()
57                 {
58                         settings = new XmlWriterSettings ();
59                         settings.OmitXmlDeclaration = true;
60                 }
61
62                 [DataContract]
63                 class Sample1
64                 {
65                         [DataMember]
66                         public string Member1;
67                 }
68
69                 [Test]
70                 [ExpectedException (typeof (ArgumentNullException))]
71                 public void ConstructorTypeNull ()
72                 {
73                         new DataContractJsonSerializer (null);
74                 }
75
76                 [Test]
77                 public void ConstructorKnownTypesNull ()
78                 {
79                         // null knownTypes is allowed.
80                         new DataContractJsonSerializer (typeof (Sample1), (IEnumerable<Type>) null);
81                         new DataContractJsonSerializer (typeof (Sample1), "Foo", null);
82                 }
83
84                 [Test]
85                 [ExpectedException (typeof (ArgumentNullException))]
86                 public void ConstructorNameNull ()
87                 {
88                         new DataContractJsonSerializer (typeof (Sample1), (string) null);
89                 }
90
91                 [Test]
92                 [ExpectedException (typeof (ArgumentOutOfRangeException))]
93                 public void ConstructorNegativeMaxObjects ()
94                 {
95                         new DataContractJsonSerializer (typeof (Sample1), "Sample1",
96                                 null, -1, false, null, false);
97                 }
98
99                 [Test]
100                 public void ConstructorMisc ()
101                 {
102                         new DataContractJsonSerializer (typeof (GlobalSample1)).WriteObject (new MemoryStream (), new GlobalSample1 ());
103                 }
104
105                 [Test]
106                 public void WriteObjectContent ()
107                 {
108                         StringWriter sw = new StringWriter ();
109                         using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
110                                 DataContractJsonSerializer ser =
111                                         new DataContractJsonSerializer (typeof (string));
112                                 xw.WriteStartElement ("my-element");
113                                 ser.WriteObjectContent (xw, "TEST STRING");
114                                 xw.WriteEndElement ();
115                         }
116                         Assert.AreEqual ("<my-element>TEST STRING</my-element>",
117                                 sw.ToString ());
118                 }
119
120                 // int
121
122                 [Test]
123                 public void SerializeIntXml ()
124                 {
125                         StringWriter sw = new StringWriter ();
126                         SerializeInt (XmlWriter.Create (sw, settings));
127                         Assert.AreEqual (
128                                 @"<root type=""number"">1</root>",
129                                 sw.ToString ());
130                 }
131
132                 [Test]
133                 public void SerializeIntJson ()
134                 {
135                         MemoryStream ms = new MemoryStream ();
136                         SerializeInt (JsonReaderWriterFactory.CreateJsonWriter (ms));
137                         Assert.AreEqual (
138                                 "1",
139                                 Encoding.UTF8.GetString (ms.ToArray ()));
140                 }
141
142                 void SerializeInt (XmlWriter writer)
143                 {
144                         DataContractJsonSerializer ser =
145                                 new DataContractJsonSerializer (typeof (int));
146                         using (XmlWriter w = writer) {
147                                 ser.WriteObject (w, 1);
148                         }
149                 }
150
151                 // int, with rootName
152
153                 [Test]
154                 public void SerializeIntXmlWithRootName ()
155                 {
156                         StringWriter sw = new StringWriter ();
157                         SerializeIntWithRootName (XmlWriter.Create (sw, settings));
158                         Assert.AreEqual (
159                                 @"<myroot type=""number"">1</myroot>",
160                                 sw.ToString ());
161                 }
162
163                 [Test]
164                 // since JsonWriter supports only "root" as the root name, using
165                 // XmlWriter from JsonReaderWriterFactory will always fail with
166                 // an explicit rootName.
167                 [ExpectedException (typeof (SerializationException))]
168                 public void SerializeIntJsonWithRootName ()
169                 {
170                         MemoryStream ms = new MemoryStream ();
171                         SerializeIntWithRootName (JsonReaderWriterFactory.CreateJsonWriter (ms));
172                         Assert.AreEqual (
173                                 "1",
174                                 Encoding.UTF8.GetString (ms.ToArray ()));
175                 }
176
177                 void SerializeIntWithRootName (XmlWriter writer)
178                 {
179                         DataContractJsonSerializer ser =
180                                 new DataContractJsonSerializer (typeof (int), "myroot");
181                         using (XmlWriter w = writer) {
182                                 ser.WriteObject (w, 1);
183                         }
184                 }
185
186                 // pass typeof(DCEmpty), serialize int
187
188                 [Test]
189                 public void SerializeIntForDCEmptyXml ()
190                 {
191                         StringWriter sw = new StringWriter ();
192                         SerializeIntForDCEmpty (XmlWriter.Create (sw, settings));
193                         Assert.AreEqual (
194                                 @"<root type=""number"">1</root>",
195                                 sw.ToString ());
196                 }
197
198                 [Test]
199                 public void SerializeIntForDCEmptyJson ()
200                 {
201                         MemoryStream ms = new MemoryStream ();
202                         SerializeIntForDCEmpty (JsonReaderWriterFactory.CreateJsonWriter (ms));
203                         Assert.AreEqual (
204                                 "1",
205                                 Encoding.UTF8.GetString (ms.ToArray ()));
206                 }
207
208                 void SerializeIntForDCEmpty (XmlWriter writer)
209                 {
210                         DataContractJsonSerializer ser =
211                                 new DataContractJsonSerializer (typeof (DCEmpty));
212                         using (XmlWriter w = writer) {
213                                 ser.WriteObject (w, 1);
214                         }
215                 }
216
217                 // DCEmpty
218
219                 [Test]
220                 public void SerializeEmptyClassXml ()
221                 {
222                         StringWriter sw = new StringWriter ();
223                         SerializeEmptyClass (XmlWriter.Create (sw, settings));
224                         Assert.AreEqual (
225                                 @"<root type=""object"" />",
226                                 sw.ToString ());
227                 }
228
229                 [Test]
230                 public void SerializeEmptyClassJson ()
231                 {
232                         MemoryStream ms = new MemoryStream ();
233                         SerializeEmptyClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
234                         Assert.AreEqual (
235                                 "{}",
236                                 Encoding.UTF8.GetString (ms.ToArray ()));
237                 }
238
239                 void SerializeEmptyClass (XmlWriter writer)
240                 {
241                         DataContractJsonSerializer ser =
242                                 new DataContractJsonSerializer (typeof (DCEmpty));
243                         using (XmlWriter w = writer) {
244                                 ser.WriteObject (w, new DCEmpty ());
245                         }
246                 }
247
248                 // string (primitive)
249
250                 [Test]
251                 public void SerializePrimitiveStringXml ()
252                 {
253                         StringWriter sw = new StringWriter ();
254                         SerializePrimitiveString (XmlWriter.Create (sw, settings));
255                         Assert.AreEqual (
256                                 "<root>TEST</root>",
257                                 sw.ToString ());
258                 }
259
260                 [Test]
261                 public void SerializePrimitiveStringJson ()
262                 {
263                         MemoryStream ms = new MemoryStream ();
264                         SerializePrimitiveString (JsonReaderWriterFactory.CreateJsonWriter (ms));
265                         Assert.AreEqual (
266                                 @"""TEST""",
267                                 Encoding.UTF8.GetString (ms.ToArray ()));
268                 }
269
270                 void SerializePrimitiveString (XmlWriter writer)
271                 {
272                         XmlObjectSerializer ser =
273                                 new DataContractJsonSerializer (typeof (string));
274                         using (XmlWriter w = writer) {
275                                 ser.WriteObject (w, "TEST");
276                         }
277                 }
278
279                 // QName (primitive but ...)
280
281                 [Test]
282                 public void SerializePrimitiveQNameXml ()
283                 {
284                         StringWriter sw = new StringWriter ();
285                         SerializePrimitiveQName (XmlWriter.Create (sw, settings));
286                         Assert.AreEqual (
287                                 "<root>foo:urn:foo</root>",
288                                 sw.ToString ());
289                 }
290
291                 [Test]
292                 public void SerializePrimitiveQNameJson ()
293                 {
294                         MemoryStream ms = new MemoryStream ();
295                         SerializePrimitiveQName (JsonReaderWriterFactory.CreateJsonWriter (ms));
296                         Assert.AreEqual (
297                                 @"""foo:urn:foo""",
298                                 Encoding.UTF8.GetString (ms.ToArray ()));
299                 }
300
301                 void SerializePrimitiveQName (XmlWriter writer)
302                 {
303                         XmlObjectSerializer ser =
304                                 new DataContractJsonSerializer (typeof (XmlQualifiedName));
305                         using (XmlWriter w = writer) {
306                                 ser.WriteObject (w, new XmlQualifiedName ("foo", "urn:foo"));
307                         }
308                 }
309
310                 // DBNull (primitive)
311
312                 [Test]
313                 public void SerializeDBNullXml ()
314                 {
315                         StringWriter sw = new StringWriter ();
316                         SerializeDBNull (XmlWriter.Create (sw, settings));
317                         Assert.AreEqual (
318                                 @"<root type=""object"" />",
319                                 sw.ToString ());
320                 }
321
322                 [Test]
323                 public void SerializeDBNullJson ()
324                 {
325                         MemoryStream ms = new MemoryStream ();
326                         SerializeDBNull (JsonReaderWriterFactory.CreateJsonWriter (ms));
327                         Assert.AreEqual (
328                                 "{}",
329                                 Encoding.UTF8.GetString (ms.ToArray ()));
330                 }
331
332                 void SerializeDBNull (XmlWriter writer)
333                 {
334                         DataContractJsonSerializer ser =
335                                 new DataContractJsonSerializer (typeof (DBNull));
336                         using (XmlWriter w = writer) {
337                                 ser.WriteObject (w, DBNull.Value);
338                         }
339                 }
340
341                 // DCSimple1
342
343                 [Test]
344                 public void SerializeSimpleClass1Xml ()
345                 {
346                         StringWriter sw = new StringWriter ();
347                         SerializeSimpleClass1 (XmlWriter.Create (sw, settings));
348                         Assert.AreEqual (
349                                 @"<root type=""object""><Foo>TEST</Foo></root>",
350                                 sw.ToString ());
351                 }
352
353                 [Test]
354                 public void SerializeSimpleClass1Json ()
355                 {
356                         MemoryStream ms = new MemoryStream ();
357                         SerializeSimpleClass1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
358                         Assert.AreEqual (
359                                 @"{""Foo"":""TEST""}",
360                                 Encoding.UTF8.GetString (ms.ToArray ()));
361                 }
362
363                 void SerializeSimpleClass1 (XmlWriter writer)
364                 {
365                         DataContractJsonSerializer ser =
366                                 new DataContractJsonSerializer (typeof (DCSimple1));
367                         using (XmlWriter w = writer) {
368                                 ser.WriteObject (w, new DCSimple1 ());
369                         }
370                 }
371
372                 // NonDC
373
374                 [Test]
375                 // NonDC is not a DataContract type.
376                 public void SerializeNonDCOnlyCtor ()
377                 {
378                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
379                 }
380
381                 [Test]
382                 //[ExpectedException (typeof (InvalidDataContractException))]
383                 // NonDC is not a DataContract type.
384                 // UPDATE: non-DataContract types are became valid in RTM.
385                 public void SerializeNonDC ()
386                 {
387                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (NonDC));
388                         using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
389                                 ser.WriteObject (w, new NonDC ());
390                         }
391                 }
392
393                 // DCHasNonDC
394
395                 [Test]
396                 //[ExpectedException (typeof (InvalidDataContractException))]
397                 // DCHasNonDC itself is a DataContract type whose field is
398                 // marked as DataMember but its type is not DataContract.
399                 // UPDATE: non-DataContract types are became valid in RTM.
400                 public void SerializeDCHasNonDC ()
401                 {
402                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasNonDC));
403                         using (XmlWriter w = XmlWriter.Create (TextWriter.Null, settings)) {
404                                 ser.WriteObject (w, new DCHasNonDC ());
405                         }
406                 }
407
408                 // DCHasSerializable
409
410                 [Test]
411                 public void SerializeSimpleSerializable1Xml ()
412                 {
413                         StringWriter sw = new StringWriter ();
414                         SerializeSimpleSerializable1 (XmlWriter.Create (sw, settings));
415                         Assert.AreEqual (
416                                 @"<root type=""object""><Ser type=""object""><Doh>doh!</Doh></Ser></root>",
417                                 sw.ToString ());
418                 }
419
420                 [Test]
421                 public void SerializeSimpleSerializable1Json ()
422                 {
423                         MemoryStream ms = new MemoryStream ();
424                         SerializeSimpleSerializable1 (JsonReaderWriterFactory.CreateJsonWriter (ms));
425                         Assert.AreEqual (
426                                 @"{""Ser"":{""Doh"":""doh!""}}",
427                                 Encoding.UTF8.GetString (ms.ToArray ()));
428                 }
429
430                 // DCHasSerializable itself is DataContract and has a field
431                 // whose type is not contract but serializable.
432                 void SerializeSimpleSerializable1 (XmlWriter writer)
433                 {
434                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCHasSerializable));
435                         using (XmlWriter w = writer) {
436                                 ser.WriteObject (w, new DCHasSerializable ());
437                         }
438                 }
439
440                 [Test]
441                 public void SerializeDCWithNameXml ()
442                 {
443                         StringWriter sw = new StringWriter ();
444                         SerializeDCWithName (XmlWriter.Create (sw, settings));
445                         Assert.AreEqual (
446                                 @"<root type=""object""><FooMember>value</FooMember></root>",
447                                 sw.ToString ());
448                 }
449
450                 [Test]
451                 public void SerializeDCWithNameJson ()
452                 {
453                         MemoryStream ms = new MemoryStream ();
454                         SerializeDCWithName (JsonReaderWriterFactory.CreateJsonWriter (ms));
455                         Assert.AreEqual (
456                                 @"{""FooMember"":""value""}",
457                                 Encoding.UTF8.GetString (ms.ToArray ()));
458                 }
459
460                 void SerializeDCWithName (XmlWriter writer)
461                 {
462                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
463                         using (XmlWriter w = writer) {
464                                 ser.WriteObject (w, new DCWithName ());
465                         }
466                 }
467
468                 [Test]
469                 public void SerializeDCWithEmptyName1 ()
470                 {
471                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyName));
472                         StringWriter sw = new StringWriter ();
473                         DCWithEmptyName dc = new DCWithEmptyName ();
474                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
475                                 try {
476                                         ser.WriteObject (w, dc);
477                                 } catch (InvalidDataContractException) {
478                                         return;
479                                 }
480                         }
481                         Assert.Fail ("Expected InvalidDataContractException");
482                 }
483
484                 [Test]
485                 public void SerializeDCWithEmptyName2 ()
486                 {
487                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithName));
488                         StringWriter sw = new StringWriter ();
489
490                         /* DataContractAttribute.Name == "", not valid */
491                         DCWithEmptyName dc = new DCWithEmptyName ();
492                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
493                                 try {
494                                         ser.WriteObject (w, dc);
495                                 } catch (InvalidDataContractException) {
496                                         return;
497                                 }
498                         }
499                         Assert.Fail ("Expected InvalidDataContractException");
500                 }
501
502                 [Test]
503                 [Category("NotWorking")]
504                 public void SerializeDCWithNullName ()
505                 {
506                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithNullName));
507                         StringWriter sw = new StringWriter ();
508                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
509                                 try {
510                                         /* DataContractAttribute.Name == "", not valid */
511                                         ser.WriteObject (w, new DCWithNullName ());
512                                 } catch (InvalidDataContractException) {
513                                         return;
514                                 }
515                         }
516                         Assert.Fail ("Expected InvalidDataContractException");
517                 }
518
519                 [Test]
520                 public void SerializeDCWithEmptyNamespace1 ()
521                 {
522                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEmptyNamespace));
523                         StringWriter sw = new StringWriter ();
524                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
525                                 ser.WriteObject (w, new DCWithEmptyNamespace ());
526                         }
527                 }
528
529                 [Test]
530                 public void SerializeWrappedClassXml ()
531                 {
532                         StringWriter sw = new StringWriter ();
533                         SerializeWrappedClass (XmlWriter.Create (sw, settings));
534                         Assert.AreEqual (
535                                 @"<root type=""object"" />",
536                                 sw.ToString ());
537                 }
538
539                 [Test]
540                 public void SerializeWrappedClassJson ()
541                 {
542                         MemoryStream ms = new MemoryStream ();
543                         SerializeWrappedClass (JsonReaderWriterFactory.CreateJsonWriter (ms));
544                         Assert.AreEqual (
545                                 "{}",
546                                 Encoding.UTF8.GetString (ms.ToArray ()));
547                 }
548
549                 void SerializeWrappedClass (XmlWriter writer)
550                 {
551                         DataContractJsonSerializer ser =
552                                 new DataContractJsonSerializer (typeof (Wrapper.DCWrapped));
553                         using (XmlWriter w = writer) {
554                                 ser.WriteObject (w, new Wrapper.DCWrapped ());
555                         }
556                 }
557
558                 // CollectionContainer : Items must have a setter. (but became valid in RTM).
559                 [Test]
560                 public void SerializeReadOnlyCollectionMember ()
561                 {
562                         DataContractJsonSerializer ser =
563                                 new DataContractJsonSerializer (typeof (CollectionContainer));
564                         StringWriter sw = new StringWriter ();
565                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
566                                 ser.WriteObject (w, null);
567                         }
568                 }
569
570                 // DataCollectionContainer : Items must have a setter. (but became valid in RTM).
571                 [Test]
572                 public void SerializeReadOnlyDataCollectionMember ()
573                 {
574                         DataContractJsonSerializer ser =
575                                 new DataContractJsonSerializer (typeof (DataCollectionContainer));
576                         StringWriter sw = new StringWriter ();
577                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
578                                 ser.WriteObject (w, null);
579                         }
580                 }
581
582                 [Test]
583                 [Ignore ("https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=409970")]
584                 [ExpectedException (typeof (SerializationException))]
585                 public void DeserializeReadOnlyDataCollection_NullCollection ()
586                 {
587                         DataContractJsonSerializer ser =
588                                 new DataContractJsonSerializer (typeof (CollectionContainer));
589                         StringWriter sw = new StringWriter ();
590                         var c = new CollectionContainer ();
591                         c.Items.Add ("foo");
592                         c.Items.Add ("bar");
593                         using (XmlWriter w = XmlWriter.Create (sw, settings))
594                                 ser.WriteObject (w, c);
595                         // CollectionContainer.Items is null, so it cannot deserialize non-null collection.
596                         using (XmlReader r = XmlReader.Create (new StringReader (sw.ToString ())))
597                                 c = (CollectionContainer) ser.ReadObject (r);
598                 }
599
600                 [Test]
601                 public void SerializeGuidXml ()
602                 {
603                         StringWriter sw = new StringWriter ();
604                         SerializeGuid (XmlWriter.Create (sw, settings));
605                         Assert.AreEqual (
606                                 @"<root>00000000-0000-0000-0000-000000000000</root>",
607                                 sw.ToString ());
608                 }
609
610                 [Test]
611                 public void SerializeGuidJson ()
612                 {
613                         MemoryStream ms = new MemoryStream ();
614                         SerializeGuid (JsonReaderWriterFactory.CreateJsonWriter (ms));
615                         Assert.AreEqual (
616                                 @"""00000000-0000-0000-0000-000000000000""",
617                                 Encoding.UTF8.GetString (ms.ToArray ()));
618                 }
619
620                 void SerializeGuid (XmlWriter writer)
621                 {
622                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Guid));
623                         using (XmlWriter w = writer) {
624                                 ser.WriteObject (w, Guid.Empty);
625                         }
626                 }
627
628                 [Test]
629                 public void SerializeEnumXml ()
630                 {
631                         StringWriter sw = new StringWriter ();
632                         SerializeEnum (XmlWriter.Create (sw, settings));
633                         Assert.AreEqual (
634                                 @"<root type=""number"">0</root>",
635                                 sw.ToString ());
636                 }
637
638                 [Test]
639                 public void SerializeEnumJson ()
640                 {
641                         MemoryStream ms = new MemoryStream ();
642                         SerializeEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
643                         Assert.AreEqual (
644                                 "0",
645                                 Encoding.UTF8.GetString (ms.ToArray ()));
646                 }
647
648                 void SerializeEnum (XmlWriter writer)
649                 {
650                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
651                         using (XmlWriter w = writer) {
652                                 ser.WriteObject (w, new Colors ());
653                         }
654                 }
655
656                 [Test]
657                 public void SerializeEnum2Xml ()
658                 {
659                         StringWriter sw = new StringWriter ();
660                         SerializeEnum2 (XmlWriter.Create (sw, settings));
661                         Assert.AreEqual (
662                                 @"<root type=""number"">0</root>",
663                                 sw.ToString ());
664                 }
665
666                 [Test]
667                 public void SerializeEnum2Json ()
668                 {
669                         MemoryStream ms = new MemoryStream ();
670                         SerializeEnum2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
671                         Assert.AreEqual (
672                                 "0",
673                                 Encoding.UTF8.GetString (ms.ToArray ()));
674                 }
675
676                 void SerializeEnum2 (XmlWriter writer)
677                 {
678                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (Colors));
679                         using (XmlWriter w = writer) {
680                                 ser.WriteObject (w, 0);
681                         }
682                 }
683
684                 [Test] // so, DataContract does not affect here.
685                 public void SerializeEnumWithDCXml ()
686                 {
687                         StringWriter sw = new StringWriter ();
688                         SerializeEnumWithDC (XmlWriter.Create (sw, settings));
689                         Assert.AreEqual (
690                                 @"<root type=""number"">0</root>",
691                                 sw.ToString ());
692                 }
693
694                 [Test]
695                 public void SerializeEnumWithDCJson ()
696                 {
697                         MemoryStream ms = new MemoryStream ();
698                         SerializeEnumWithDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
699                         Assert.AreEqual (
700                                 "0",
701                                 Encoding.UTF8.GetString (ms.ToArray ()));
702                 }
703
704                 void SerializeEnumWithDC (XmlWriter writer)
705                 {
706                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
707                         using (XmlWriter w = writer) {
708                                 ser.WriteObject (w, new ColorsWithDC ());
709                         }
710                 }
711
712                 [Test]
713                 public void SerializeEnumWithNoDCXml ()
714                 {
715                         StringWriter sw = new StringWriter ();
716                         SerializeEnumWithNoDC (XmlWriter.Create (sw, settings));
717                         Assert.AreEqual (
718                                 @"<root type=""number"">0</root>",
719                                 sw.ToString ());
720                 }
721
722                 [Test]
723                 public void SerializeEnumWithNoDCJson ()
724                 {
725                         MemoryStream ms = new MemoryStream ();
726                         SerializeEnumWithNoDC (JsonReaderWriterFactory.CreateJsonWriter (ms));
727                         Assert.AreEqual (
728                                 "0",
729                                 Encoding.UTF8.GetString (ms.ToArray ()));
730                 }
731
732                 void SerializeEnumWithNoDC (XmlWriter writer)
733                 {
734                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsEnumMemberNoDC));
735                         using (XmlWriter w = writer) {
736                                 ser.WriteObject (w, new ColorsEnumMemberNoDC ());
737                         }
738                 }
739
740                 [Test]
741                 public void SerializeEnumWithDC2Xml ()
742                 {
743                         StringWriter sw = new StringWriter ();
744                         SerializeEnumWithDC2 (XmlWriter.Create (sw, settings));
745                         Assert.AreEqual (
746                                 @"<root type=""number"">3</root>",
747                                 sw.ToString ());
748                 }
749
750                 [Test]
751                 public void SerializeEnumWithDC2Json ()
752                 {
753                         MemoryStream ms = new MemoryStream ();
754                         SerializeEnumWithDC2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
755                         Assert.AreEqual (
756                                 "3",
757                                 Encoding.UTF8.GetString (ms.ToArray ()));
758                 }
759
760                 void SerializeEnumWithDC2 (XmlWriter writer)
761                 {
762                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
763                         using (XmlWriter w = writer) {
764                                 ser.WriteObject (w, 3);
765                         }
766                 }
767
768 /*
769                 [Test]
770                 [ExpectedException (typeof (SerializationException))]
771                 public void SerializeEnumWithDCInvalid ()
772                 {
773                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (ColorsWithDC));
774                         StringWriter sw = new StringWriter ();
775                         ColorsWithDC cdc = ColorsWithDC.Blue;
776                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
777                                 ser.WriteObject (w, cdc);
778                         }
779                 }
780 */
781
782                 [Test]
783                 public void SerializeDCWithEnumXml ()
784                 {
785                         StringWriter sw = new StringWriter ();
786                         SerializeDCWithEnum (XmlWriter.Create (sw, settings));
787                         Assert.AreEqual (
788                                 @"<root type=""object""><_colors type=""number"">0</_colors></root>",
789                                 sw.ToString ());
790                 }
791
792                 [Test]
793                 public void SerializeDCWithEnumJson ()
794                 {
795                         MemoryStream ms = new MemoryStream ();
796                         SerializeDCWithEnum (JsonReaderWriterFactory.CreateJsonWriter (ms));
797                         Assert.AreEqual (
798                                 @"{""_colors"":0}",
799                                 Encoding.UTF8.GetString (ms.ToArray ()));
800                 }
801
802                 void SerializeDCWithEnum (XmlWriter writer)
803                 {
804                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum));
805                         using (XmlWriter w = writer) {
806                                 ser.WriteObject (w, new DCWithEnum ());
807                         }
808                 }
809
810                 [Test]
811                 public void SerializerDCArrayXml ()
812                 {
813                         StringWriter sw = new StringWriter ();
814                         SerializerDCArray (XmlWriter.Create (sw, settings));
815                         Assert.AreEqual (
816                                 @"<root type=""array""><item type=""object""><_colors type=""number"">0</_colors></item><item type=""object""><_colors type=""number"">1</_colors></item></root>",
817                                 sw.ToString ());
818                 }
819
820                 [Test]
821                 public void SerializerDCArrayJson ()
822                 {
823                         MemoryStream ms = new MemoryStream ();
824                         SerializerDCArray (JsonReaderWriterFactory.CreateJsonWriter (ms));
825                         Assert.AreEqual (
826                                 @"[{""_colors"":0},{""_colors"":1}]",
827                                 Encoding.UTF8.GetString (ms.ToArray ()));
828                 }
829
830                 void SerializerDCArray (XmlWriter writer)
831                 {
832                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (DCWithEnum []));
833                         DCWithEnum [] arr = new DCWithEnum [2];
834                         arr [0] = new DCWithEnum (); arr [0].colors = Colors.Red;
835                         arr [1] = new DCWithEnum (); arr [1].colors = Colors.Green;
836                         using (XmlWriter w = writer) {
837                                 ser.WriteObject (w, arr);
838                         }
839                 }
840
841                 [Test]
842                 public void SerializerDCArray2Xml ()
843                 {
844                         StringWriter sw = new StringWriter ();
845                         SerializerDCArray2 (XmlWriter.Create (sw, settings));
846                         Assert.AreEqual (
847                                 @"<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>",
848                                 sw.ToString ());
849                 }
850
851                 [Test]
852                 public void SerializerDCArray2Json ()
853                 {
854                         MemoryStream ms = new MemoryStream ();
855                         SerializerDCArray2 (JsonReaderWriterFactory.CreateJsonWriter (ms));
856                         Assert.AreEqual (
857                                 @"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
858                                 Encoding.UTF8.GetString (ms.ToArray ()));
859                 }
860
861                 void SerializerDCArray2 (XmlWriter writer)
862                 {
863                         List<Type> known = new List<Type> ();
864                         known.Add (typeof (DCWithEnum));
865                         known.Add (typeof (DCSimple1));
866                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (object []), known);
867                         object [] arr = new object [2];
868                         arr [0] = new DCWithEnum (); ((DCWithEnum)arr [0]).colors = Colors.Red;
869                         arr [1] = new DCSimple1 (); ((DCSimple1) arr [1]).Foo = "hello";
870
871                         using (XmlWriter w = writer) {
872                                 ser.WriteObject (w, arr);
873                         }
874                 }
875
876                 [Test]
877                 public void SerializerDCArray3Xml ()
878                 {
879                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
880                         StringWriter sw = new StringWriter ();
881                         int [] arr = new int [2];
882                         arr [0] = 1; arr [1] = 2;
883
884                         using (XmlWriter w = XmlWriter.Create (sw, settings)) {
885                                 ser.WriteObject (w, arr);
886                         }
887
888                         Assert.AreEqual (
889                                 @"<root type=""array""><item type=""number"">1</item><item type=""number"">2</item></root>",
890                                 sw.ToString ());
891                 }
892
893                 [Test]
894                 public void SerializerDCArray3Json ()
895                 {
896                         MemoryStream ms = new MemoryStream ();
897                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (int []));
898                         int [] arr = new int [2];
899                         arr [0] = 1; arr [1] = 2;
900
901                         using (XmlWriter w = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
902                                 ser.WriteObject (w, arr);
903                         }
904
905                         Assert.AreEqual (
906                                 @"[1,2]",
907                                 Encoding.UTF8.GetString (ms.ToArray ()));
908                 }
909
910                 [Test]
911                 // ... so, non-JSON XmlWriter is still accepted.
912                 public void SerializeNonDCArrayXml ()
913                 {
914                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
915                         StringWriter sw = new StringWriter ();
916                         using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
917                                 ser.WriteObject (xw, new SerializeNonDCArrayType ());
918                         }
919                         Assert.AreEqual (@"<root type=""object""><IPAddresses type=""array"" /></root>",
920                                 sw.ToString ());
921                 }
922
923                 [Test]
924                 public void SerializeNonDCArrayJson ()
925                 {
926                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
927                         MemoryStream ms = new MemoryStream ();
928                         using (XmlWriter xw = JsonReaderWriterFactory.CreateJsonWriter (ms)) {
929                                 ser.WriteObject (xw, new SerializeNonDCArrayType ());
930                         }
931                         Assert.AreEqual (@"{""IPAddresses"":[]}",
932                                 Encoding.UTF8.GetString (ms.ToArray ()));
933                 }
934
935                 [Test]
936                 public void SerializeNonDCArrayItems ()
937                 {
938                         DataContractJsonSerializer ser = new DataContractJsonSerializer (typeof (SerializeNonDCArrayType));
939                         StringWriter sw = new StringWriter ();
940                         using (XmlWriter xw = XmlWriter.Create (sw, settings)) {
941                                 SerializeNonDCArrayType obj = new SerializeNonDCArrayType ();
942                                 obj.IPAddresses = new NonDCItem [] {new NonDCItem () { Data = new byte [] {1, 2, 3, 4} } };
943                                 ser.WriteObject (xw, obj);
944                         }
945
946                         XmlDocument doc = new XmlDocument ();
947                         doc.LoadXml (sw.ToString ());
948                         XmlNamespaceManager nsmgr = new XmlNamespaceManager (doc.NameTable);
949                         nsmgr.AddNamespace ("s", "http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization");
950                         nsmgr.AddNamespace ("n", "http://schemas.datacontract.org/2004/07/System.Net");
951                         nsmgr.AddNamespace ("a", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");
952
953                         Assert.AreEqual (1, doc.SelectNodes ("/root/IPAddresses/item", nsmgr).Count, "#1");
954                         XmlElement el = doc.SelectSingleNode ("/root/IPAddresses/item/Data", nsmgr) as XmlElement;
955                         Assert.IsNotNull (el, "#3");
956                         Assert.AreEqual (4, el.SelectNodes ("item", nsmgr).Count, "#4");
957                 }
958
959                 [Test]
960                 public void MaxItemsInObjectGraph1 ()
961                 {
962                         // object count == maximum
963                         DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCEmpty), null, 1, false, null, false);
964                         s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCEmpty ());
965                 }
966
967                 [Test]
968                 [ExpectedException (typeof (SerializationException))]
969                 public void MaxItemsInObjectGraph2 ()
970                 {
971                         // object count > maximum
972                         DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1), null, 1, false, null, false);
973                         s.WriteObject (XmlWriter.Create (TextWriter.Null), new DCSimple1 ());
974                 }
975
976                 [Test]
977                 public void DeserializeString ()
978                 {
979                         Assert.AreEqual ("ABC", Deserialize ("\"ABC\"", typeof (string)));
980                 }
981
982                 [Test]
983                 public void DeserializeInt ()
984                 {
985                         Assert.AreEqual (5, Deserialize ("5", typeof (int)));
986                 }
987
988                 [Test]
989                 public void DeserializeArray ()
990                 {
991                         int [] ret = (int []) Deserialize ("[5,6,7]", typeof (int []));
992                         Assert.AreEqual (5, ret [0], "#1");
993                         Assert.AreEqual (6, ret [1], "#2");
994                         Assert.AreEqual (7, ret [2], "#3");
995                 }
996
997                 [Test]
998                 public void DeserializeArrayUntyped ()
999                 {
1000                         object [] ret = (object []) Deserialize ("[5,6,7]", typeof (object []));
1001                         Assert.AreEqual (5, ret [0], "#1");
1002                         Assert.AreEqual (6, ret [1], "#2");
1003                         Assert.AreEqual (7, ret [2], "#3");
1004                 }
1005
1006                 [Test]
1007                 public void DeserializeMixedArray ()
1008                 {
1009                         object [] ret = (object []) Deserialize ("[5,\"6\",false]", typeof (object []));
1010                         Assert.AreEqual (5, ret [0], "#1");
1011                         Assert.AreEqual ("6", ret [1], "#2");
1012                         Assert.AreEqual (false, ret [2], "#3");
1013                 }
1014
1015                 [Test]
1016                 [ExpectedException (typeof (SerializationException))]
1017                 public void DeserializeEmptyAsString ()
1018                 {
1019                         // it somehow expects "root" which should have been already consumed.
1020                         Deserialize ("", typeof (string));
1021                 }
1022
1023                 [Test]
1024                 [ExpectedException (typeof (SerializationException))]
1025                 public void DeserializeEmptyAsInt ()
1026                 {
1027                         // it somehow expects "root" which should have been already consumed.
1028                         Deserialize ("", typeof (int));
1029                 }
1030
1031                 [Test]
1032                 [ExpectedException (typeof (SerializationException))]
1033                 public void DeserializeEmptyAsDBNull ()
1034                 {
1035                         // it somehow expects "root" which should have been already consumed.
1036                         Deserialize ("", typeof (DBNull));
1037                 }
1038
1039                 [Test]
1040                 public void DeserializeEmptyObjectAsString ()
1041                 {
1042                         // looks like it is converted to ""
1043                         Assert.AreEqual (String.Empty, Deserialize ("{}", typeof (string)));
1044                 }
1045
1046                 [Test]
1047                 [ExpectedException (typeof (SerializationException))]
1048                 public void DeserializeEmptyObjectAsInt ()
1049                 {
1050                         Deserialize ("{}", typeof (int));
1051                 }
1052
1053                 [Test]
1054                 public void DeserializeEmptyObjectAsDBNull ()
1055                 {
1056                         Assert.AreEqual (DBNull.Value, Deserialize ("{}", typeof (DBNull)));
1057                 }
1058
1059                 [Test]
1060                 [ExpectedException (typeof (SerializationException))]
1061                 public void DeserializeEnumByName ()
1062                 {
1063                         // enum is parsed into long
1064                         Deserialize (@"""Red""", typeof (Colors));
1065                 }
1066
1067                 [Test]
1068                 public void DeserializeEnum2 ()
1069                 {
1070                         object o = Deserialize ("0", typeof (Colors));
1071
1072                         Assert.AreEqual (typeof (Colors), o.GetType (), "#de3");
1073                         Colors c = (Colors) o;
1074                         Assert.AreEqual (Colors.Red, c, "#de4");
1075                 }
1076                 
1077                 [Test]
1078                 [ExpectedException (typeof (SerializationException))]
1079                 public void DeserializeEnumInvalid ()
1080                 {
1081                         Deserialize ("", typeof (Colors));
1082                 }
1083
1084                 [Test]
1085                 [ExpectedException (typeof (SerializationException))]
1086                 [Category ("NotDotNet")] // 0.0 is an invalid Colors value.
1087                 public void DeserializeEnumInvalid3 ()
1088                 {
1089                         //"0.0" instead of "0"
1090                         Deserialize (
1091                                 "0.0",
1092                                 typeof (Colors));
1093                 }
1094
1095                 [Test]
1096                 public void DeserializeEnumWithDC ()
1097                 {
1098                         object o = Deserialize ("0", typeof (ColorsWithDC));
1099                         
1100                         Assert.AreEqual (typeof (ColorsWithDC), o.GetType (), "#de5");
1101                         ColorsWithDC cdc = (ColorsWithDC) o;
1102                         Assert.AreEqual (ColorsWithDC.Red, o, "#de6");
1103                 }
1104
1105                 [Test]
1106                 [ExpectedException (typeof (SerializationException))]
1107                 [Category ("NotDotNet")] // 4 is an invalid Colors value.
1108                 [Category ("NotWorking")]
1109                 public void DeserializeEnumWithDCInvalid ()
1110                 {
1111                         Deserialize (
1112                                 "4",
1113                                 typeof (ColorsWithDC));
1114                 }
1115
1116                 [Test]
1117                 public void DeserializeDCWithEnum ()
1118                 {
1119                         object o = Deserialize (
1120                                 "{\"_colors\":0}",
1121                                 typeof (DCWithEnum));
1122
1123                         Assert.AreEqual (typeof (DCWithEnum), o.GetType (), "#de7");
1124                         DCWithEnum dc = (DCWithEnum) o;
1125                         Assert.AreEqual (Colors.Red, dc.colors, "#de8");
1126                 }
1127
1128                 [Test]
1129                 public void ReadObjectVerifyObjectNameFalse ()
1130                 {
1131                         string xml = @"<any><Member1>bar</Member1></any>";
1132                         object o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1133                                 .ReadObject (XmlReader.Create (new StringReader (xml)), false);
1134                         Assert.IsTrue (o is VerifyObjectNameTestData, "#1");
1135
1136                         string xml2 = @"<any><x:Member1 xmlns:x=""http://schemas.datacontract.org/2004/07/MonoTests.System.Runtime.Serialization"">bar</x:Member1></any>";
1137                         o = new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1138                                 .ReadObject (XmlReader.Create (new StringReader (xml2)), false);
1139                         Assert.IsTrue (o is VerifyObjectNameTestData, "#2");
1140                 }
1141
1142                 [Test]
1143                 [ExpectedException (typeof (SerializationException))]
1144                 public void ReadObjectVerifyObjectNameTrue ()
1145                 {
1146                         string xml = @"<any><Member1>bar</Member1></any>";
1147                         new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1148                                 .ReadObject (XmlReader.Create (new StringReader (xml)), true);
1149                 }
1150
1151                 [Test] // member name is out of scope
1152                 public void ReadObjectVerifyObjectNameTrue2 ()
1153                 {
1154                         string xml = @"<root><Member2>bar</Member2></root>";
1155                         new DataContractJsonSerializer (typeof (VerifyObjectNameTestData))
1156                                 .ReadObject (XmlReader.Create (new StringReader (xml)), true);
1157                 }
1158
1159                 [Test]
1160                 public void ReadTypedObjectJson ()
1161                 {
1162                         object o = Deserialize (@"{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}", typeof (DCWithEnum));
1163                         Assert.AreEqual (typeof (DCWithEnum), o.GetType ());
1164                 }
1165
1166                 [Test]
1167                 public void ReadObjectDCArrayJson ()
1168                 {
1169                         object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0}]",
1170                                 typeof (object []), typeof (DCWithEnum));
1171                         Assert.AreEqual (typeof (object []), o.GetType (), "#1");
1172                         object [] arr = (object []) o;
1173                         Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
1174                 }
1175
1176                 [Test]
1177                 public void ReadObjectDCArray2Json ()
1178                 {
1179                         object o = Deserialize (@"[{""__type"":""DCWithEnum:#MonoTests.System.Runtime.Serialization.Json"",""_colors"":0},{""__type"":""DCSimple1:#MonoTests.System.Runtime.Serialization.Json"",""Foo"":""hello""}]",
1180                                 typeof (object []), typeof (DCWithEnum), typeof (DCSimple1));
1181                         Assert.AreEqual (typeof (object []), o.GetType (), "#1");
1182                         object [] arr = (object []) o;
1183                         Assert.AreEqual (typeof (DCWithEnum), arr [0].GetType (), "#2");
1184                         Assert.AreEqual (typeof (DCSimple1), arr [1].GetType (), "#3");
1185                 }
1186
1187                 private object Deserialize (string xml, Type type, params Type [] knownTypes)
1188                 {
1189                         DataContractJsonSerializer ser = new DataContractJsonSerializer (type, knownTypes);
1190                         XmlReader xr = JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (xml), new XmlDictionaryReaderQuotas ());
1191                         return ser.ReadObject (xr);
1192                 }
1193
1194                 [Test]
1195                 public void IsStartObject ()
1196                 {
1197                         DataContractJsonSerializer s = new DataContractJsonSerializer (typeof (DCSimple1));
1198                         Assert.IsTrue (s.IsStartObject (XmlReader.Create (new StringReader ("<root></root>"))), "#1");
1199                         Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<dummy></dummy>"))), "#2");
1200                         Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<Foo></Foo>"))), "#3");
1201                         Assert.IsFalse (s.IsStartObject (XmlReader.Create (new StringReader ("<root xmlns='urn:foo'></root>"))), "#4");
1202                 }
1203
1204                 [Test]
1205                 public void SerializeNonDC2 ()
1206                 {
1207                         var ser = new DataContractJsonSerializer (typeof (TestData));
1208                         StringWriter sw = new StringWriter ();
1209                         var obj = new TestData () { Foo = "foo", Bar = "bar", Baz = "baz" };
1210
1211                         // XML
1212                         using (var xw = XmlWriter.Create (sw))
1213                                 ser.WriteObject (xw, obj);
1214                         var s = sw.ToString ();
1215                         // since the order is not preserved, we compare only contents.
1216                         Assert.IsTrue (s.IndexOf ("<Foo>foo</Foo>") > 0, "#1-1");
1217                         Assert.IsTrue (s.IndexOf ("<Bar>bar</Bar>") > 0, "#1-2");
1218                         Assert.IsFalse (s.IndexOf ("<Baz>baz</Baz>") > 0, "#1-3");
1219
1220                         // JSON
1221                         MemoryStream ms = new MemoryStream ();
1222                         using (var xw = JsonReaderWriterFactory.CreateJsonWriter (ms))
1223                                 ser.WriteObject (ms, obj);
1224                         s = new StreamReader (new MemoryStream (ms.ToArray ())).ReadToEnd ().Replace ('"', '/');
1225                         // since the order is not preserved, we compare only contents.
1226                         Assert.IsTrue (s.IndexOf ("/Foo/:/foo/") > 0, "#2-1");
1227                         Assert.IsTrue (s.IndexOf ("/Bar/:/bar/") > 0, "#2-2");
1228                         Assert.IsFalse (s.IndexOf ("/Baz/:/baz/") > 0, "#2-3");
1229                 }
1230
1231                 [Test]
1232                 public void AlwaysEmitTypeInformation ()
1233                 {
1234                         var ms = new MemoryStream ();
1235                         var ds = new DataContractJsonSerializer (typeof (string), "root", null, 10, false, null, true);
1236                         ds.WriteObject (ms, "foobar");
1237                         var s = Encoding.UTF8.GetString (ms.ToArray ());
1238                         Assert.AreEqual ("\"foobar\"", s, "#1");
1239                 }
1240
1241                 [Test]
1242                 public void AlwaysEmitTypeInformation2 ()
1243                 {
1244                         var ms = new MemoryStream ();
1245                         var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, true);
1246                         ds.WriteObject (ms, new TestData () { Foo = "foo"});
1247                         var s = Encoding.UTF8.GetString (ms.ToArray ());
1248                         Assert.AreEqual (@"{""__type"":""TestData:#MonoTests.System.Runtime.Serialization.Json"",""Bar"":null,""Foo"":""foo""}", s, "#1");
1249                 }
1250
1251                 [Test]
1252                 public void AlwaysEmitTypeInformation3 ()
1253                 {
1254                         var ms = new MemoryStream ();
1255                         var ds = new DataContractJsonSerializer (typeof (TestData), "root", null, 10, false, null, false);
1256                         ds.WriteObject (ms, new TestData () { Foo = "foo"});
1257                         var s = Encoding.UTF8.GetString (ms.ToArray ());
1258                         Assert.AreEqual (@"{""Bar"":null,""Foo"":""foo""}", s, "#1");
1259                 }
1260
1261                 [Test]
1262                 public void TestNonpublicDeserialization ()
1263                 {
1264                         string s1= @"{""Bar"":""bar"", ""Foo"":""foo"", ""Baz"":""baz""}";
1265                         TestData o1 = ((TestData)(new DataContractJsonSerializer (typeof (TestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s1), new XmlDictionaryReaderQuotas ()))));
1266
1267                         Assert.AreEqual (null, o1.Baz, "#1");
1268
1269                         string s2 = @"{""TestData"":[{""key"":""key1"",""value"":""value1""}]}";
1270                         KeyValueTestData o2 = ((KeyValueTestData)(new DataContractJsonSerializer (typeof (KeyValueTestData)).ReadObject (JsonReaderWriterFactory.CreateJsonReader (Encoding.UTF8.GetBytes (s2), new XmlDictionaryReaderQuotas ()))));
1271
1272                         Assert.AreEqual (1, o2.TestData.Count, "#2");
1273                         Assert.AreEqual ("key1", o2.TestData[0].Key, "#3");
1274                         Assert.AreEqual ("value1", o2.TestData[0].Value, "#4");
1275                 }
1276
1277                 // [Test] use this case if you want to check lame silverlight parser behavior. Seealso #549756
1278                 public void QuotelessDeserialization ()
1279                 {
1280                         string s1 = @"{FooMember:""value""}";
1281                         var ds = new DataContractJsonSerializer (typeof (DCWithName));
1282                         ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s1)));
1283
1284                         string s2 = @"{FooMember:"" \""{dummy:string}\""""}";
1285                         ds.ReadObject (new MemoryStream (Encoding.UTF8.GetBytes (s2)));
1286                 }
1287
1288                 [Test]
1289                 [Category ("NotWorking")]
1290                 public void TypeIsNotPartsOfKnownTypes ()
1291                 {
1292                         var dcs = new DataContractSerializer (typeof (string));
1293                         Assert.AreEqual (0, dcs.KnownTypes.Count, "KnownTypes #1");
1294                         var dcjs = new DataContractJsonSerializer (typeof (string));
1295                         Assert.AreEqual (0, dcjs.KnownTypes.Count, "KnownTypes #2");
1296                 }
1297
1298                 [Test]
1299                 public void ReadWriteNullObject ()
1300                 {
1301                         DataContractJsonSerializer dcjs = new DataContractJsonSerializer (typeof (string));
1302                         using (MemoryStream ms = new MemoryStream ()) {
1303                                 dcjs.WriteObject (ms, null);
1304                                 ms.Position = 0;
1305                                 using (StreamReader sr = new StreamReader (ms)) {
1306                                         string data = sr.ReadToEnd ();
1307                                         Assert.AreEqual ("null", data, "WriteObject(stream,null)");
1308
1309                                         ms.Position = 0;
1310                                         Assert.IsNull (dcjs.ReadObject (ms), "ReadObject(stream)");
1311                                 }
1312                         };
1313                 }
1314
1315                 object ReadWriteObject (Type type, object obj, string expected)
1316                 {
1317                         using (MemoryStream ms = new MemoryStream ()) {
1318                                 DataContractJsonSerializer dcjs = new DataContractJsonSerializer (type);
1319                                 dcjs.WriteObject (ms, obj);
1320                                 ms.Position = 0;
1321                                 using (StreamReader sr = new StreamReader (ms)) {
1322                                         Assert.AreEqual (expected, sr.ReadToEnd (), "WriteObject");
1323
1324                                         ms.Position = 0;
1325                                         return dcjs.ReadObject (ms);
1326                                 }
1327                         }
1328                 }
1329
1330                 [Test]
1331                 [Ignore ("Wrong test case. See bug #573691")]
1332                 public void ReadWriteObject_Single_SpecialCases ()
1333                 {
1334                         Assert.IsTrue (Single.IsNaN ((float) ReadWriteObject (typeof (float), Single.NaN, "NaN")));
1335                         Assert.IsTrue (Single.IsNegativeInfinity ((float) ReadWriteObject (typeof (float), Single.NegativeInfinity, "-INF")));
1336                         Assert.IsTrue (Single.IsPositiveInfinity ((float) ReadWriteObject (typeof (float), Single.PositiveInfinity, "INF")));
1337                 }
1338
1339                 [Test]
1340                 [Ignore ("Wrong test case. See bug #573691")]
1341                 public void ReadWriteObject_Double_SpecialCases ()
1342                 {
1343                         Assert.IsTrue (Double.IsNaN ((double) ReadWriteObject (typeof (double), Double.NaN, "NaN")));
1344                         Assert.IsTrue (Double.IsNegativeInfinity ((double) ReadWriteObject (typeof (double), Double.NegativeInfinity, "-INF")));
1345                         Assert.IsTrue (Double.IsPositiveInfinity ((double) ReadWriteObject (typeof (double), Double.PositiveInfinity, "INF")));
1346                 }
1347
1348                 [Test]
1349                 public void ReadWriteDateTime ()
1350                 {
1351                         var ms = new MemoryStream ();
1352                         DataContractJsonSerializer serializer = new DataContractJsonSerializer (typeof (Query));
1353                         Query query = new Query () {
1354                                 StartDate = new DateTime (2010, 3, 4, 5, 6, 7),
1355                                 EndDate = new DateTime (2010, 4, 5, 6, 7, 8)
1356                                 };
1357                         serializer.WriteObject (ms, query);
1358                         Assert.AreEqual ("{\"StartDate\":\"\\/Date(1267679167000)\\/\",\"EndDate\":\"\\/Date(1270447628000)\\/\"}", Encoding.UTF8.GetString (ms.ToArray ()), "#1");
1359                         ms.Position = 0;
1360                         Console.WriteLine (new StreamReader (ms).ReadToEnd ());
1361                         ms.Position = 0;
1362                         var q = (Query) serializer.ReadObject(ms);
1363                         Assert.AreEqual (query.StartDate, q.StartDate, "#2");
1364                         Assert.AreEqual (query.EndDate, q.EndDate, "#3");
1365                 }
1366
1367                 [DataContract(Name = "DateTest")]
1368                 public class DateTest
1369                 {
1370                         [DataMember(Name = "should_have_value")]
1371                         public DateTime? ShouldHaveValue { get; set; }
1372                 }
1373
1374                 //
1375                 // This tests both the extended format "number-0500" as well
1376                 // as the nullable field in the structure
1377                 [Test]
1378                 public void BugXamarin163 ()
1379                 {
1380                         string json = @"{""should_have_value"":""\/Date(1277355600000-0500)\/""}";
1381
1382                         byte[] bytes = global::System.Text.Encoding.UTF8.GetBytes(json);
1383                         Stream inputStream = new MemoryStream(bytes);
1384                         
1385                         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DateTest));
1386                         DateTest t = serializer.ReadObject(inputStream) as DateTest;
1387                         Assert.AreEqual (634129344000000000, t.ShouldHaveValue.Value.Ticks, "#1");
1388                 }
1389
1390                 [Test]
1391                 public void NullableFieldsShouldSupportNullValue ()
1392                 {
1393                         string json = @"{""should_have_value"":null}";
1394                         var inputStream = new MemoryStream (Encoding.UTF8.GetBytes (json));
1395                         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(DateTest));
1396                         Console.WriteLine ("# serializer assembly: {0}", serializer.GetType ().Assembly.Location);
1397                         DateTest t = serializer.ReadObject (inputStream) as DateTest;
1398                         Assert.AreEqual (false, t.ShouldHaveValue.HasValue, "#2");
1399                 }
1400                 
1401                 [Test]
1402                 public void DeserializeNullMember ()
1403                 {
1404                         var ds = new DataContractJsonSerializer (typeof (ClassA));
1405                         var stream = new MemoryStream ();
1406                         var a = new ClassA ();
1407                         ds.WriteObject (stream, a);
1408                         stream.Position = 0;
1409                         a = (ClassA) ds.ReadObject (stream);
1410                         Assert.IsNull (a.B, "#1");
1411                 }
1412
1413                 [Test]
1414                 public void OnDeserializationMethods ()
1415                 {
1416                         var ds = new DataContractJsonSerializer (typeof (GSPlayerListErg));
1417                         var obj = new GSPlayerListErg ();
1418                         var ms = new MemoryStream ();
1419                         ds.WriteObject (ms, obj);
1420                         ms.Position = 0;
1421                         ds.ReadObject (ms);
1422                         Assert.IsTrue (GSPlayerListErg.A, "A");
1423                         Assert.IsTrue (GSPlayerListErg.B, "B");
1424                         Assert.IsTrue (GSPlayerListErg.C, "C");
1425                 }
1426                 
1427                 [Test]
1428                 public void WriteChar ()
1429                 {
1430                         DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof (CharTest));
1431                         using (MemoryStream ms = new MemoryStream()) {
1432                                 serializer.WriteObject(ms, new CharTest ());
1433                                 ms.Position = 0L;
1434                                 using (StreamReader reader = new StreamReader(ms)) {
1435                                         reader.ReadToEnd();
1436                                 }
1437                         }
1438                 }
1439
1440                 [Test]
1441                 public void DictionarySerialization ()
1442                 {
1443                         var dict = new MyDictionary<string,string> ();
1444                         dict.Add ("key", "value");
1445                         var serializer = new DataContractJsonSerializer (dict.GetType ());
1446                         var stream = new MemoryStream ();
1447                         serializer.WriteObject (stream, dict);
1448                         stream.Position = 0;
1449
1450                         Assert.AreEqual ("[{\"Key\":\"key\",\"Value\":\"value\"}]", new StreamReader (stream).ReadToEnd (), "#1");
1451                         stream.Position = 0;
1452                         dict = (MyDictionary<string,string>) serializer.ReadObject (stream);
1453                         Assert.AreEqual (1, dict.Count, "#2");
1454                         Assert.AreEqual ("value", dict ["key"], "#3");
1455                 }
1456                 
1457                 [Test]
1458                 public void Bug13485 ()
1459                 {
1460                         const string json = "{ \"Name\" : \"Test\", \"Value\" : \"ValueA\" }";
1461
1462                         string result = string.Empty;
1463                         var serializer = new DataContractJsonSerializer (typeof (Bug13485Type));
1464                         Bug13485Type entity;
1465                         using (var stream = new MemoryStream (Encoding.UTF8.GetBytes (json)))
1466                                 entity = (Bug13485Type) serializer.ReadObject (stream);
1467
1468                         result = entity.GetValue;
1469                         Assert.AreEqual ("ValueA", result, "#1");
1470                 }
1471
1472                 [DataContract(Name = "UriTest")]
1473                 public class UriTest
1474                 {
1475                         [DataMember(Name = "members")]
1476                         public Uri MembersRelativeLink { get; set; }
1477                 }
1478
1479                 [Test]
1480                 public void Bug15169 ()
1481                 {
1482                         const string json = "{\"members\":\"foo/bar/members\"}";
1483                         var serializer = new DataContractJsonSerializer (typeof (UriTest));
1484                         UriTest entity;
1485                         using (var stream = new MemoryStream (Encoding.UTF8.GetBytes (json)))
1486                                 entity = (UriTest) serializer.ReadObject (stream);
1487
1488                         Assert.AreEqual ("foo/bar/members", entity.MembersRelativeLink.ToString ());
1489                 }
1490                 
1491                 #region Test methods for collection serialization
1492                 
1493                 [Test]
1494                 public void TestArrayListSerialization ()
1495                 {
1496                         var collection = new ArrayListContainer ();
1497                         var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1498                         var expectedItemsCount = 4;
1499                         
1500                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1501                         var stream = new MemoryStream ();
1502                         serializer.WriteObject (stream, collection);
1503
1504                         stream.Position = 0;
1505                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1506
1507                         stream.Position = 0;
1508                         collection = (ArrayListContainer) serializer.ReadObject (stream);
1509                         
1510                         Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1511                 }
1512                 
1513                 [Test]
1514                 [ExpectedException (typeof (InvalidDataContractException))]
1515                 public void TestBitArraySerialization ()
1516                 {
1517                         var collection = new BitArrayContainer ();
1518                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1519                         var stream = new MemoryStream ();
1520                         serializer.WriteObject (stream, collection);
1521                 }
1522                 
1523                 [Test]
1524                 public void TestHashtableSerialization ()
1525                 {
1526                         var collection = new HashtableContainer ();
1527                         var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1528                         
1529                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1530                         var stream = new MemoryStream ();
1531                         serializer.WriteObject (stream, collection);
1532
1533                         stream.Position = 0;
1534                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1535                 }
1536                 
1537                 [Test]
1538                 [ExpectedException (typeof (ArgumentException))]
1539                 public void TestHashtableDeserialization ()
1540                 {
1541                         var collection = new HashtableContainer ();
1542                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1543                         var stream = new MemoryStream ();
1544                         serializer.WriteObject (stream, collection);
1545                         
1546                         stream.Position = 0;
1547                         serializer.ReadObject (stream);
1548                 }
1549                 
1550                 [Test]
1551                 [ExpectedException (typeof (InvalidDataContractException))]
1552                 public void TestQueueSerialization ()
1553                 {
1554                         var collection = new QueueContainer ();
1555                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1556                         var stream = new MemoryStream ();
1557                         serializer.WriteObject (stream, collection);
1558                 }
1559                 
1560                 [Test]
1561                 public void TestSortedListSerialization ()
1562                 {
1563                         var collection = new SortedListContainer ();
1564                         var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1565                         
1566                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1567                         var stream = new MemoryStream ();
1568                         serializer.WriteObject (stream, collection);
1569
1570                         stream.Position = 0;
1571                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1572                 }
1573                 
1574                 [Test]
1575                 [ExpectedException (typeof (ArgumentException))]
1576                 public void TestSortedListDeserialization ()
1577                 {
1578                         var collection = new SortedListContainer ();
1579                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1580                         var stream = new MemoryStream ();
1581                         serializer.WriteObject (stream, collection);
1582                         
1583                         stream.Position = 0;
1584                         serializer.ReadObject (stream);
1585                 }
1586                 
1587                 [Test]
1588                 [ExpectedException (typeof (InvalidDataContractException))]
1589                 public void TestStackSerialization ()
1590                 {
1591                         var collection = new StackContainer ();
1592                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1593                         var stream = new MemoryStream ();
1594                         serializer.WriteObject (stream, collection);
1595                 }
1596                 
1597                 [Test]
1598                 public void TestEnumerableWithAddSerialization ()
1599                 {
1600                         var collection = new EnumerableWithAddContainer ();
1601                         var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1602                         var expectedItemsCount = 4;
1603                         
1604                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1605                         var stream = new MemoryStream ();
1606                         serializer.WriteObject (stream, collection);
1607
1608                         stream.Position = 0;
1609                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1610
1611                         stream.Position = 0;
1612                         collection = (EnumerableWithAddContainer) serializer.ReadObject (stream);
1613                         
1614                         Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1615                 }
1616                 
1617                 [Test]
1618                 [ExpectedException (typeof (InvalidDataContractException))]
1619                 public void TestEnumerableWithSpecialAddSerialization ()
1620                 {
1621                         var collection = new EnumerableWithSpecialAddContainer ();                      
1622                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1623                         var stream = new MemoryStream ();
1624                         serializer.WriteObject (stream, collection);
1625                 }
1626         
1627                 [Test]
1628                 public void TestHashSetSerialization ()
1629                 {
1630                         var collection = new GenericHashSetContainer ();
1631                         var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1632                         var expectedItemsCount = 2;
1633                         
1634                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1635                         var stream = new MemoryStream ();
1636                         serializer.WriteObject (stream, collection);
1637
1638                         stream.Position = 0;
1639                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1640
1641                         stream.Position = 0;
1642                         collection = (GenericHashSetContainer) serializer.ReadObject (stream);
1643                         
1644                         Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1645                 }
1646                 
1647                 [Test]
1648                 public void TestLinkedListSerialization ()
1649                 {
1650                         var collection = new GenericLinkedListContainer ();
1651                         var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1652                         var expectedItemsCount = 4;
1653                         
1654                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1655                         var stream = new MemoryStream ();
1656                         serializer.WriteObject (stream, collection);
1657
1658                         stream.Position = 0;
1659                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1660
1661                         stream.Position = 0;
1662                         collection = (GenericLinkedListContainer) serializer.ReadObject (stream);
1663                         
1664                         Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1665                 }
1666                 
1667                 [Test]
1668                 [ExpectedException (typeof (InvalidDataContractException))]
1669                 public void TestGenericQueueSerialization ()
1670                 {
1671                         var collection = new GenericQueueContainer ();                  
1672                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1673                         var stream = new MemoryStream ();
1674                         serializer.WriteObject (stream, collection);
1675                 }
1676                 
1677                 [Test]
1678                 [ExpectedException (typeof (InvalidDataContractException))]
1679                 public void TestGenericStackSerialization ()
1680                 {
1681                         var collection = new GenericStackContainer ();                  
1682                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1683                         var stream = new MemoryStream ();
1684                         serializer.WriteObject (stream, collection);
1685                 }
1686                 
1687                 [Test]
1688                 public void TestGenericDictionarySerialization ()
1689                 {
1690                         var collection = new GenericDictionaryContainer ();                     
1691                         var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1692                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1693                         var stream = new MemoryStream ();
1694                         serializer.WriteObject (stream, collection);
1695                         
1696                         stream.Position = 0;
1697                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1698                 }
1699                 
1700                 [Test]
1701                 [ExpectedException (typeof (ArgumentException))]
1702                 public void TestGenericDictionaryDeserialization ()
1703                 {
1704                         var collection = new GenericDictionaryContainer ();                     
1705                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1706                         var stream = new MemoryStream ();
1707                         serializer.WriteObject (stream, collection);
1708                         
1709                         stream.Position = 0;
1710                         serializer.ReadObject (stream);
1711                 }
1712                 
1713                 [Test]
1714                 public void TestGenericSortedListSerialization ()
1715                 {
1716                         var collection = new GenericSortedListContainer ();                     
1717                         var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1718                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1719                         var stream = new MemoryStream ();
1720                         serializer.WriteObject (stream, collection);
1721                         
1722                         stream.Position = 0;
1723                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1724                 }
1725                 
1726                 [Test]
1727                 [ExpectedException (typeof (ArgumentException))]
1728                 public void TestGenericSortedListDeserialization ()
1729                 {
1730                         var collection = new GenericSortedListContainer ();                     
1731                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1732                         var stream = new MemoryStream ();
1733                         serializer.WriteObject (stream, collection);
1734                         
1735                         stream.Position = 0;
1736                         serializer.ReadObject (stream);
1737                 }
1738                 
1739                 [Test]
1740                 public void TestGenericSortedDictionarySerialization ()
1741                 {
1742                         var collection = new GenericSortedDictionaryContainer ();                       
1743                         var expectedOutput = "{\"Items\":[{\"Key\":\"key1\",\"Value\":\"banana\"},{\"Key\":\"key2\",\"Value\":\"apple\"}]}";
1744                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1745                         var stream = new MemoryStream ();
1746                         serializer.WriteObject (stream, collection);
1747                         
1748                         stream.Position = 0;
1749                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1750                 }
1751                 
1752                 [Test]
1753                 [ExpectedException (typeof (ArgumentException))]
1754                 public void TestGenericSortedDictionaryDeserialization ()
1755                 {
1756                         var collection = new GenericSortedDictionaryContainer ();                       
1757                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1758                         var stream = new MemoryStream ();
1759                         serializer.WriteObject (stream, collection);
1760                         
1761                         stream.Position = 0;
1762                         serializer.ReadObject (stream);
1763                 }
1764                 
1765                 [Test]
1766                 public void TestGenericEnumerableWithAddSerialization ()
1767                 {
1768                         var collection = new GenericEnumerableWithAddContainer ();
1769                         var expectedOutput = "{\"Items\":[\"banana\",\"apple\"]}";
1770                         var expectedItemsCount = 4;
1771                         
1772                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1773                         var stream = new MemoryStream ();
1774                         serializer.WriteObject (stream, collection);
1775
1776                         stream.Position = 0;
1777                         Assert.AreEqual (expectedOutput, new StreamReader (stream).ReadToEnd (), "#1");
1778
1779                         stream.Position = 0;
1780                         collection = (GenericEnumerableWithAddContainer) serializer.ReadObject (stream);
1781                         
1782                         Assert.AreEqual (expectedItemsCount, collection.Items.Count, "#2");
1783                 }
1784                 
1785                 [Test]
1786                 [ExpectedException (typeof (InvalidDataContractException))]
1787                 public void TestGenericEnumerableWithSpecialAddSerialization ()
1788                 {
1789                         var collection = new GenericEnumerableWithSpecialAddContainer ();                       
1790                         var serializer = new DataContractJsonSerializer (collection.GetType ());
1791                         var stream = new MemoryStream ();
1792                         serializer.WriteObject (stream, collection);
1793                 }
1794                 
1795                 [Test]
1796                 [ExpectedException (typeof (InvalidDataContractException))]
1797                 public void TestNonCollectionGetOnlyProperty ()
1798                 {
1799                         var o = new NonCollectionGetOnlyContainer ();                   
1800                         var serializer = new DataContractJsonSerializer (o.GetType ());
1801                         var stream = new MemoryStream ();
1802                         serializer.WriteObject (stream, o);
1803                 }
1804                 
1805                 #endregion
1806         }
1807         
1808         public class CharTest
1809         {
1810                 public char Foo;
1811         }
1812
1813         public class TestData
1814         {
1815                 public string Foo { get; set; }
1816                 public string Bar { get; set; }
1817                 internal string Baz { get; set; }
1818         }
1819
1820         public enum Colors {
1821                 Red, Green, Blue
1822         }
1823
1824         [DataContract (Name = "_ColorsWithDC")]
1825         public enum ColorsWithDC {
1826
1827                 [EnumMember (Value = "_Red")]
1828                 Red, 
1829                 [EnumMember]
1830                 Green, 
1831                 Blue
1832         }
1833
1834
1835         public enum ColorsEnumMemberNoDC {
1836                 [EnumMember (Value = "_Red")]
1837                 Red, 
1838                 [EnumMember]
1839                 Green, 
1840                 Blue
1841         }
1842
1843         [DataContract]
1844         public class DCWithEnum {
1845                 [DataMember (Name = "_colors")]
1846                 public Colors colors;
1847         }
1848
1849         [DataContract]
1850         public class DCEmpty
1851         {
1852                 // serializer doesn't touch it.
1853                 public string Foo = "TEST";
1854         }
1855
1856         [DataContract]
1857         public class DCSimple1
1858         {
1859                 [DataMember]
1860                 public string Foo = "TEST";
1861         }
1862
1863         [DataContract]
1864         public class DCHasNonDC
1865         {
1866                 [DataMember]
1867                 public NonDC Hoge= new NonDC ();
1868         }
1869
1870         public class NonDC
1871         {
1872                 public string Whee = "whee!";
1873         }
1874
1875         [DataContract]
1876         public class DCHasSerializable
1877         {
1878                 [DataMember]
1879                 public SimpleSer1 Ser = new SimpleSer1 ();
1880         }
1881
1882         [DataContract (Name = "Foo")]
1883         public class DCWithName
1884         {
1885                 [DataMember (Name = "FooMember")]
1886                 public string DMWithName = "value";
1887         }
1888
1889         [DataContract (Name = "")]
1890         public class DCWithEmptyName
1891         {
1892                 [DataMember]
1893                 public string Foo;
1894         }
1895
1896         [DataContract (Name = null)]
1897         public class DCWithNullName
1898         {
1899                 [DataMember]
1900                 public string Foo;
1901         }
1902
1903         [DataContract (Namespace = "")]
1904         public class DCWithEmptyNamespace
1905         {
1906                 [DataMember]
1907                 public string Foo;
1908         }
1909
1910         [Serializable]
1911         public class SimpleSer1
1912         {
1913                 public string Doh = "doh!";
1914         }
1915
1916         public class Wrapper
1917         {
1918                 [DataContract]
1919                 public class DCWrapped
1920                 {
1921                 }
1922         }
1923
1924         [DataContract]
1925         public class CollectionContainer
1926         {
1927                 Collection<string> items = new Collection<string> ();
1928
1929                 [DataMember]
1930                 public Collection<string> Items {
1931                         get { return items; }
1932                 }
1933         }
1934
1935         [CollectionDataContract]
1936         public class DataCollection<T> : Collection<T>
1937         {
1938         }
1939
1940         [DataContract]
1941         public class DataCollectionContainer
1942         {
1943                 DataCollection<string> items = new DataCollection<string> ();
1944
1945                 [DataMember]
1946                 public DataCollection<string> Items {
1947                         get { return items; }
1948                 }
1949         }
1950
1951         [DataContract]
1952         class SerializeNonDCArrayType
1953         {
1954                 [DataMember]
1955                 public NonDCItem [] IPAddresses = new NonDCItem [0];
1956         }
1957
1958         public class NonDCItem
1959         {
1960                 public byte [] Data { get; set; }
1961         }
1962
1963         [DataContract]
1964         public class VerifyObjectNameTestData
1965         {
1966                 [DataMember]
1967                 string Member1 = "foo";
1968         }
1969
1970         [Serializable]
1971         public class KeyValueTestData {
1972                 public List<KeyValuePair<string,string>> TestData = new List<KeyValuePair<string,string>>();
1973         }
1974
1975         [DataContract] // bug #586169
1976         public class Query
1977         {
1978                 [DataMember (Order=1)]
1979                 public DateTime StartDate { get; set; }
1980                 [DataMember (Order=2)]
1981                 public DateTime EndDate { get; set; }
1982         }
1983
1984         public class ClassA {
1985                 public ClassB B { get; set; }
1986         }
1987
1988         public class ClassB
1989         {
1990         }
1991
1992         public class GSPlayerListErg
1993         {
1994                 public GSPlayerListErg ()
1995                 {
1996                         Init ();
1997                 }
1998
1999                 void Init ()
2000                 {
2001                         C = true;
2002                 }
2003
2004                 [OnDeserializing]
2005                 public void OnDeserializing (StreamingContext c)
2006                 {
2007                         A = true;
2008                         Init ();
2009                 }
2010
2011                 [OnDeserialized]
2012                 void OnDeserialized (StreamingContext c)
2013                 {
2014                         B = true;
2015                 }
2016
2017                 public static bool A, B, C;
2018
2019                 [DataMember (Name = "T")]
2020                 public long CodedServerTimeUTC { get; set; }
2021                 public DateTime ServerTimeUTC { get; set; }
2022         }
2023 }
2024
2025 [DataContract]
2026 class GlobalSample1
2027 {
2028 }
2029
2030
2031 public class MyDictionary<K, V> : System.Collections.Generic.IDictionary<K, V>
2032 {
2033         Dictionary<K,V> dic = new Dictionary<K,V> ();
2034
2035         public void Add (K key, V value)
2036         {
2037                 dic.Add (key,  value);
2038         }
2039
2040         public bool ContainsKey (K key)
2041         {
2042                 return dic.ContainsKey (key);
2043         }
2044
2045         public ICollection<K> Keys {
2046                 get { return dic.Keys; }
2047         }
2048
2049         public bool Remove (K key)
2050         {
2051                 return dic.Remove (key);
2052         }
2053
2054         public bool TryGetValue (K key, out V value)
2055         {
2056                 return dic.TryGetValue (key, out value);
2057         }
2058
2059         public ICollection<V> Values {
2060                 get { return dic.Values; }
2061         }
2062
2063         public V this [K key] {
2064                 get { return dic [key]; }
2065                 set { dic [key] = value; }
2066         }
2067
2068         IEnumerator IEnumerable.GetEnumerator ()
2069         {
2070                 return dic.GetEnumerator ();
2071         }
2072
2073         ICollection<KeyValuePair<K,V>> Coll {
2074                 get { return (ICollection<KeyValuePair<K,V>>) dic; }
2075         }
2076
2077         public void Add (KeyValuePair<K, V> item)
2078         {
2079                 Coll.Add (item);
2080         }
2081
2082         public void Clear ()
2083         {
2084                 dic.Clear ();
2085         }
2086
2087         public bool Contains (KeyValuePair<K, V> item)
2088         {
2089                 return Coll.Contains (item);
2090         }
2091
2092         public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
2093         {
2094                 Coll.CopyTo (array, arrayIndex);
2095         }
2096
2097         public int Count {
2098                 get { return dic.Count; }
2099         }
2100
2101         public bool IsReadOnly {
2102                 get { return Coll.IsReadOnly; }
2103         }
2104
2105         public bool Remove (KeyValuePair<K, V> item)
2106         {
2107                 return Coll.Remove (item);
2108         }
2109
2110         public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
2111         {
2112                 return Coll.GetEnumerator ();
2113         }
2114 }
2115
2116 [DataContract]
2117 public class Bug13485Type
2118 {
2119         [DataMember]
2120         public string Name { get; set; }
2121
2122         [DataMember (Name = "Value")]
2123         private string Value { get; set; }
2124
2125         public string GetValue { get { return this.Value; } }
2126 }
2127
2128 #region Test classes for Collection serialization
2129
2130 [DataContract]
2131         public abstract class CollectionContainer <V>
2132         {
2133                 V items;
2134
2135                 [DataMember]
2136                 public V Items
2137                 {
2138                         get {
2139                                 if (items == null) items = Init ();
2140                                 return items;
2141                         }
2142                 }
2143                 
2144                 public CollectionContainer ()
2145                 {
2146                         Init ();
2147                 }
2148         
2149                 protected abstract V Init ();
2150         }
2151         
2152         [DataContract]
2153         public class ArrayListContainer : CollectionContainer<ArrayList> {
2154                 protected override ArrayList Init ()
2155                 {
2156                         return new ArrayList { "banana", "apple" };
2157                 }
2158         }
2159         
2160         [DataContract]
2161         public class BitArrayContainer : CollectionContainer<BitArray> {
2162                 protected override BitArray Init ()
2163                 {
2164                         return new BitArray (new [] { false, true });
2165                 }
2166         }
2167         
2168         [DataContract]
2169         public class HashtableContainer : CollectionContainer<Hashtable> {
2170                 protected override Hashtable Init ()
2171                 {
2172                         var ht = new Hashtable ();
2173                         ht.Add ("key1", "banana");
2174                         ht.Add ("key2", "apple");
2175                         return ht;
2176                 }
2177         }
2178         
2179         [DataContract]
2180         public class QueueContainer : CollectionContainer<Queue> {
2181                 protected override Queue Init ()
2182                 {
2183                         var q = new Queue ();
2184                         q.Enqueue ("banana");
2185                         q.Enqueue ("apple");
2186                         return q;
2187                 }
2188         }
2189         
2190         [DataContract]
2191         public class SortedListContainer : CollectionContainer<SortedList> {
2192                 protected override SortedList Init ()
2193                 {
2194                         var l = new SortedList ();
2195                         l.Add ("key1", "banana");
2196                         l.Add ("key2", "apple");
2197                         return l;
2198                 }
2199         }
2200         
2201         [DataContract]
2202         public class StackContainer : CollectionContainer<Stack> {
2203                 protected override Stack Init ()
2204                 {
2205                         var s = new Stack ();
2206                         s.Push ("banana");
2207                         s.Push ("apple");
2208                         return s;
2209                 }
2210         }
2211
2212         public class EnumerableWithAdd : IEnumerable
2213         {
2214                 private ArrayList items;
2215
2216                 public EnumerableWithAdd()
2217                 {
2218                         items = new ArrayList();
2219                 }
2220
2221                 public IEnumerator GetEnumerator()
2222                 {
2223                         return items.GetEnumerator();
2224                 }
2225
2226                 public void Add(object value)
2227                 {
2228                         items.Add(value);
2229                 }
2230
2231                 public int Count
2232                 {
2233                         get {
2234                                 return items.Count;
2235                         }
2236                 }
2237         }
2238
2239         public class EnumerableWithSpecialAdd : IEnumerable
2240         {
2241                 private ArrayList items;
2242
2243                 public EnumerableWithSpecialAdd()
2244                 {
2245                         items = new ArrayList();
2246                 }
2247
2248                 public IEnumerator GetEnumerator()
2249                 {
2250                         return items.GetEnumerator();
2251                 }
2252
2253                 public void Add(object value, int index)
2254                 {
2255                         items.Add(value);
2256                 }
2257
2258                 public int Count
2259                 {
2260                         get
2261                         {
2262                                 return items.Count;
2263                         }
2264                 }
2265         }
2266
2267         [DataContract]
2268         public class EnumerableWithAddContainer : CollectionContainer<EnumerableWithAdd>
2269         {
2270                 protected override EnumerableWithAdd Init()
2271                 {
2272                         var s = new EnumerableWithAdd();
2273                         s.Add ("banana");
2274                         s.Add ("apple");
2275                         return s;
2276                 }
2277         }
2278
2279         [DataContract]
2280         public class EnumerableWithSpecialAddContainer : CollectionContainer<EnumerableWithSpecialAdd>
2281         {
2282                 protected override EnumerableWithSpecialAdd Init()
2283                 {
2284                         var s = new EnumerableWithSpecialAdd();
2285                         s.Add("banana", 0);
2286                         s.Add("apple", 0);
2287                         return s;
2288                 }
2289         }
2290
2291         [DataContract]
2292         public class GenericDictionaryContainer : CollectionContainer<Dictionary<string, string>> {
2293                 protected override Dictionary<string, string> Init ()
2294                 {
2295                         var d = new Dictionary<string, string> ();
2296                         d.Add ("key1", "banana");
2297                         d.Add ("key2", "apple");
2298                         return d;
2299                 }
2300         }
2301
2302         [DataContract]
2303         public class GenericHashSetContainer : CollectionContainer<HashSet<string>> {
2304                 protected override HashSet<string> Init ()
2305                 {
2306                         return new HashSet<string> { "banana", "apple" };
2307                 }
2308         }
2309
2310         [DataContract]
2311         public class GenericLinkedListContainer : CollectionContainer<LinkedList<string>> {
2312                 protected override LinkedList<string> Init ()
2313                 {
2314                         var l = new LinkedList<string> ();
2315                         l.AddFirst ("apple");
2316                         l.AddFirst ("banana");
2317                         return l;
2318                 }
2319         }
2320
2321         [DataContract]
2322         public class GenericListContainer : CollectionContainer<List<string>> {
2323                 protected override List<string> Init ()
2324                 {
2325                         return new List<string> { "banana", "apple" };
2326                 }
2327         }
2328
2329         [DataContract]
2330         public class GenericQueueContainer : CollectionContainer<Queue<string>> {
2331                 protected override Queue<string> Init ()
2332                 {
2333                         var q = new Queue<string> ();
2334                         q.Enqueue ("banana");
2335                         q.Enqueue ("apple" );
2336                         return q;
2337                 }
2338         }
2339
2340         [DataContract]
2341         public class GenericSortedDictionaryContainer : CollectionContainer<SortedDictionary<string, string>> {
2342                 protected override SortedDictionary<string, string> Init ()
2343                 {
2344                         var d = new SortedDictionary<string, string> ();
2345                         d.Add ("key1", "banana");
2346                         d.Add ("key2", "apple");
2347                         return d;
2348                 }
2349         }
2350
2351         [DataContract]
2352         public class GenericSortedListContainer : CollectionContainer<SortedList<string, string>> {
2353                 protected override SortedList<string, string> Init ()
2354                 {
2355                         var d = new SortedList<string, string> ();
2356                         d.Add ("key1", "banana");
2357                         d.Add ("key2", "apple");
2358                         return d;
2359                 }
2360         }
2361
2362         [DataContract]
2363         public class GenericStackContainer : CollectionContainer<Stack<string>> {
2364                 protected override Stack<string> Init ()
2365                 {
2366                         var s = new Stack<string> ();
2367                         s.Push ("banana");
2368                         s.Push ("apple" );
2369                         return s;
2370                 }
2371         }
2372
2373         public class GenericEnumerableWithAdd : IEnumerable<string>
2374         {
2375                 private List<string> items;
2376
2377                 public GenericEnumerableWithAdd()
2378                 {
2379                         items = new List<string>();
2380                 }
2381
2382                 IEnumerator IEnumerable.GetEnumerator()
2383                 {
2384                         return items.GetEnumerator ();
2385                 }
2386
2387                 public IEnumerator<string> GetEnumerator()
2388                 {
2389                         return items.GetEnumerator ();
2390                 }
2391
2392                 public void Add(string value)
2393                 {
2394                         items.Add(value);
2395                 }
2396
2397                 public int Count
2398                 {
2399                         get {
2400                                 return items.Count;
2401                         }
2402                 }
2403         }
2404
2405         public class GenericEnumerableWithSpecialAdd : IEnumerable<string>
2406         {
2407                 private List<string> items;
2408
2409                 public GenericEnumerableWithSpecialAdd()
2410                 {
2411                         items = new List<string>();
2412                 }
2413
2414                 IEnumerator IEnumerable.GetEnumerator()
2415                 {
2416                         return items.GetEnumerator ();
2417                 }
2418
2419                 public IEnumerator<string> GetEnumerator()
2420                 {
2421                         return items.GetEnumerator ();
2422                 }
2423
2424                 public void Add(string value, int index)
2425                 {
2426                         items.Add(value);
2427                 }
2428
2429                 public int Count
2430                 {
2431                         get
2432                         {
2433                                 return items.Count;
2434                         }
2435                 }
2436         }
2437
2438         [DataContract]
2439         public class GenericEnumerableWithAddContainer : CollectionContainer<GenericEnumerableWithAdd>
2440         {
2441                 protected override GenericEnumerableWithAdd Init()
2442                 {
2443                         var s = new GenericEnumerableWithAdd();
2444                         s.Add ("banana");
2445                         s.Add ("apple");
2446                         return s;
2447                 }
2448         }
2449
2450         [DataContract]
2451         public class GenericEnumerableWithSpecialAddContainer : CollectionContainer<GenericEnumerableWithSpecialAdd>
2452         {
2453                 protected override GenericEnumerableWithSpecialAdd Init()
2454                 {
2455                         var s = new GenericEnumerableWithSpecialAdd();
2456                         s.Add("banana", 0);
2457                         s.Add("apple", 0);
2458                         return s;
2459                 }
2460         }       
2461
2462         [DataContract]
2463         public class NonCollectionGetOnlyContainer
2464         {
2465                 string _test = "my string";
2466         
2467                 [DataMember]
2468                 public string MyString {
2469                         get {
2470                                 return _test;
2471                         }
2472                 }
2473         }       
2474
2475 #endregion