ObjectStateFormatter.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014
  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 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. internal 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. if (algo != null)
  87. return algo;
  88. if (!EnableMac)
  89. return null;
  90. byte [] algoKey;
  91. if (page != null) {
  92. #if NET_2_0
  93. MachineKeySection mconfig = (MachineKeySection) WebConfigurationManager.GetSection ("system.web/machineKey");
  94. algoKey = mconfig.ValidationKeyBytes;
  95. #else
  96. MachineKeyConfig mconfig = HttpContext.GetAppConfig ("system.web/machineKey") as MachineKeyConfig;
  97. algoKey = mconfig.ValidationKey;
  98. #endif
  99. } else
  100. algoKey = vkey;
  101. return new HMACSHA1 (algoKey);
  102. }
  103. static int ValidateInput (HashAlgorithm algo, byte [] data, int offset, int size)
  104. {
  105. if (algo == null)
  106. throw new HttpException ("Unable to validate data.");
  107. int hash_size = algo.HashSize / 8;
  108. if (size != 0 && size < hash_size)
  109. throw new HttpException ("Unable to validate data.");
  110. int data_length = size - hash_size;
  111. MemoryStream data_stream = new MemoryStream (data, offset, data_length, false, false);
  112. byte [] hash = algo.ComputeHash (data_stream);
  113. for (int i = 0; i < hash_size; i++) {
  114. if (hash [i] != data [data_length + i])
  115. throw new HttpException ("Unable to validate data.");
  116. }
  117. return data_length;
  118. }
  119. public object Deserialize (Stream inputStream)
  120. {
  121. if (inputStream == null)
  122. throw new ArgumentNullException ("inputStream");
  123. return DeserializeObject (new BinaryReader (inputStream));
  124. }
  125. public object Deserialize (string inputString)
  126. {
  127. if (inputString == null)
  128. throw new ArgumentNullException ("inputString");
  129. #if NET_2_0
  130. if (inputString.Length == 0)
  131. throw new ArgumentNullException ("inputString");
  132. #else
  133. if (inputString == "")
  134. return "";
  135. #endif
  136. byte [] buffer = Convert.FromBase64String (inputString);
  137. int length;
  138. if (buffer == null || (length = buffer.Length) == 0)
  139. throw new ArgumentNullException ("inputString");
  140. if (page != null && EnableMac)
  141. length = ValidateInput (GetAlgo (), buffer, 0, length);
  142. #if NET_2_0
  143. bool isEncrypted = ((int)buffer [--length] == 1)? true : false;
  144. #endif
  145. Stream ms = new MemoryStream (buffer, 0, length, false, false);
  146. #if NET_2_0
  147. if (isEncrypted) {
  148. ms = new CryptoStream (ms, page.GetCryptoTransform (CryptoStreamMode.Read), CryptoStreamMode.Read);
  149. }
  150. #endif
  151. return Deserialize (ms);
  152. }
  153. public string Serialize (object stateGraph)
  154. {
  155. if (stateGraph == null)
  156. return "";
  157. MemoryStream ms = new MemoryStream ();
  158. Stream output = ms;
  159. #if NET_2_0
  160. bool needEncryption = page == null ? false : page.NeedViewStateEncryption;
  161. if (needEncryption){
  162. output = new CryptoStream (output, page.GetCryptoTransform (CryptoStreamMode.Write), CryptoStreamMode.Write);
  163. }
  164. #endif
  165. Serialize (output, stateGraph);
  166. #if NET_2_0
  167. ms.WriteByte((byte)(needEncryption? 1 : 0));
  168. #endif
  169. #if TRACE
  170. ms.WriteTo (File.OpenWrite (Path.GetTempFileName ()));
  171. #endif
  172. if (EnableMac && ms.Length > 0) {
  173. HashAlgorithm algo = GetAlgo ();
  174. if (algo != null) {
  175. byte [] hash = algo.ComputeHash (ms.GetBuffer (), 0, (int) ms.Length);
  176. ms.Write (hash, 0, hash.Length);
  177. }
  178. }
  179. return Convert.ToBase64String (ms.GetBuffer (), 0, (int) ms.Length);
  180. }
  181. public void Serialize (Stream outputStream, object stateGraph)
  182. {
  183. if (outputStream == null)
  184. throw new ArgumentNullException ("outputStream");
  185. if (stateGraph == null)
  186. throw new ArgumentNullException ("stateGraph");
  187. SerializeValue (new BinaryWriter (outputStream), stateGraph);
  188. }
  189. void SerializeValue (BinaryWriter w, object o)
  190. {
  191. ObjectFormatter.WriteObject (w, o, new WriterContext ());
  192. }
  193. object DeserializeObject (BinaryReader r)
  194. {
  195. return ObjectFormatter.ReadObject (r, new ReaderContext ());
  196. }
  197. #region IFormatter
  198. object IFormatter.Deserialize (Stream serializationStream)
  199. {
  200. return Deserialize (serializationStream);
  201. }
  202. void IFormatter.Serialize (Stream serializationStream, object stateGraph)
  203. {
  204. Serialize (serializationStream, stateGraph);
  205. }
  206. SerializationBinder IFormatter.Binder {
  207. get { return null; }
  208. set { }
  209. }
  210. StreamingContext IFormatter.Context {
  211. get { return new StreamingContext (StreamingContextStates.All); }
  212. set { }
  213. }
  214. ISurrogateSelector IFormatter.SurrogateSelector {
  215. get { return null; }
  216. set { }
  217. }
  218. #endregion
  219. #region Object Readers/Writers
  220. class WriterContext {
  221. Hashtable cache;
  222. short nextKey = 0;
  223. public bool RegisterCache (object o, out short key)
  224. {
  225. if (cache == null) {
  226. cache = new Hashtable ();
  227. cache.Add (o, key = nextKey++);
  228. return false;
  229. }
  230. object posKey = cache [o];
  231. if (posKey == null) {
  232. cache.Add (o, key = nextKey++);
  233. return false;
  234. }
  235. key = (short) posKey;
  236. return true;
  237. }
  238. }
  239. class ReaderContext {
  240. ArrayList cache;
  241. public void CacheItem (object o)
  242. {
  243. if (cache == null)
  244. cache = new ArrayList ();
  245. cache.Add (o);
  246. }
  247. public object GetCache (short key)
  248. {
  249. return cache [key];
  250. }
  251. }
  252. abstract class ObjectFormatter {
  253. static readonly Hashtable writeMap = new Hashtable ();
  254. static ObjectFormatter [] readMap = new ObjectFormatter [256];
  255. static BinaryObjectFormatter binaryObjectFormatter;
  256. static TypeFormatter typeFormatter;
  257. static EnumFormatter enumFormatter;
  258. static SingleRankArrayFormatter singleRankArrayFormatter;
  259. static TypeConverterFormatter typeConverterFormatter;
  260. static ObjectFormatter ()
  261. {
  262. new StringFormatter ().Register ();
  263. new Int64Formatter ().Register ();
  264. new Int32Formatter ().Register ();
  265. new Int16Formatter ().Register ();
  266. new ByteFormatter ().Register ();
  267. new BooleanFormatter ().Register ();
  268. new CharFormatter ().Register ();
  269. new DateTimeFormatter ().Register ();
  270. new PairFormatter ().Register ();
  271. new TripletFormatter ().Register ();
  272. new ArrayListFormatter ().Register ();
  273. new HashtableFormatter ().Register ();
  274. new ObjectArrayFormatter ().Register ();
  275. new UnitFormatter ().Register ();
  276. new FontUnitFormatter ().Register ();
  277. new ColorFormatter ().Register ();
  278. enumFormatter = new EnumFormatter ();
  279. enumFormatter.Register ();
  280. typeFormatter = new TypeFormatter ();
  281. typeFormatter.Register ();
  282. singleRankArrayFormatter = new SingleRankArrayFormatter ();
  283. singleRankArrayFormatter.Register ();
  284. typeConverterFormatter = new TypeConverterFormatter ();
  285. typeConverterFormatter.Register ();
  286. binaryObjectFormatter = new BinaryObjectFormatter ();
  287. binaryObjectFormatter.Register ();
  288. }
  289. // 0 == null
  290. static byte nextId = 1;
  291. public ObjectFormatter ()
  292. {
  293. PrimaryId = nextId ++;
  294. if (NumberOfIds == 1)
  295. return;
  296. SecondaryId = nextId ++;
  297. if (NumberOfIds == 2)
  298. return;
  299. TertiaryId = nextId ++;
  300. if (NumberOfIds == 3)
  301. return;
  302. throw new Exception ();
  303. }
  304. protected readonly byte PrimaryId, SecondaryId = 255, TertiaryId = 255;
  305. protected abstract void Write (BinaryWriter w, object o, WriterContext ctx);
  306. protected abstract object Read (byte token, BinaryReader r, ReaderContext ctx);
  307. protected abstract Type Type { get; }
  308. protected virtual int NumberOfIds { get { return 1; } }
  309. public virtual void Register ()
  310. {
  311. writeMap [Type] = this;
  312. readMap [PrimaryId] = this;
  313. if (SecondaryId != 255) {
  314. readMap [SecondaryId] = this;
  315. if (TertiaryId != 255)
  316. readMap [TertiaryId] = this;
  317. }
  318. }
  319. public static void WriteObject (BinaryWriter w, object o, WriterContext ctx)
  320. {
  321. #if TRACE
  322. if (o != null) {
  323. Trace.WriteLine (String.Format ("Writing {0} (type: {1})", o, o.GetType ()));
  324. Trace.Indent ();
  325. } else {
  326. Trace.WriteLine ("Writing null");
  327. }
  328. long pos = w.BaseStream.Position;
  329. #endif
  330. if (o == null) {
  331. w.Write ((byte) 0);
  332. return;
  333. }
  334. Type t = o.GetType ();
  335. ObjectFormatter fmt = writeMap [t] as ObjectFormatter;
  336. if (fmt == null) {
  337. // Handle abstract types here
  338. if (o is Type)
  339. fmt = typeFormatter;
  340. else if (t.IsEnum)
  341. fmt = enumFormatter;
  342. else if (t.IsArray && ((Array) o).Rank == 1)
  343. fmt = singleRankArrayFormatter;
  344. else {
  345. TypeConverter converter;
  346. converter = TypeDescriptor.GetConverter (o);
  347. if (converter == null ||
  348. !converter.CanConvertTo (typeof (string)) ||
  349. !converter.CanConvertFrom (typeof (string))) {
  350. fmt = binaryObjectFormatter;
  351. } else {
  352. typeConverterFormatter.Converter = converter;
  353. fmt = typeConverterFormatter;
  354. }
  355. }
  356. }
  357. fmt.Write (w, o, ctx);
  358. #if TRACE
  359. Trace.Unindent ();
  360. Trace.WriteLine (String.Format ("Wrote {0} (type: {1}) {2} bytes", o, o.GetType (), w.BaseStream.Position - pos));
  361. #endif
  362. }
  363. public static object ReadObject (BinaryReader r, ReaderContext ctx)
  364. {
  365. byte sig = r.ReadByte ();
  366. if (sig == 0)
  367. return null;
  368. return readMap [sig].Read (sig, r, ctx);
  369. }
  370. protected void Write7BitEncodedInt (BinaryWriter w, int value)
  371. {
  372. do {
  373. int high = (value >> 7) & 0x01ffffff;
  374. byte b = (byte)(value & 0x7f);
  375. if (high != 0) {
  376. b = (byte)(b | 0x80);
  377. }
  378. w.Write(b);
  379. value = high;
  380. } while(value != 0);
  381. }
  382. protected int Read7BitEncodedInt (BinaryReader r)
  383. {
  384. int ret = 0;
  385. int shift = 0;
  386. byte b;
  387. do {
  388. b = r.ReadByte();
  389. ret = ret | ((b & 0x7f) << shift);
  390. shift += 7;
  391. } while ((b & 0x80) == 0x80);
  392. return ret;
  393. }
  394. }
  395. #region Primitive Formatters
  396. class StringFormatter : ObjectFormatter {
  397. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  398. {
  399. short key;
  400. if (ctx.RegisterCache (o, out key)) {
  401. w.Write (SecondaryId);
  402. w.Write (key);
  403. } else {
  404. w.Write (PrimaryId);
  405. w.Write ((string)o);
  406. }
  407. }
  408. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  409. {
  410. if (token == PrimaryId) {
  411. string s = r.ReadString ();
  412. ctx.CacheItem (s);
  413. return s;
  414. } else {
  415. return ctx.GetCache (r.ReadInt16 ());
  416. }
  417. }
  418. protected override Type Type {
  419. get { return typeof (string); }
  420. }
  421. protected override int NumberOfIds {
  422. get { return 2; }
  423. }
  424. }
  425. class Int64Formatter : ObjectFormatter {
  426. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  427. {
  428. w.Write (PrimaryId);
  429. w.Write ((long)o);
  430. }
  431. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  432. {
  433. return r.ReadInt64 ();
  434. }
  435. protected override Type Type {
  436. get { return typeof (long); }
  437. }
  438. }
  439. class Int32Formatter : ObjectFormatter {
  440. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  441. {
  442. int i = (int) o;
  443. if ((int)(byte) i == i) {
  444. w.Write (SecondaryId);
  445. w.Write ((byte) i);
  446. } else {
  447. w.Write (PrimaryId);
  448. w.Write (i);
  449. }
  450. }
  451. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  452. {
  453. if (token == PrimaryId)
  454. return r.ReadInt32 ();
  455. else
  456. return (int) r.ReadByte ();
  457. }
  458. protected override Type Type {
  459. get { return typeof (int); }
  460. }
  461. protected override int NumberOfIds {
  462. get { return 2; }
  463. }
  464. }
  465. class Int16Formatter : ObjectFormatter {
  466. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  467. {
  468. w.Write (PrimaryId);
  469. w.Write ((short)o);
  470. }
  471. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  472. {
  473. return r.ReadInt16 ();
  474. }
  475. protected override Type Type {
  476. get { return typeof (short); }
  477. }
  478. }
  479. class ByteFormatter : ObjectFormatter {
  480. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  481. {
  482. w.Write (PrimaryId);
  483. w.Write ((byte)o);
  484. }
  485. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  486. {
  487. return r.ReadByte ();
  488. }
  489. protected override Type Type {
  490. get { return typeof (byte); }
  491. }
  492. }
  493. class BooleanFormatter : ObjectFormatter {
  494. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  495. {
  496. if ((bool)o == true)
  497. w.Write (PrimaryId);
  498. else
  499. w.Write (SecondaryId);
  500. }
  501. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  502. {
  503. return token == PrimaryId;
  504. }
  505. protected override Type Type {
  506. get { return typeof (bool); }
  507. }
  508. protected override int NumberOfIds {
  509. get { return 2; }
  510. }
  511. }
  512. class CharFormatter : ObjectFormatter {
  513. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  514. {
  515. w.Write (PrimaryId);
  516. w.Write ((char) o);
  517. }
  518. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  519. {
  520. return r.ReadChar ();
  521. }
  522. protected override Type Type {
  523. get { return typeof (char); }
  524. }
  525. }
  526. class DateTimeFormatter : ObjectFormatter {
  527. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  528. {
  529. w.Write (PrimaryId);
  530. w.Write (((DateTime) o).Ticks);
  531. }
  532. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  533. {
  534. return new DateTime (r.ReadInt64 ());
  535. }
  536. protected override Type Type {
  537. get { return typeof (DateTime); }
  538. }
  539. }
  540. class PairFormatter : ObjectFormatter {
  541. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  542. {
  543. Pair p = (Pair) o;
  544. w.Write (PrimaryId);
  545. WriteObject (w, p.First, ctx);
  546. WriteObject (w, p.Second, ctx);
  547. }
  548. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  549. {
  550. Pair p = new Pair ();
  551. p.First = ReadObject (r, ctx);
  552. p.Second = ReadObject (r, ctx);
  553. return p;
  554. }
  555. protected override Type Type {
  556. get { return typeof (Pair); }
  557. }
  558. }
  559. class TripletFormatter : ObjectFormatter {
  560. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  561. {
  562. Triplet t = (Triplet) o;
  563. w.Write (PrimaryId);
  564. WriteObject (w, t.First, ctx);
  565. WriteObject (w, t.Second, ctx);
  566. WriteObject (w, t.Third, ctx);
  567. }
  568. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  569. {
  570. Triplet t = new Triplet ();
  571. t.First = ReadObject (r, ctx);
  572. t.Second = ReadObject (r, ctx);
  573. t.Third = ReadObject (r, ctx);
  574. return t;
  575. }
  576. protected override Type Type {
  577. get { return typeof (Triplet); }
  578. }
  579. }
  580. class ArrayListFormatter : ObjectFormatter {
  581. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  582. {
  583. ArrayList l = (ArrayList) o;
  584. w.Write (PrimaryId);
  585. Write7BitEncodedInt (w, l.Count);
  586. foreach (object i in l)
  587. WriteObject (w, i, ctx);
  588. }
  589. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  590. {
  591. int len = Read7BitEncodedInt (r);
  592. ArrayList l = new ArrayList (len);
  593. for (int i = 0; i < len; i++)
  594. l.Add (ReadObject (r, ctx));
  595. return l;
  596. }
  597. protected override Type Type {
  598. get { return typeof (ArrayList); }
  599. }
  600. }
  601. class HashtableFormatter : ObjectFormatter {
  602. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  603. {
  604. Hashtable ht = (Hashtable) o;
  605. w.Write (PrimaryId);
  606. Write7BitEncodedInt (w, ht.Count);
  607. foreach (DictionaryEntry de in ht) {
  608. WriteObject (w, de.Key, ctx);
  609. WriteObject (w, de.Value, ctx);
  610. }
  611. }
  612. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  613. {
  614. int len = Read7BitEncodedInt (r);
  615. Hashtable ht = new Hashtable (len);
  616. for (int i = 0; i < len; i++) {
  617. object key = ReadObject (r, ctx);
  618. object val = ReadObject (r, ctx);
  619. ht.Add (key, val);
  620. }
  621. return ht;
  622. }
  623. protected override Type Type {
  624. get { return typeof (Hashtable); }
  625. }
  626. }
  627. class ObjectArrayFormatter : ObjectFormatter {
  628. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  629. {
  630. object [] val = (object []) o;
  631. w.Write (PrimaryId);
  632. Write7BitEncodedInt (w, val.Length);
  633. foreach (object i in val)
  634. WriteObject (w, i, ctx);
  635. }
  636. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  637. {
  638. int len = Read7BitEncodedInt (r);
  639. object [] ret = new object [len];
  640. for (int i = 0; i < len; i++)
  641. ret [i] = ReadObject (r, ctx);
  642. return ret;
  643. }
  644. protected override Type Type {
  645. get { return typeof (object []); }
  646. }
  647. }
  648. #endregion
  649. #region System.Web Optimizations
  650. class ColorFormatter : ObjectFormatter {
  651. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  652. {
  653. Color c = (Color) o;
  654. if (c.IsEmpty || c.IsKnownColor) {
  655. w.Write (SecondaryId);
  656. if (c.IsEmpty)
  657. w.Write (-1); //isempty marker
  658. else
  659. w.Write ((int) c.ToKnownColor ());
  660. }
  661. else {
  662. w.Write (PrimaryId);
  663. w.Write (c.ToArgb ());
  664. }
  665. }
  666. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  667. {
  668. int value = r.ReadInt32 ();
  669. if (token == PrimaryId)
  670. return Color.FromArgb (value);
  671. else {
  672. if (value == -1) //isempty marker
  673. return Color.Empty;
  674. return Color.FromKnownColor ((KnownColor)value);
  675. }
  676. }
  677. protected override Type Type {
  678. get { return typeof (Color); }
  679. }
  680. protected override int NumberOfIds {
  681. get { return 2; }
  682. }
  683. }
  684. #endregion
  685. #region Special Formatters
  686. class EnumFormatter : ObjectFormatter {
  687. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  688. {
  689. object value = Convert.ChangeType (o, ((Enum) o).GetTypeCode ());
  690. w.Write (PrimaryId);
  691. WriteObject (w, o.GetType (), ctx);
  692. WriteObject (w, value, ctx);
  693. }
  694. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  695. {
  696. Type t = (Type) ReadObject (r, ctx);
  697. object value = ReadObject (r, ctx);
  698. return Enum.ToObject (t, value);
  699. }
  700. protected override Type Type {
  701. get { return typeof (Enum); }
  702. }
  703. }
  704. class TypeFormatter : ObjectFormatter {
  705. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  706. {
  707. short key;
  708. if (ctx.RegisterCache (o, out key)) {
  709. w.Write (SecondaryId);
  710. w.Write (key);
  711. } else {
  712. w.Write (PrimaryId);
  713. w.Write (((Type) o).FullName);
  714. // We should cache the name of the assembly
  715. w.Write (((Type) o).Assembly.FullName);
  716. }
  717. }
  718. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  719. {
  720. if (token == PrimaryId) {
  721. string type = r.ReadString ();
  722. string assembly = r.ReadString ();
  723. Type t = Assembly.Load (assembly).GetType (type);
  724. ctx.CacheItem (t);
  725. return t;
  726. } else {
  727. return ctx.GetCache (r.ReadInt16 ());
  728. }
  729. }
  730. protected override Type Type {
  731. get { return typeof (Type); }
  732. }
  733. protected override int NumberOfIds {
  734. get { return 2; }
  735. }
  736. }
  737. class SingleRankArrayFormatter : ObjectFormatter {
  738. readonly BinaryFormatter _binaryFormatter = new BinaryFormatter ();
  739. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  740. {
  741. Array val = (Array) o;
  742. if (val.GetType ().GetElementType ().IsPrimitive) {
  743. w.Write (SecondaryId);
  744. _binaryFormatter.Serialize (w.BaseStream, o);
  745. return;
  746. }
  747. w.Write (PrimaryId);
  748. WriteObject (w, val.GetType ().GetElementType (), ctx);
  749. Write7BitEncodedInt (w, val.Length);
  750. foreach (object i in val)
  751. WriteObject (w, i, ctx);
  752. }
  753. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  754. {
  755. if (token == SecondaryId) {
  756. return _binaryFormatter.Deserialize (r.BaseStream);
  757. }
  758. Type t = (Type) ReadObject (r, ctx);
  759. int len = Read7BitEncodedInt (r);
  760. Array val = Array.CreateInstance (t, len);
  761. for (int i = 0; i < len; i++)
  762. val.SetValue (ReadObject (r, ctx), i);
  763. return val;
  764. }
  765. protected override Type Type {
  766. get { return typeof (Array); }
  767. }
  768. protected override int NumberOfIds {
  769. get { return 2; }
  770. }
  771. }
  772. class FontUnitFormatter : StringFormatter {
  773. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  774. {
  775. base.Write (w, o.ToString (), ctx);
  776. }
  777. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  778. {
  779. return FontUnit.Parse ((string) base.Read (token, r, ctx));
  780. }
  781. protected override Type Type {
  782. get { return typeof (FontUnit); }
  783. }
  784. }
  785. class UnitFormatter : StringFormatter {
  786. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  787. {
  788. base.Write (w, o.ToString (), ctx);
  789. }
  790. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  791. {
  792. return Unit.Parse ((string) base.Read (token, r, ctx));
  793. }
  794. protected override Type Type {
  795. get { return typeof (Unit); }
  796. }
  797. }
  798. class TypeConverterFormatter : StringFormatter {
  799. TypeConverter converter;
  800. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  801. {
  802. w.Write (PrimaryId);
  803. ObjectFormatter.WriteObject (w, o.GetType (), ctx);
  804. string v = (string) converter.ConvertTo (null, CultureInfo.InvariantCulture,
  805. o, typeof (string));
  806. base.Write (w, v, ctx);
  807. }
  808. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  809. {
  810. Type t = (Type) ObjectFormatter.ReadObject (r, ctx);
  811. converter = TypeDescriptor.GetConverter (t);
  812. token = r.ReadByte ();
  813. string v = (string) base.Read (token, r, ctx);
  814. return converter.ConvertFrom (null, CultureInfo.InvariantCulture, v);
  815. }
  816. protected override Type Type {
  817. get { return typeof (TypeConverter); }
  818. }
  819. public TypeConverter Converter {
  820. set { converter = value; }
  821. }
  822. }
  823. class BinaryObjectFormatter : ObjectFormatter {
  824. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  825. {
  826. w.Write (PrimaryId);
  827. MemoryStream ms = new MemoryStream (128);
  828. new BinaryFormatter ().Serialize (ms, o);
  829. byte [] buf = ms.GetBuffer ();
  830. Write7BitEncodedInt (w, buf.Length);
  831. w.Write (buf, 0, buf.Length);
  832. }
  833. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  834. {
  835. int len = Read7BitEncodedInt (r);
  836. byte [] buf = r.ReadBytes (len);
  837. if (buf.Length != len)
  838. throw new Exception ();
  839. return new BinaryFormatter ().Deserialize (new MemoryStream (buf));
  840. }
  841. protected override Type Type {
  842. get { return typeof (object); }
  843. }
  844. }
  845. #endregion
  846. #endregion
  847. }
  848. }