ObjectStateFormatter.cs 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059
  1. //
  2. // System.Web.UI.ObjectStateFormatter
  3. //
  4. // Authors:
  5. // Ben Maurer ([email protected])
  6. // Gonzalo Paniagua ([email protected])
  7. //
  8. // (C) 2003 Ben Maurer
  9. // (c) Copyright 2004-2008 Novell, Inc. (http://www.novell.com)
  10. //
  11. //
  12. // Permission is hereby granted, free of charge, to any person obtaining
  13. // a copy of this software and associated documentation files (the
  14. // "Software"), to deal in the Software without restriction, including
  15. // without limitation the rights to use, copy, modify, merge, publish,
  16. // distribute, sublicense, and/or sell copies of the Software, and to
  17. // permit persons to whom the Software is furnished to do so, subject to
  18. // the following conditions:
  19. //
  20. // The above copyright notice and this permission notice shall be
  21. // included in all copies or substantial portions of the Software.
  22. //
  23. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  24. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  25. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  26. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  27. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  28. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  29. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  30. //
  31. //#define TRACE
  32. using System.Collections;
  33. using System.ComponentModel;
  34. using System.Globalization;
  35. using System.Drawing;
  36. using System.IO;
  37. using System.Reflection;
  38. using System.Runtime.Serialization.Formatters.Binary;
  39. using System.Runtime.Serialization;
  40. using System.Text;
  41. using System.Web.UI.WebControls;
  42. using System.Web.Util;
  43. using System.Diagnostics;
  44. using System.Security.Cryptography;
  45. using System.Web.Configuration;
  46. namespace System.Web.UI {
  47. #if NET_2_0
  48. public
  49. #else
  50. internal
  51. #endif
  52. sealed class ObjectStateFormatter : IFormatter, IStateFormatter
  53. {
  54. Page page;
  55. HashAlgorithm algo;
  56. byte [] vkey;
  57. public ObjectStateFormatter ()
  58. {
  59. }
  60. internal ObjectStateFormatter (Page page)
  61. {
  62. this.page = page;
  63. }
  64. internal ObjectStateFormatter (byte [] vkey)
  65. {
  66. this.vkey = vkey;
  67. }
  68. internal bool EnableMac {
  69. get {
  70. if (page == null) {
  71. if (vkey == null)
  72. return false;
  73. return true;
  74. } else {
  75. #if NET_2_0
  76. return page.EnableViewStateMac;
  77. #elif NET_1_1
  78. return page.EnableViewStateMacInternal;
  79. #else
  80. return false;
  81. #endif
  82. }
  83. }
  84. }
  85. internal HashAlgorithm GetAlgo ()
  86. {
  87. if (algo != null)
  88. return algo;
  89. if (!EnableMac)
  90. return null;
  91. byte [] algoKey;
  92. if (page != null) {
  93. #if NET_2_0
  94. MachineKeySection mconfig = (MachineKeySection) WebConfigurationManager.GetWebApplicationSection ("system.web/machineKey");
  95. algoKey = MachineKeySectionUtils.ValidationKeyBytes (mconfig);
  96. #else
  97. MachineKeyConfig mconfig = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
  98. algoKey = mconfig.ValidationKey;
  99. #endif
  100. } else
  101. algoKey = vkey;
  102. algo = new HMACSHA1 (algoKey);
  103. return algo;
  104. }
  105. static int ValidateInput (HashAlgorithm algo, byte [] data, int offset, int size)
  106. {
  107. if (algo == null)
  108. throw new HttpException ("Unable to validate data.");
  109. int hash_size = algo.HashSize / 8;
  110. if (size != 0 && size < hash_size)
  111. throw new HttpException ("Unable to validate data.");
  112. int data_length = size - hash_size;
  113. MemoryStream data_stream = new MemoryStream (data, offset, data_length, false, false);
  114. byte [] hash = algo.ComputeHash (data_stream);
  115. for (int i = 0; i < hash_size; i++) {
  116. if (hash [i] != data [data_length + i])
  117. throw new HttpException ("Unable to validate data.");
  118. }
  119. return data_length;
  120. }
  121. public object Deserialize (Stream inputStream)
  122. {
  123. if (inputStream == null)
  124. throw new ArgumentNullException ("inputStream");
  125. return DeserializeObject (new BinaryReader (inputStream));
  126. }
  127. public object Deserialize (string inputString)
  128. {
  129. if (inputString == null)
  130. throw new ArgumentNullException ("inputString");
  131. #if NET_2_0
  132. if (inputString.Length == 0)
  133. throw new ArgumentNullException ("inputString");
  134. #else
  135. if (inputString == "")
  136. return "";
  137. #endif
  138. byte [] buffer = Convert.FromBase64String (inputString);
  139. int length;
  140. if (buffer == null || (length = buffer.Length) == 0)
  141. throw new ArgumentNullException ("inputString");
  142. if (page != null && EnableMac)
  143. length = ValidateInput (GetAlgo (), buffer, 0, length);
  144. #if NET_2_0
  145. bool isEncrypted = ((int)buffer [--length] == 1)? true : false;
  146. #endif
  147. Stream ms = new MemoryStream (buffer, 0, length, false, false);
  148. #if NET_2_0
  149. if (isEncrypted)
  150. ms = new CryptoStream (ms, page.GetCryptoTransform (CryptoStreamMode.Read), CryptoStreamMode.Read);
  151. #endif
  152. return Deserialize (ms);
  153. }
  154. public string Serialize (object stateGraph)
  155. {
  156. if (stateGraph == null)
  157. return "";
  158. MemoryStream ms = new MemoryStream ();
  159. Stream output = ms;
  160. #if NET_2_0
  161. bool needEncryption = page == null ? false : page.NeedViewStateEncryption;
  162. if (needEncryption){
  163. output = new CryptoStream (output, page.GetCryptoTransform (CryptoStreamMode.Write), CryptoStreamMode.Write);
  164. }
  165. #endif
  166. Serialize (output, stateGraph);
  167. #if NET_2_0
  168. ms.WriteByte((byte)(needEncryption? 1 : 0));
  169. #endif
  170. #if TRACE
  171. ms.WriteTo (File.OpenWrite (Path.GetTempFileName ()));
  172. #endif
  173. if (EnableMac && ms.Length > 0) {
  174. HashAlgorithm algo = GetAlgo ();
  175. if (algo != null) {
  176. byte [] hash = algo.ComputeHash (ms.GetBuffer (), 0, (int) ms.Length);
  177. ms.Write (hash, 0, hash.Length);
  178. }
  179. }
  180. return Convert.ToBase64String (ms.GetBuffer (), 0, (int) ms.Length);
  181. }
  182. public void Serialize (Stream outputStream, object stateGraph)
  183. {
  184. if (outputStream == null)
  185. throw new ArgumentNullException ("outputStream");
  186. if (stateGraph == null)
  187. throw new ArgumentNullException ("stateGraph");
  188. SerializeValue (new BinaryWriter (outputStream), stateGraph);
  189. }
  190. void SerializeValue (BinaryWriter w, object o)
  191. {
  192. ObjectFormatter.WriteObject (w, o, new WriterContext ());
  193. }
  194. object DeserializeObject (BinaryReader r)
  195. {
  196. return ObjectFormatter.ReadObject (r, new ReaderContext ());
  197. }
  198. #region IFormatter
  199. object IFormatter.Deserialize (Stream serializationStream)
  200. {
  201. return Deserialize (serializationStream);
  202. }
  203. void IFormatter.Serialize (Stream serializationStream, object stateGraph)
  204. {
  205. Serialize (serializationStream, stateGraph);
  206. }
  207. SerializationBinder IFormatter.Binder {
  208. get { return null; }
  209. set { }
  210. }
  211. StreamingContext IFormatter.Context {
  212. get { return new StreamingContext (StreamingContextStates.All); }
  213. set { }
  214. }
  215. ISurrogateSelector IFormatter.SurrogateSelector {
  216. get { return null; }
  217. set { }
  218. }
  219. #endregion
  220. #region Object Readers/Writers
  221. class WriterContext
  222. {
  223. Hashtable cache;
  224. short nextKey = 0;
  225. short key = 0;
  226. public short Key {
  227. get { return key; }
  228. }
  229. public bool RegisterCache (object o)
  230. {
  231. if (nextKey == short.MaxValue)
  232. return false;
  233. if (cache == null) {
  234. cache = new Hashtable ();
  235. cache.Add (o, key = nextKey++);
  236. return false;
  237. }
  238. object posKey = cache [o];
  239. if (posKey == null) {
  240. cache.Add (o, key = nextKey++);
  241. return false;
  242. }
  243. key = (short) posKey;
  244. return true;
  245. }
  246. }
  247. class ReaderContext
  248. {
  249. ArrayList cache;
  250. public void CacheItem (object o)
  251. {
  252. if (cache == null)
  253. cache = new ArrayList ();
  254. cache.Add (o);
  255. }
  256. public object GetCache (short key)
  257. {
  258. return cache [key];
  259. }
  260. }
  261. abstract class ObjectFormatter
  262. {
  263. static readonly Hashtable writeMap = new Hashtable ();
  264. static ObjectFormatter [] readMap = new ObjectFormatter [256];
  265. static BinaryObjectFormatter binaryObjectFormatter;
  266. static TypeFormatter typeFormatter;
  267. static EnumFormatter enumFormatter;
  268. static SingleRankArrayFormatter singleRankArrayFormatter;
  269. static TypeConverterFormatter typeConverterFormatter;
  270. static ObjectFormatter ()
  271. {
  272. new StringFormatter ().Register ();
  273. new Int64Formatter ().Register ();
  274. new Int32Formatter ().Register ();
  275. new Int16Formatter ().Register ();
  276. new ByteFormatter ().Register ();
  277. new BooleanFormatter ().Register ();
  278. new CharFormatter ().Register ();
  279. new DateTimeFormatter ().Register ();
  280. new PairFormatter ().Register ();
  281. new TripletFormatter ().Register ();
  282. new ArrayListFormatter ().Register ();
  283. new HashtableFormatter ().Register ();
  284. new ObjectArrayFormatter ().Register ();
  285. new UnitFormatter ().Register ();
  286. new FontUnitFormatter ().Register ();
  287. new ColorFormatter ().Register ();
  288. enumFormatter = new EnumFormatter ();
  289. enumFormatter.Register ();
  290. typeFormatter = new TypeFormatter ();
  291. typeFormatter.Register ();
  292. singleRankArrayFormatter = new SingleRankArrayFormatter ();
  293. singleRankArrayFormatter.Register ();
  294. typeConverterFormatter = new TypeConverterFormatter ();
  295. typeConverterFormatter.Register ();
  296. binaryObjectFormatter = new BinaryObjectFormatter ();
  297. binaryObjectFormatter.Register ();
  298. }
  299. // 0 == null
  300. static byte nextId = 1;
  301. public ObjectFormatter ()
  302. {
  303. PrimaryId = nextId ++;
  304. if (NumberOfIds == 1)
  305. return;
  306. SecondaryId = nextId ++;
  307. if (NumberOfIds == 2)
  308. return;
  309. TertiaryId = nextId ++;
  310. if (NumberOfIds == 3)
  311. return;
  312. throw new Exception ();
  313. }
  314. protected readonly byte PrimaryId, SecondaryId = 255, TertiaryId = 255;
  315. protected abstract void Write (BinaryWriter w, object o, WriterContext ctx);
  316. protected abstract object Read (byte token, BinaryReader r, ReaderContext ctx);
  317. protected abstract Type Type { get; }
  318. protected virtual int NumberOfIds { get { return 1; } }
  319. public virtual void Register ()
  320. {
  321. writeMap [Type] = this;
  322. readMap [PrimaryId] = this;
  323. if (SecondaryId != 255) {
  324. readMap [SecondaryId] = this;
  325. if (TertiaryId != 255)
  326. readMap [TertiaryId] = this;
  327. }
  328. }
  329. public static void WriteObject (BinaryWriter w, object o, WriterContext ctx)
  330. {
  331. #if TRACE && !TARGET_J2EE
  332. if (o != null) {
  333. Trace.WriteLine (String.Format ("Writing {0} (type: {1})", o, o.GetType ()));
  334. Trace.Indent ();
  335. } else {
  336. Trace.WriteLine ("Writing null");
  337. }
  338. long pos = w.BaseStream.Position;
  339. #endif
  340. if (o == null) {
  341. w.Write ((byte) 0);
  342. return;
  343. }
  344. Type t = o.GetType ();
  345. #if TRACE
  346. Trace.WriteLine (String.Format ("Looking up formatter for type {0}", t));
  347. #endif
  348. ObjectFormatter fmt = writeMap [t] as ObjectFormatter;
  349. #if TRACE
  350. Trace.WriteLine (String.Format ("Formatter from writeMap: '{0}'", fmt));
  351. #endif
  352. if (fmt == null) {
  353. // Handle abstract types here
  354. if (o is Type)
  355. fmt = typeFormatter;
  356. else if (t.IsEnum)
  357. fmt = enumFormatter;
  358. else if (t.IsArray && ((Array) o).Rank == 1)
  359. fmt = singleRankArrayFormatter;
  360. else {
  361. TypeConverter converter;
  362. converter = TypeDescriptor.GetConverter (o);
  363. #if TRACE
  364. Trace.WriteLine (String.Format ("Type converter: '{0}' (to string: {1}; from {2}: {3})",
  365. converter,
  366. converter != null ? converter.CanConvertTo (typeof (string)) : false,
  367. t,
  368. converter != null ? converter.CanConvertFrom (t) : false));
  369. #endif
  370. if (converter == null || !converter.CanConvertTo (typeof (string)))
  371. fmt = binaryObjectFormatter;
  372. else {
  373. typeConverterFormatter.Converter = converter;
  374. fmt = typeConverterFormatter;
  375. }
  376. }
  377. }
  378. #if TRACE
  379. Trace.WriteLine (String.Format ("Writing with formatter '{0}'", fmt.GetType ()));
  380. #endif
  381. fmt.Write (w, o, ctx);
  382. #if TRACE && !TARGET_J2EE
  383. Trace.Unindent ();
  384. Trace.WriteLine (String.Format ("Wrote {0} (type: {1}) {2} bytes", o, o.GetType (), w.BaseStream.Position - pos));
  385. #endif
  386. }
  387. public static object ReadObject (BinaryReader r, ReaderContext ctx)
  388. {
  389. byte sig = r.ReadByte ();
  390. if (sig == 0)
  391. return null;
  392. return readMap [sig].Read (sig, r, ctx);
  393. }
  394. protected void Write7BitEncodedInt (BinaryWriter w, int value)
  395. {
  396. do {
  397. int high = (value >> 7) & 0x01ffffff;
  398. byte b = (byte)(value & 0x7f);
  399. if (high != 0)
  400. b = (byte)(b | 0x80);
  401. w.Write(b);
  402. value = high;
  403. } while(value != 0);
  404. }
  405. protected int Read7BitEncodedInt (BinaryReader r)
  406. {
  407. int ret = 0;
  408. int shift = 0;
  409. byte b;
  410. do {
  411. b = r.ReadByte();
  412. ret = ret | ((b & 0x7f) << shift);
  413. shift += 7;
  414. } while ((b & 0x80) == 0x80);
  415. return ret;
  416. }
  417. }
  418. #region Primitive Formatters
  419. class StringFormatter : ObjectFormatter
  420. {
  421. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  422. {
  423. if (ctx.RegisterCache (o)) {
  424. w.Write (SecondaryId);
  425. w.Write (ctx.Key);
  426. } else {
  427. w.Write (PrimaryId);
  428. w.Write ((string)o);
  429. }
  430. }
  431. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  432. {
  433. if (token == PrimaryId) {
  434. string s = r.ReadString ();
  435. ctx.CacheItem (s);
  436. return s;
  437. } else {
  438. return ctx.GetCache (r.ReadInt16 ());
  439. }
  440. }
  441. protected override Type Type {
  442. get { return typeof (string); }
  443. }
  444. protected override int NumberOfIds {
  445. get { return 2; }
  446. }
  447. }
  448. class Int64Formatter : ObjectFormatter
  449. {
  450. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  451. {
  452. w.Write (PrimaryId);
  453. w.Write ((long)o);
  454. }
  455. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  456. {
  457. return r.ReadInt64 ();
  458. }
  459. protected override Type Type {
  460. get { return typeof (long); }
  461. }
  462. }
  463. class Int32Formatter : ObjectFormatter
  464. {
  465. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  466. {
  467. int i = (int) o;
  468. if ((int)(byte) i == i) {
  469. w.Write (SecondaryId);
  470. w.Write ((byte) i);
  471. } else {
  472. w.Write (PrimaryId);
  473. w.Write (i);
  474. }
  475. }
  476. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  477. {
  478. if (token == PrimaryId)
  479. return r.ReadInt32 ();
  480. else
  481. return (int) r.ReadByte ();
  482. }
  483. protected override Type Type {
  484. get { return typeof (int); }
  485. }
  486. protected override int NumberOfIds {
  487. get { return 2; }
  488. }
  489. }
  490. class Int16Formatter : ObjectFormatter
  491. {
  492. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  493. {
  494. w.Write (PrimaryId);
  495. w.Write ((short)o);
  496. }
  497. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  498. {
  499. return r.ReadInt16 ();
  500. }
  501. protected override Type Type {
  502. get { return typeof (short); }
  503. }
  504. }
  505. class ByteFormatter : ObjectFormatter
  506. {
  507. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  508. {
  509. w.Write (PrimaryId);
  510. w.Write ((byte)o);
  511. }
  512. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  513. {
  514. return r.ReadByte ();
  515. }
  516. protected override Type Type {
  517. get { return typeof (byte); }
  518. }
  519. }
  520. class BooleanFormatter : ObjectFormatter
  521. {
  522. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  523. {
  524. if ((bool)o == true)
  525. w.Write (PrimaryId);
  526. else
  527. w.Write (SecondaryId);
  528. }
  529. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  530. {
  531. return token == PrimaryId;
  532. }
  533. protected override Type Type {
  534. get { return typeof (bool); }
  535. }
  536. protected override int NumberOfIds {
  537. get { return 2; }
  538. }
  539. }
  540. class CharFormatter : ObjectFormatter
  541. {
  542. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  543. {
  544. w.Write (PrimaryId);
  545. w.Write ((char) o);
  546. }
  547. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  548. {
  549. return r.ReadChar ();
  550. }
  551. protected override Type Type {
  552. get { return typeof (char); }
  553. }
  554. }
  555. class DateTimeFormatter : ObjectFormatter
  556. {
  557. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  558. {
  559. w.Write (PrimaryId);
  560. w.Write (((DateTime) o).Ticks);
  561. }
  562. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  563. {
  564. return new DateTime (r.ReadInt64 ());
  565. }
  566. protected override Type Type {
  567. get { return typeof (DateTime); }
  568. }
  569. }
  570. class PairFormatter : ObjectFormatter
  571. {
  572. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  573. {
  574. Pair p = (Pair) o;
  575. w.Write (PrimaryId);
  576. WriteObject (w, p.First, ctx);
  577. WriteObject (w, p.Second, ctx);
  578. }
  579. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  580. {
  581. Pair p = new Pair ();
  582. p.First = ReadObject (r, ctx);
  583. p.Second = ReadObject (r, ctx);
  584. return p;
  585. }
  586. protected override Type Type {
  587. get { return typeof (Pair); }
  588. }
  589. }
  590. class TripletFormatter : ObjectFormatter
  591. {
  592. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  593. {
  594. Triplet t = (Triplet) o;
  595. w.Write (PrimaryId);
  596. WriteObject (w, t.First, ctx);
  597. WriteObject (w, t.Second, ctx);
  598. WriteObject (w, t.Third, ctx);
  599. }
  600. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  601. {
  602. Triplet t = new Triplet ();
  603. t.First = ReadObject (r, ctx);
  604. t.Second = ReadObject (r, ctx);
  605. t.Third = ReadObject (r, ctx);
  606. return t;
  607. }
  608. protected override Type Type {
  609. get { return typeof (Triplet); }
  610. }
  611. }
  612. class ArrayListFormatter : ObjectFormatter
  613. {
  614. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  615. {
  616. ArrayList l = (ArrayList) o;
  617. w.Write (PrimaryId);
  618. Write7BitEncodedInt (w, l.Count);
  619. for (int i = 0; i < l.Count; i++)
  620. WriteObject (w, l [i], ctx);
  621. }
  622. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  623. {
  624. int len = Read7BitEncodedInt (r);
  625. ArrayList l = new ArrayList (len);
  626. for (int i = 0; i < len; i++)
  627. l.Add (ReadObject (r, ctx));
  628. return l;
  629. }
  630. protected override Type Type {
  631. get { return typeof (ArrayList); }
  632. }
  633. }
  634. class HashtableFormatter : ObjectFormatter
  635. {
  636. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  637. {
  638. Hashtable ht = (Hashtable) o;
  639. w.Write (PrimaryId);
  640. Write7BitEncodedInt (w, ht.Count);
  641. foreach (DictionaryEntry de in ht) {
  642. WriteObject (w, de.Key, ctx);
  643. WriteObject (w, de.Value, ctx);
  644. }
  645. }
  646. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  647. {
  648. int len = Read7BitEncodedInt (r);
  649. Hashtable ht = new Hashtable (len);
  650. for (int i = 0; i < len; i++) {
  651. object key = ReadObject (r, ctx);
  652. object val = ReadObject (r, ctx);
  653. ht.Add (key, val);
  654. }
  655. return ht;
  656. }
  657. protected override Type Type {
  658. get { return typeof (Hashtable); }
  659. }
  660. }
  661. class ObjectArrayFormatter : ObjectFormatter
  662. {
  663. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  664. {
  665. object [] val = (object []) o;
  666. w.Write (PrimaryId);
  667. Write7BitEncodedInt (w, val.Length);
  668. for (int i = 0; i < val.Length; i++)
  669. WriteObject (w, val [i], ctx);
  670. }
  671. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  672. {
  673. int len = Read7BitEncodedInt (r);
  674. object [] ret = new object [len];
  675. for (int i = 0; i < len; i++)
  676. ret [i] = ReadObject (r, ctx);
  677. return ret;
  678. }
  679. protected override Type Type {
  680. get { return typeof (object []); }
  681. }
  682. }
  683. #endregion
  684. #region System.Web Optimizations
  685. class ColorFormatter : ObjectFormatter
  686. {
  687. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  688. {
  689. Color c = (Color) o;
  690. if (c.IsEmpty || c.IsKnownColor) {
  691. w.Write (SecondaryId);
  692. if (c.IsEmpty)
  693. w.Write (-1); //isempty marker
  694. else
  695. w.Write ((int) c.ToKnownColor ());
  696. } else {
  697. w.Write (PrimaryId);
  698. w.Write (c.ToArgb ());
  699. }
  700. }
  701. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  702. {
  703. int value = r.ReadInt32 ();
  704. if (token == PrimaryId)
  705. return Color.FromArgb (value);
  706. else {
  707. if (value == -1) //isempty marker
  708. return Color.Empty;
  709. return Color.FromKnownColor ((KnownColor)value);
  710. }
  711. }
  712. protected override Type Type {
  713. get { return typeof (Color); }
  714. }
  715. protected override int NumberOfIds {
  716. get { return 2; }
  717. }
  718. }
  719. #endregion
  720. #region Special Formatters
  721. class EnumFormatter : ObjectFormatter
  722. {
  723. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  724. {
  725. object value = Convert.ChangeType (o, ((Enum) o).GetTypeCode ());
  726. w.Write (PrimaryId);
  727. WriteObject (w, o.GetType (), ctx);
  728. WriteObject (w, value, ctx);
  729. }
  730. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  731. {
  732. Type t = (Type) ReadObject (r, ctx);
  733. object value = ReadObject (r, ctx);
  734. return Enum.ToObject (t, value);
  735. }
  736. protected override Type Type {
  737. get { return typeof (Enum); }
  738. }
  739. }
  740. class TypeFormatter : ObjectFormatter
  741. {
  742. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  743. {
  744. if (ctx.RegisterCache (o)) {
  745. w.Write (SecondaryId);
  746. w.Write (ctx.Key);
  747. } else {
  748. w.Write (PrimaryId);
  749. w.Write (((Type) o).FullName);
  750. // We should cache the name of the assembly
  751. w.Write (((Type) o).Assembly.FullName);
  752. }
  753. }
  754. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  755. {
  756. if (token == PrimaryId) {
  757. string type = r.ReadString ();
  758. string assembly = r.ReadString ();
  759. Type t = Assembly.Load (assembly).GetType (type);
  760. ctx.CacheItem (t);
  761. return t;
  762. } else {
  763. return ctx.GetCache (r.ReadInt16 ());
  764. }
  765. }
  766. protected override Type Type {
  767. get { return typeof (Type); }
  768. }
  769. protected override int NumberOfIds {
  770. get { return 2; }
  771. }
  772. }
  773. class SingleRankArrayFormatter : ObjectFormatter
  774. {
  775. readonly BinaryFormatter _binaryFormatter = new BinaryFormatter ();
  776. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  777. {
  778. Array val = (Array) o;
  779. if (val.GetType ().GetElementType ().IsPrimitive) {
  780. w.Write (SecondaryId);
  781. _binaryFormatter.Serialize (w.BaseStream, o);
  782. return;
  783. }
  784. w.Write (PrimaryId);
  785. WriteObject (w, val.GetType ().GetElementType (), ctx);
  786. Write7BitEncodedInt (w, val.Length);
  787. for (int i = 0; i < val.Length; i++)
  788. WriteObject (w, val.GetValue (i), ctx);
  789. }
  790. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  791. {
  792. if (token == SecondaryId)
  793. return _binaryFormatter.Deserialize (r.BaseStream);
  794. Type t = (Type) ReadObject (r, ctx);
  795. int len = Read7BitEncodedInt (r);
  796. Array val = Array.CreateInstance (t, len);
  797. for (int i = 0; i < len; i++)
  798. val.SetValue (ReadObject (r, ctx), i);
  799. return val;
  800. }
  801. protected override Type Type {
  802. get { return typeof (Array); }
  803. }
  804. protected override int NumberOfIds {
  805. get { return 2; }
  806. }
  807. }
  808. class FontUnitFormatter : StringFormatter
  809. {
  810. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  811. {
  812. base.Write (w, o.ToString (), ctx);
  813. }
  814. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  815. {
  816. return FontUnit.Parse ((string) base.Read (token, r, ctx));
  817. }
  818. protected override Type Type {
  819. get { return typeof (FontUnit); }
  820. }
  821. }
  822. class UnitFormatter : StringFormatter
  823. {
  824. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  825. {
  826. base.Write (w, o.ToString (), ctx);
  827. }
  828. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  829. {
  830. return Unit.Parse ((string) base.Read (token, r, ctx));
  831. }
  832. protected override Type Type {
  833. get { return typeof (Unit); }
  834. }
  835. }
  836. class TypeConverterFormatter : StringFormatter
  837. {
  838. TypeConverter converter;
  839. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  840. {
  841. w.Write (PrimaryId);
  842. ObjectFormatter.WriteObject (w, o.GetType (), ctx);
  843. string v = (string) converter.ConvertTo (null, Helpers.InvariantCulture,
  844. o, typeof (string));
  845. base.Write (w, v, ctx);
  846. }
  847. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  848. {
  849. Type t = (Type) ObjectFormatter.ReadObject (r, ctx);
  850. converter = TypeDescriptor.GetConverter (t);
  851. token = r.ReadByte ();
  852. string v = (string) base.Read (token, r, ctx);
  853. return converter.ConvertFrom (null, Helpers.InvariantCulture, v);
  854. }
  855. protected override Type Type {
  856. get { return typeof (TypeConverter); }
  857. }
  858. public TypeConverter Converter {
  859. set { converter = value; }
  860. }
  861. }
  862. class BinaryObjectFormatter : ObjectFormatter
  863. {
  864. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  865. {
  866. w.Write (PrimaryId);
  867. MemoryStream ms = new MemoryStream (128);
  868. new BinaryFormatter ().Serialize (ms, o);
  869. byte [] buf = ms.GetBuffer ();
  870. Write7BitEncodedInt (w, buf.Length);
  871. w.Write (buf, 0, buf.Length);
  872. }
  873. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  874. {
  875. int len = Read7BitEncodedInt (r);
  876. byte [] buf = r.ReadBytes (len);
  877. if (buf.Length != len)
  878. throw new Exception ();
  879. return new BinaryFormatter ().Deserialize (new MemoryStream (buf));
  880. }
  881. protected override Type Type {
  882. get { return typeof (object); }
  883. }
  884. }
  885. #endregion
  886. #endregion
  887. }
  888. }