DataContractJsonSerializerTest.cs 74 KB

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