DataContractJsonSerializerTest.cs 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666
  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 = new DateTime (2010, 3, 4, 5, 6, 7),
  1204. EndDate = new DateTime (2010, 4, 5, 6, 7, 8)
  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-0500)\/""}";
  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 (634129344000000000, 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. #endregion
  1634. }
  1635. public class CharTest
  1636. {
  1637. public char Foo;
  1638. }
  1639. public class TestData
  1640. {
  1641. public string Foo { get; set; }
  1642. public string Bar { get; set; }
  1643. internal string Baz { get; set; }
  1644. }
  1645. public enum Colors {
  1646. Red, Green, Blue
  1647. }
  1648. [DataContract (Name = "_ColorsWithDC")]
  1649. public enum ColorsWithDC {
  1650. [EnumMember (Value = "_Red")]
  1651. Red,
  1652. [EnumMember]
  1653. Green,
  1654. Blue
  1655. }
  1656. public enum ColorsEnumMemberNoDC {
  1657. [EnumMember (Value = "_Red")]
  1658. Red,
  1659. [EnumMember]
  1660. Green,
  1661. Blue
  1662. }
  1663. [DataContract]
  1664. public class DCWithEnum {
  1665. [DataMember (Name = "_colors")]
  1666. public Colors colors;
  1667. }
  1668. [DataContract]
  1669. public class DCEmpty
  1670. {
  1671. // serializer doesn't touch it.
  1672. public string Foo = "TEST";
  1673. }
  1674. [DataContract]
  1675. public class DCSimple1
  1676. {
  1677. [DataMember]
  1678. public string Foo = "TEST";
  1679. }
  1680. [DataContract]
  1681. public class DCHasNonDC
  1682. {
  1683. [DataMember]
  1684. public NonDC Hoge= new NonDC ();
  1685. }
  1686. public class NonDC
  1687. {
  1688. public string Whee = "whee!";
  1689. }
  1690. [DataContract]
  1691. public class DCHasSerializable
  1692. {
  1693. [DataMember]
  1694. public SimpleSer1 Ser = new SimpleSer1 ();
  1695. }
  1696. [DataContract (Name = "Foo")]
  1697. public class DCWithName
  1698. {
  1699. [DataMember (Name = "FooMember")]
  1700. public string DMWithName = "value";
  1701. }
  1702. [DataContract (Name = "")]
  1703. public class DCWithEmptyName
  1704. {
  1705. [DataMember]
  1706. public string Foo;
  1707. }
  1708. [DataContract (Name = null)]
  1709. public class DCWithNullName
  1710. {
  1711. [DataMember]
  1712. public string Foo;
  1713. }
  1714. [DataContract (Namespace = "")]
  1715. public class DCWithEmptyNamespace
  1716. {
  1717. [DataMember]
  1718. public string Foo;
  1719. }
  1720. [Serializable]
  1721. public class SimpleSer1
  1722. {
  1723. public string Doh = "doh!";
  1724. }
  1725. public class Wrapper
  1726. {
  1727. [DataContract]
  1728. public class DCWrapped
  1729. {
  1730. }
  1731. }
  1732. [DataContract]
  1733. public class CollectionContainer
  1734. {
  1735. Collection<string> items = new Collection<string> ();
  1736. [DataMember]
  1737. public Collection<string> Items {
  1738. get { return items; }
  1739. }
  1740. }
  1741. [CollectionDataContract]
  1742. public class DataCollection<T> : Collection<T>
  1743. {
  1744. }
  1745. [DataContract]
  1746. public class DataCollectionContainer
  1747. {
  1748. DataCollection<string> items = new DataCollection<string> ();
  1749. [DataMember]
  1750. public DataCollection<string> Items {
  1751. get { return items; }
  1752. }
  1753. }
  1754. [DataContract]
  1755. class SerializeNonDCArrayType
  1756. {
  1757. [DataMember]
  1758. public NonDCItem [] IPAddresses = new NonDCItem [0];
  1759. }
  1760. public class NonDCItem
  1761. {
  1762. public byte [] Data { get; set; }
  1763. }
  1764. [DataContract]
  1765. public class VerifyObjectNameTestData
  1766. {
  1767. [DataMember]
  1768. string Member1 = "foo";
  1769. }
  1770. [Serializable]
  1771. public class KeyValueTestData {
  1772. public List<KeyValuePair<string,string>> TestData = new List<KeyValuePair<string,string>>();
  1773. }
  1774. [DataContract] // bug #586169
  1775. public class Query
  1776. {
  1777. [DataMember (Order=1)]
  1778. public DateTime StartDate { get; set; }
  1779. [DataMember (Order=2)]
  1780. public DateTime EndDate { get; set; }
  1781. }
  1782. public class ClassA {
  1783. public ClassB B { get; set; }
  1784. }
  1785. public class ClassB
  1786. {
  1787. }
  1788. public class GSPlayerListErg
  1789. {
  1790. public GSPlayerListErg ()
  1791. {
  1792. Init ();
  1793. }
  1794. void Init ()
  1795. {
  1796. C = true;
  1797. }
  1798. [OnDeserializing]
  1799. public void OnDeserializing (StreamingContext c)
  1800. {
  1801. A = true;
  1802. Init ();
  1803. }
  1804. [OnDeserialized]
  1805. void OnDeserialized (StreamingContext c)
  1806. {
  1807. B = true;
  1808. }
  1809. public static bool A, B, C;
  1810. [DataMember (Name = "T")]
  1811. public long CodedServerTimeUTC { get; set; }
  1812. public DateTime ServerTimeUTC { get; set; }
  1813. }
  1814. #region polymorphism test helper classes
  1815. [DataContract]
  1816. [KnownType (typeof (KnownDerivedType))]
  1817. public class ParentType
  1818. {
  1819. [DataMember]
  1820. public string Name { get; set; }
  1821. [DataMember]
  1822. public BaseType PolymorphicProperty { get; set; }
  1823. }
  1824. [DataContract]
  1825. public class BaseType
  1826. {
  1827. [DataMember]
  1828. public string BaseTypeProperty { get; set; }
  1829. }
  1830. [DataContract]
  1831. public class KnownDerivedType : BaseType
  1832. {
  1833. [DataMemberAttribute]
  1834. public string DerivedProperty { get; set; }
  1835. }
  1836. [DataContract]
  1837. public class UnknownDerivedType : BaseType
  1838. {
  1839. [DataMember]
  1840. public string DerivedProperty { get; set; }
  1841. }
  1842. #endregion
  1843. }
  1844. [DataContract]
  1845. class GlobalSample1
  1846. {
  1847. }
  1848. public class MyDictionary<K, V> : System.Collections.Generic.IDictionary<K, V>
  1849. {
  1850. Dictionary<K,V> dic = new Dictionary<K,V> ();
  1851. public void Add (K key, V value)
  1852. {
  1853. dic.Add (key, value);
  1854. }
  1855. public bool ContainsKey (K key)
  1856. {
  1857. return dic.ContainsKey (key);
  1858. }
  1859. public ICollection<K> Keys {
  1860. get { return dic.Keys; }
  1861. }
  1862. public bool Remove (K key)
  1863. {
  1864. return dic.Remove (key);
  1865. }
  1866. public bool TryGetValue (K key, out V value)
  1867. {
  1868. return dic.TryGetValue (key, out value);
  1869. }
  1870. public ICollection<V> Values {
  1871. get { return dic.Values; }
  1872. }
  1873. public V this [K key] {
  1874. get { return dic [key]; }
  1875. set { dic [key] = value; }
  1876. }
  1877. IEnumerator IEnumerable.GetEnumerator ()
  1878. {
  1879. return dic.GetEnumerator ();
  1880. }
  1881. ICollection<KeyValuePair<K,V>> Coll {
  1882. get { return (ICollection<KeyValuePair<K,V>>) dic; }
  1883. }
  1884. public void Add (KeyValuePair<K, V> item)
  1885. {
  1886. Coll.Add (item);
  1887. }
  1888. public void Clear ()
  1889. {
  1890. dic.Clear ();
  1891. }
  1892. public bool Contains (KeyValuePair<K, V> item)
  1893. {
  1894. return Coll.Contains (item);
  1895. }
  1896. public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
  1897. {
  1898. Coll.CopyTo (array, arrayIndex);
  1899. }
  1900. public int Count {
  1901. get { return dic.Count; }
  1902. }
  1903. public bool IsReadOnly {
  1904. get { return Coll.IsReadOnly; }
  1905. }
  1906. public bool Remove (KeyValuePair<K, V> item)
  1907. {
  1908. return Coll.Remove (item);
  1909. }
  1910. public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
  1911. {
  1912. return Coll.GetEnumerator ();
  1913. }
  1914. }
  1915. public class MyExplicitDictionary<K, V> : IDictionary<K, V> {
  1916. Dictionary<K,V> dic = new Dictionary<K,V> ();
  1917. public void Add (K key, V value)
  1918. {
  1919. dic.Add (key, value);
  1920. }
  1921. public bool ContainsKey (K key)
  1922. {
  1923. return dic.ContainsKey (key);
  1924. }
  1925. ICollection<K> IDictionary<K, V>.Keys {
  1926. get { return dic.Keys; }
  1927. }
  1928. public bool Remove (K key)
  1929. {
  1930. return dic.Remove (key);
  1931. }
  1932. public bool TryGetValue (K key, out V value)
  1933. {
  1934. return dic.TryGetValue (key, out value);
  1935. }
  1936. ICollection<V> IDictionary<K, V>.Values {
  1937. get { return dic.Values; }
  1938. }
  1939. public V this [K key] {
  1940. get { return dic [key]; }
  1941. set { dic [key] = value; }
  1942. }
  1943. IEnumerator IEnumerable.GetEnumerator ()
  1944. {
  1945. return dic.GetEnumerator ();
  1946. }
  1947. ICollection<KeyValuePair<K,V>> Coll {
  1948. get { return (ICollection<KeyValuePair<K,V>>) dic; }
  1949. }
  1950. public void Add (KeyValuePair<K, V> item)
  1951. {
  1952. Coll.Add (item);
  1953. }
  1954. public void Clear ()
  1955. {
  1956. dic.Clear ();
  1957. }
  1958. public bool Contains (KeyValuePair<K, V> item)
  1959. {
  1960. return Coll.Contains (item);
  1961. }
  1962. public void CopyTo (KeyValuePair<K, V> [] array, int arrayIndex)
  1963. {
  1964. Coll.CopyTo (array, arrayIndex);
  1965. }
  1966. public int Count {
  1967. get { return dic.Count; }
  1968. }
  1969. public bool IsReadOnly {
  1970. get { return Coll.IsReadOnly; }
  1971. }
  1972. public bool Remove (KeyValuePair<K, V> item)
  1973. {
  1974. return Coll.Remove (item);
  1975. }
  1976. public IEnumerator<KeyValuePair<K, V>> GetEnumerator ()
  1977. {
  1978. return Coll.GetEnumerator ();
  1979. }
  1980. }
  1981. [DataContract]
  1982. public class Bug13485Type
  1983. {
  1984. [DataMember]
  1985. public string Name { get; set; }
  1986. [DataMember (Name = "Value")]
  1987. private string Value { get; set; }
  1988. public string GetValue { get { return this.Value; } }
  1989. }
  1990. #region Test classes for Collection serialization
  1991. [DataContract]
  1992. public abstract class CollectionContainer <V>
  1993. {
  1994. V items;
  1995. [DataMember]
  1996. public V Items
  1997. {
  1998. get {
  1999. if (items == null) items = Init ();
  2000. return items;
  2001. }
  2002. }
  2003. public CollectionContainer ()
  2004. {
  2005. Init ();
  2006. }
  2007. protected abstract V Init ();
  2008. }
  2009. [DataContract]
  2010. public class ArrayListContainer : CollectionContainer<ArrayList> {
  2011. protected override ArrayList Init ()
  2012. {
  2013. return new ArrayList { "banana", "apple" };
  2014. }
  2015. }
  2016. [DataContract]
  2017. public class BitArrayContainer : CollectionContainer<BitArray> {
  2018. protected override BitArray Init ()
  2019. {
  2020. return new BitArray (new [] { false, true });
  2021. }
  2022. }
  2023. [DataContract]
  2024. public class HashtableContainer : CollectionContainer<Hashtable> {
  2025. protected override Hashtable Init ()
  2026. {
  2027. var ht = new Hashtable ();
  2028. ht.Add ("key1", "banana");
  2029. ht.Add ("key2", "apple");
  2030. return ht;
  2031. }
  2032. }
  2033. [DataContract]
  2034. public class QueueContainer : CollectionContainer<Queue> {
  2035. protected override Queue Init ()
  2036. {
  2037. var q = new Queue ();
  2038. q.Enqueue ("banana");
  2039. q.Enqueue ("apple");
  2040. return q;
  2041. }
  2042. }
  2043. [DataContract]
  2044. public class SortedListContainer : CollectionContainer<SortedList> {
  2045. protected override SortedList Init ()
  2046. {
  2047. var l = new SortedList ();
  2048. l.Add ("key1", "banana");
  2049. l.Add ("key2", "apple");
  2050. return l;
  2051. }
  2052. }
  2053. [DataContract]
  2054. public class StackContainer : CollectionContainer<Stack> {
  2055. protected override Stack Init ()
  2056. {
  2057. var s = new Stack ();
  2058. s.Push ("banana");
  2059. s.Push ("apple");
  2060. return s;
  2061. }
  2062. }
  2063. public class EnumerableWithAdd : IEnumerable
  2064. {
  2065. private ArrayList items;
  2066. public EnumerableWithAdd()
  2067. {
  2068. items = new ArrayList();
  2069. }
  2070. public IEnumerator GetEnumerator()
  2071. {
  2072. return items.GetEnumerator();
  2073. }
  2074. public void Add(object value)
  2075. {
  2076. items.Add(value);
  2077. }
  2078. public int Count
  2079. {
  2080. get {
  2081. return items.Count;
  2082. }
  2083. }
  2084. }
  2085. public class EnumerableWithSpecialAdd : IEnumerable
  2086. {
  2087. private ArrayList items;
  2088. public EnumerableWithSpecialAdd()
  2089. {
  2090. items = new ArrayList();
  2091. }
  2092. public IEnumerator GetEnumerator()
  2093. {
  2094. return items.GetEnumerator();
  2095. }
  2096. public void Add(object value, int index)
  2097. {
  2098. items.Add(value);
  2099. }
  2100. public int Count
  2101. {
  2102. get
  2103. {
  2104. return items.Count;
  2105. }
  2106. }
  2107. }
  2108. [DataContract]
  2109. public class EnumerableWithAddContainer : CollectionContainer<EnumerableWithAdd>
  2110. {
  2111. protected override EnumerableWithAdd Init()
  2112. {
  2113. var s = new EnumerableWithAdd();
  2114. s.Add ("banana");
  2115. s.Add ("apple");
  2116. return s;
  2117. }
  2118. }
  2119. [DataContract]
  2120. public class EnumerableWithSpecialAddContainer : CollectionContainer<EnumerableWithSpecialAdd>
  2121. {
  2122. protected override EnumerableWithSpecialAdd Init()
  2123. {
  2124. var s = new EnumerableWithSpecialAdd();
  2125. s.Add("banana", 0);
  2126. s.Add("apple", 0);
  2127. return s;
  2128. }
  2129. }
  2130. [DataContract]
  2131. public class GenericDictionaryContainer : CollectionContainer<Dictionary<string, string>> {
  2132. protected override Dictionary<string, string> Init ()
  2133. {
  2134. var d = new Dictionary<string, string> ();
  2135. d.Add ("key1", "banana");
  2136. d.Add ("key2", "apple");
  2137. return d;
  2138. }
  2139. }
  2140. [DataContract]
  2141. public class GenericHashSetContainer : CollectionContainer<HashSet<string>> {
  2142. protected override HashSet<string> Init ()
  2143. {
  2144. return new HashSet<string> { "banana", "apple" };
  2145. }
  2146. }
  2147. [DataContract]
  2148. public class GenericLinkedListContainer : CollectionContainer<LinkedList<string>> {
  2149. protected override LinkedList<string> Init ()
  2150. {
  2151. var l = new LinkedList<string> ();
  2152. l.AddFirst ("apple");
  2153. l.AddFirst ("banana");
  2154. return l;
  2155. }
  2156. }
  2157. [DataContract]
  2158. public class GenericListContainer : CollectionContainer<List<string>> {
  2159. protected override List<string> Init ()
  2160. {
  2161. return new List<string> { "banana", "apple" };
  2162. }
  2163. }
  2164. [DataContract]
  2165. public class GenericQueueContainer : CollectionContainer<Queue<string>> {
  2166. protected override Queue<string> Init ()
  2167. {
  2168. var q = new Queue<string> ();
  2169. q.Enqueue ("banana");
  2170. q.Enqueue ("apple" );
  2171. return q;
  2172. }
  2173. }
  2174. [DataContract]
  2175. public class GenericSortedDictionaryContainer : CollectionContainer<SortedDictionary<string, string>> {
  2176. protected override SortedDictionary<string, string> Init ()
  2177. {
  2178. var d = new SortedDictionary<string, string> ();
  2179. d.Add ("key1", "banana");
  2180. d.Add ("key2", "apple");
  2181. return d;
  2182. }
  2183. }
  2184. [DataContract]
  2185. public class GenericSortedListContainer : CollectionContainer<SortedList<string, string>> {
  2186. protected override SortedList<string, string> Init ()
  2187. {
  2188. var d = new SortedList<string, string> ();
  2189. d.Add ("key1", "banana");
  2190. d.Add ("key2", "apple");
  2191. return d;
  2192. }
  2193. }
  2194. [DataContract]
  2195. public class GenericStackContainer : CollectionContainer<Stack<string>> {
  2196. protected override Stack<string> Init ()
  2197. {
  2198. var s = new Stack<string> ();
  2199. s.Push ("banana");
  2200. s.Push ("apple" );
  2201. return s;
  2202. }
  2203. }
  2204. public class GenericEnumerableWithAdd : IEnumerable<string>
  2205. {
  2206. private List<string> items;
  2207. public GenericEnumerableWithAdd()
  2208. {
  2209. items = new List<string>();
  2210. }
  2211. IEnumerator IEnumerable.GetEnumerator()
  2212. {
  2213. return items.GetEnumerator ();
  2214. }
  2215. public IEnumerator<string> GetEnumerator()
  2216. {
  2217. return items.GetEnumerator ();
  2218. }
  2219. public void Add(string value)
  2220. {
  2221. items.Add(value);
  2222. }
  2223. public int Count
  2224. {
  2225. get {
  2226. return items.Count;
  2227. }
  2228. }
  2229. }
  2230. public class GenericEnumerableWithSpecialAdd : IEnumerable<string>
  2231. {
  2232. private List<string> items;
  2233. public GenericEnumerableWithSpecialAdd()
  2234. {
  2235. items = new List<string>();
  2236. }
  2237. IEnumerator IEnumerable.GetEnumerator()
  2238. {
  2239. return items.GetEnumerator ();
  2240. }
  2241. public IEnumerator<string> GetEnumerator()
  2242. {
  2243. return items.GetEnumerator ();
  2244. }
  2245. public void Add(string value, int index)
  2246. {
  2247. items.Add(value);
  2248. }
  2249. public int Count
  2250. {
  2251. get
  2252. {
  2253. return items.Count;
  2254. }
  2255. }
  2256. }
  2257. [DataContract]
  2258. public class GenericEnumerableWithAddContainer : CollectionContainer<GenericEnumerableWithAdd>
  2259. {
  2260. protected override GenericEnumerableWithAdd Init()
  2261. {
  2262. var s = new GenericEnumerableWithAdd();
  2263. s.Add ("banana");
  2264. s.Add ("apple");
  2265. return s;
  2266. }
  2267. }
  2268. [DataContract]
  2269. public class GenericEnumerableWithSpecialAddContainer : CollectionContainer<GenericEnumerableWithSpecialAdd>
  2270. {
  2271. protected override GenericEnumerableWithSpecialAdd Init()
  2272. {
  2273. var s = new GenericEnumerableWithSpecialAdd();
  2274. s.Add("banana", 0);
  2275. s.Add("apple", 0);
  2276. return s;
  2277. }
  2278. }
  2279. [DataContract]
  2280. public class NonCollectionGetOnlyContainer
  2281. {
  2282. string _test = "my string";
  2283. [DataMember]
  2284. public string MyString {
  2285. get {
  2286. return _test;
  2287. }
  2288. }
  2289. }
  2290. #endregion