DataContractJsonSerializerTest.cs 72 KB

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