ObjectStateFormatter.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774
  1. //
  2. // System.Web.UI.ObjectStateFormatter
  3. //
  4. // Authors:
  5. // Ben Maurer ([email protected])
  6. //
  7. // (C) 2003 Ben Maurer
  8. //
  9. #define TRACE
  10. using System.Collections;
  11. using System.Drawing;
  12. using System.IO;
  13. using System.Reflection;
  14. using System.Runtime.Serialization.Formatters.Binary;
  15. using System.Runtime.Serialization;
  16. using System.Text;
  17. using System.Web.UI.WebControls;
  18. using System.Web.Util;
  19. using System.Diagnostics;
  20. namespace System.Web.UI {
  21. #if NET_1_2
  22. public
  23. #else
  24. internal
  25. #endif
  26. sealed class ObjectStateFormatter : IFormatter {
  27. public object Deserialize (Stream inputStream)
  28. {
  29. if (inputStream == null)
  30. throw new ArgumentNullException ("inputStream");
  31. return DeserializeObject (new BinaryReader (inputStream));
  32. }
  33. public object Deserialize (string inputString)
  34. {
  35. if (inputString == null)
  36. throw new ArgumentNullException ("inputString");
  37. if (inputString == "")
  38. return null;
  39. return Deserialize (new MemoryStream (Convert.FromBase64String (inputString)));
  40. }
  41. public string Serialize (object stateGraph)
  42. {
  43. if (stateGraph == null)
  44. return "";
  45. MemoryStream ms = new MemoryStream ();
  46. Serialize (ms, stateGraph);
  47. #if TRACE
  48. ms.WriteTo (File.OpenWrite (Path.GetTempFileName ()));
  49. #endif
  50. return Convert.ToBase64String (ms.GetBuffer (), 0, (int) ms.Length);
  51. }
  52. public void Serialize (Stream outputStream, object stateGraph)
  53. {
  54. if (outputStream == null)
  55. throw new ArgumentNullException ("outputStream");
  56. if (stateGraph == null)
  57. throw new ArgumentNullException ("stateGraph");
  58. SerializeValue (new BinaryWriter (outputStream), stateGraph);
  59. }
  60. void SerializeValue (BinaryWriter w, object o)
  61. {
  62. ObjectFormatter.WriteObject (w, o, new WriterContext ());
  63. }
  64. object DeserializeObject (BinaryReader r)
  65. {
  66. return ObjectFormatter.ReadObject (r, new ReaderContext ());
  67. }
  68. #region IFormatter
  69. object IFormatter.Deserialize (Stream serializationStream)
  70. {
  71. return Deserialize (serializationStream);
  72. }
  73. void IFormatter.Serialize (Stream serializationStream, object stateGraph)
  74. {
  75. Serialize (serializationStream, stateGraph);
  76. }
  77. SerializationBinder IFormatter.Binder {
  78. get { return null; }
  79. set { }
  80. }
  81. StreamingContext IFormatter.Context {
  82. get { return new StreamingContext (StreamingContextStates.All); }
  83. set { }
  84. }
  85. ISurrogateSelector IFormatter.SurrogateSelector {
  86. get { return null; }
  87. set { }
  88. }
  89. #endregion
  90. #region Object Readers/Writers
  91. class WriterContext {
  92. Hashtable cache;
  93. short nextKey = 0;
  94. public bool RegisterCache (object o, out short key)
  95. {
  96. if (cache == null) {
  97. cache = new Hashtable ();
  98. cache.Add (o, key = nextKey++);
  99. return false;
  100. }
  101. object posKey = cache [o];
  102. if (posKey == null) {
  103. cache.Add (o, key = nextKey++);
  104. return false;
  105. }
  106. key = (short) posKey;
  107. return true;
  108. }
  109. }
  110. class ReaderContext {
  111. ArrayList cache;
  112. public void CacheItem (object o)
  113. {
  114. if (cache == null)
  115. cache = new ArrayList ();
  116. cache.Add (o);
  117. }
  118. public object GetCache (short key)
  119. {
  120. return cache [key];
  121. }
  122. }
  123. abstract class ObjectFormatter {
  124. static readonly Hashtable writeMap = new Hashtable ();
  125. static ObjectFormatter [] readMap = new ObjectFormatter [256];
  126. static BinaryObjectFormatter binaryObjectFormatter;
  127. static TypeFormatter typeFormatter;
  128. static EnumFormatter enumFormatter;
  129. static SingleRankArrayFormatter singleRankArrayFormatter;
  130. static ObjectFormatter ()
  131. {
  132. new StringFormatter ().Register ();
  133. new Int64Formatter ().Register ();
  134. new Int32Formatter ().Register ();
  135. new Int16Formatter ().Register ();
  136. new ByteFormatter ().Register ();
  137. new BooleanFormatter ().Register ();
  138. new CharFormatter ().Register ();
  139. new DateTimeFormatter ().Register ();
  140. new PairFormatter ().Register ();
  141. new TripletFormatter ().Register ();
  142. new ArrayListFormatter ().Register ();
  143. new HashtableFormatter ().Register ();
  144. new ObjectArrayFormatter ().Register ();
  145. new ColorFormatter ().Register ();
  146. enumFormatter = new EnumFormatter ();
  147. enumFormatter.Register ();
  148. typeFormatter = new TypeFormatter ();
  149. typeFormatter.Register ();
  150. singleRankArrayFormatter = new SingleRankArrayFormatter ();
  151. singleRankArrayFormatter.Register ();
  152. binaryObjectFormatter = new BinaryObjectFormatter ();
  153. binaryObjectFormatter.Register ();
  154. }
  155. // 0 == null
  156. static byte nextId = 1;
  157. public ObjectFormatter ()
  158. {
  159. PrimaryId = nextId ++;
  160. if (NumberOfIds == 1)
  161. return;
  162. SecondaryId = nextId ++;
  163. if (NumberOfIds == 2)
  164. return;
  165. TertiaryId = nextId ++;
  166. if (NumberOfIds == 3)
  167. return;
  168. throw new Exception ();
  169. }
  170. protected readonly byte PrimaryId, SecondaryId = 255, TertiaryId = 255;
  171. protected abstract void Write (BinaryWriter w, object o, WriterContext ctx);
  172. protected abstract object Read (byte token, BinaryReader r, ReaderContext ctx);
  173. protected abstract Type Type { get; }
  174. protected virtual int NumberOfIds { get { return 1; } }
  175. public virtual void Register ()
  176. {
  177. writeMap [Type] = this;
  178. readMap [PrimaryId] = this;
  179. if (SecondaryId != 255) {
  180. readMap [SecondaryId] = this;
  181. if (TertiaryId != 255)
  182. readMap [TertiaryId] = this;
  183. }
  184. }
  185. public static void WriteObject (BinaryWriter w, object o, WriterContext ctx)
  186. {
  187. #if TRACE
  188. if (o != null) {
  189. Trace.WriteLine (String.Format ("Writing {0} (type: {1})", o, o.GetType ()));
  190. Trace.Indent ();
  191. } else {
  192. Trace.WriteLine ("Writing null");
  193. }
  194. long pos = w.BaseStream.Position;
  195. #endif
  196. if (o == null) {
  197. w.Write ((byte) 0);
  198. return;
  199. }
  200. Type t = o.GetType ();
  201. ObjectFormatter fmt = writeMap [t] as ObjectFormatter;
  202. if (fmt == null) {
  203. // Handle abstract types here
  204. if (o is Type)
  205. fmt = typeFormatter;
  206. else if (t.IsEnum)
  207. fmt = enumFormatter;
  208. else if (t.IsArray && ((Array) o).Rank == 1)
  209. fmt = singleRankArrayFormatter;
  210. else
  211. fmt = binaryObjectFormatter;
  212. }
  213. fmt.Write (w, o, ctx);
  214. #if TRACE
  215. Trace.Unindent ();
  216. Trace.WriteLine (String.Format ("Wrote {0} (type: {1}) {2} bytes", o, o.GetType (), w.BaseStream.Position - pos));
  217. #endif
  218. }
  219. public static object ReadObject (BinaryReader r, ReaderContext ctx)
  220. {
  221. byte sig = r.ReadByte ();
  222. if (sig == 0)
  223. return null;
  224. return readMap [sig].Read (sig, r, ctx);
  225. }
  226. protected void Write7BitEncodedInt (BinaryWriter w, int value)
  227. {
  228. do {
  229. int high = (value >> 7) & 0x01ffffff;
  230. byte b = (byte)(value & 0x7f);
  231. if (high != 0) {
  232. b = (byte)(b | 0x80);
  233. }
  234. w.Write(b);
  235. value = high;
  236. } while(value != 0);
  237. }
  238. protected int Read7BitEncodedInt (BinaryReader r)
  239. {
  240. int ret = 0;
  241. int shift = 0;
  242. byte b;
  243. do {
  244. b = r.ReadByte();
  245. ret = ret | ((b & 0x7f) << shift);
  246. shift += 7;
  247. } while ((b & 0x80) == 0x80);
  248. return ret;
  249. }
  250. }
  251. #region Primitive Formatters
  252. class StringFormatter : ObjectFormatter {
  253. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  254. {
  255. short key;
  256. if (ctx.RegisterCache (o, out key)) {
  257. w.Write (SecondaryId);
  258. w.Write (key);
  259. } else {
  260. w.Write (PrimaryId);
  261. w.Write ((string)o);
  262. }
  263. }
  264. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  265. {
  266. if (token == PrimaryId) {
  267. string s = r.ReadString ();
  268. ctx.CacheItem (s);
  269. return s;
  270. } else {
  271. return ctx.GetCache (r.ReadInt16 ());
  272. }
  273. }
  274. protected override Type Type {
  275. get { return typeof (string); }
  276. }
  277. protected override int NumberOfIds {
  278. get { return 2; }
  279. }
  280. }
  281. class Int64Formatter : ObjectFormatter {
  282. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  283. {
  284. w.Write (PrimaryId);
  285. w.Write ((long)o);
  286. }
  287. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  288. {
  289. return r.ReadInt64 ();
  290. }
  291. protected override Type Type {
  292. get { return typeof (long); }
  293. }
  294. }
  295. class Int32Formatter : ObjectFormatter {
  296. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  297. {
  298. int i = (int) o;
  299. if ((int)(byte) i == i) {
  300. w.Write (SecondaryId);
  301. w.Write ((byte) i);
  302. } else {
  303. w.Write (PrimaryId);
  304. w.Write (i);
  305. }
  306. }
  307. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  308. {
  309. if (token == PrimaryId)
  310. return r.ReadInt32 ();
  311. else
  312. return (int) r.ReadByte ();
  313. }
  314. protected override Type Type {
  315. get { return typeof (int); }
  316. }
  317. protected override int NumberOfIds {
  318. get { return 2; }
  319. }
  320. }
  321. class Int16Formatter : ObjectFormatter {
  322. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  323. {
  324. w.Write (PrimaryId);
  325. w.Write ((short)o);
  326. }
  327. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  328. {
  329. return r.ReadInt16 ();
  330. }
  331. protected override Type Type {
  332. get { return typeof (short); }
  333. }
  334. }
  335. class ByteFormatter : ObjectFormatter {
  336. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  337. {
  338. w.Write (PrimaryId);
  339. w.Write ((byte)o);
  340. }
  341. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  342. {
  343. return r.ReadByte ();
  344. }
  345. protected override Type Type {
  346. get { return typeof (byte); }
  347. }
  348. }
  349. class BooleanFormatter : ObjectFormatter {
  350. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  351. {
  352. if ((bool)o == true)
  353. w.Write (PrimaryId);
  354. else
  355. w.Write (SecondaryId);
  356. }
  357. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  358. {
  359. return token == PrimaryId;
  360. }
  361. protected override Type Type {
  362. get { return typeof (bool); }
  363. }
  364. protected override int NumberOfIds {
  365. get { return 2; }
  366. }
  367. }
  368. class CharFormatter : ObjectFormatter {
  369. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  370. {
  371. w.Write (PrimaryId);
  372. w.Write ((char) o);
  373. }
  374. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  375. {
  376. return r.ReadChar ();
  377. }
  378. protected override Type Type {
  379. get { return typeof (char); }
  380. }
  381. }
  382. class DateTimeFormatter : ObjectFormatter {
  383. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  384. {
  385. w.Write (PrimaryId);
  386. w.Write (((DateTime) o).Ticks);
  387. }
  388. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  389. {
  390. return new DateTime (r.ReadInt64 ());
  391. }
  392. protected override Type Type {
  393. get { return typeof (DateTime); }
  394. }
  395. }
  396. class PairFormatter : ObjectFormatter {
  397. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  398. {
  399. Pair p = (Pair) o;
  400. w.Write (PrimaryId);
  401. WriteObject (w, p.First, ctx);
  402. WriteObject (w, p.Second, ctx);
  403. }
  404. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  405. {
  406. Pair p = new Pair ();
  407. p.First = ReadObject (r, ctx);
  408. p.Second = ReadObject (r, ctx);
  409. return p;
  410. }
  411. protected override Type Type {
  412. get { return typeof (Pair); }
  413. }
  414. }
  415. class TripletFormatter : ObjectFormatter {
  416. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  417. {
  418. Triplet t = (Triplet) o;
  419. w.Write (PrimaryId);
  420. WriteObject (w, t.First, ctx);
  421. WriteObject (w, t.Second, ctx);
  422. WriteObject (w, t.Third, ctx);
  423. }
  424. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  425. {
  426. Triplet t = new Triplet ();
  427. t.First = ReadObject (r, ctx);
  428. t.Second = ReadObject (r, ctx);
  429. t.Third = ReadObject (r, ctx);
  430. return t;
  431. }
  432. protected override Type Type {
  433. get { return typeof (Triplet); }
  434. }
  435. }
  436. class ArrayListFormatter : ObjectFormatter {
  437. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  438. {
  439. ArrayList l = (ArrayList) o;
  440. w.Write (PrimaryId);
  441. Write7BitEncodedInt (w, l.Count);
  442. foreach (object i in l)
  443. WriteObject (w, i, ctx);
  444. }
  445. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  446. {
  447. int len = Read7BitEncodedInt (r);
  448. ArrayList l = new ArrayList (len);
  449. for (int i = 0; i < len; i++)
  450. l.Add (ReadObject (r, ctx));
  451. return l;
  452. }
  453. protected override Type Type {
  454. get { return typeof (ArrayList); }
  455. }
  456. }
  457. class HashtableFormatter : ObjectFormatter {
  458. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  459. {
  460. Hashtable ht = (Hashtable) o;
  461. w.Write (PrimaryId);
  462. Write7BitEncodedInt (w, ht.Count);
  463. foreach (DictionaryEntry de in ht) {
  464. WriteObject (w, de.Key, ctx);
  465. WriteObject (w, de.Value, ctx);
  466. }
  467. }
  468. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  469. {
  470. int len = Read7BitEncodedInt (r);
  471. Hashtable ht = new Hashtable (len);
  472. for (int i = 0; i < len; i++) {
  473. object key = ReadObject (r, ctx);
  474. object val = ReadObject (r, ctx);
  475. ht.Add (key, val);
  476. }
  477. return ht;
  478. }
  479. protected override Type Type {
  480. get { return typeof (Hashtable); }
  481. }
  482. }
  483. class ObjectArrayFormatter : ObjectFormatter {
  484. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  485. {
  486. object [] val = (object []) o;
  487. w.Write (PrimaryId);
  488. Write7BitEncodedInt (w, val.Length);
  489. foreach (object i in val)
  490. WriteObject (w, i, ctx);
  491. }
  492. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  493. {
  494. int len = Read7BitEncodedInt (r);
  495. object [] ret = new object [len];
  496. for (int i = 0; i < len; i++)
  497. ret [i] = ReadObject (r, ctx);
  498. return ret;
  499. }
  500. protected override Type Type {
  501. get { return typeof (object []); }
  502. }
  503. }
  504. #endregion
  505. #region System.Web Optimizations
  506. class ColorFormatter : ObjectFormatter {
  507. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  508. {
  509. Color c = (Color) o;
  510. if (!c.IsKnownColor) {
  511. w.Write (PrimaryId);
  512. w.Write (c.ToArgb ());
  513. } else {
  514. w.Write (SecondaryId);
  515. w.Write ((int) c.ToKnownColor ());
  516. }
  517. }
  518. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  519. {
  520. if (token == PrimaryId)
  521. return Color.FromArgb (r.ReadInt32 ());
  522. else
  523. return Color.FromKnownColor ((KnownColor) r.ReadInt32 ());
  524. }
  525. protected override Type Type {
  526. get { return typeof (Color); }
  527. }
  528. protected override int NumberOfIds {
  529. get { return 2; }
  530. }
  531. }
  532. #endregion
  533. #region Special Formatters
  534. class EnumFormatter : ObjectFormatter {
  535. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  536. {
  537. object value = Convert.ChangeType (o, ((Enum) o).GetTypeCode ());
  538. w.Write (PrimaryId);
  539. WriteObject (w, o.GetType (), ctx);
  540. WriteObject (w, value, ctx);
  541. }
  542. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  543. {
  544. Type t = (Type) ReadObject (r, ctx);
  545. object value = ReadObject (r, ctx);
  546. return Enum.ToObject (t, value);
  547. }
  548. protected override Type Type {
  549. get { return typeof (Enum); }
  550. }
  551. }
  552. class TypeFormatter : ObjectFormatter {
  553. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  554. {
  555. short key;
  556. if (ctx.RegisterCache (o, out key)) {
  557. w.Write (SecondaryId);
  558. w.Write (key);
  559. } else {
  560. w.Write (PrimaryId);
  561. w.Write (((Type) o).FullName);
  562. // We should cache the name of the assembly
  563. w.Write (((Type) o).Assembly.FullName);
  564. }
  565. }
  566. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  567. {
  568. if (token == PrimaryId) {
  569. string type = r.ReadString ();
  570. string assembly = r.ReadString ();
  571. Type t = Assembly.Load (assembly).GetType (type);
  572. ctx.CacheItem (t);
  573. return t;
  574. } else {
  575. return ctx.GetCache (r.ReadInt16 ());
  576. }
  577. }
  578. protected override Type Type {
  579. get { return typeof (Type); }
  580. }
  581. protected override int NumberOfIds {
  582. get { return 2; }
  583. }
  584. }
  585. class SingleRankArrayFormatter : ObjectFormatter {
  586. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  587. {
  588. Array val = (Array) o;
  589. w.Write (PrimaryId);
  590. WriteObject (w, val.GetType ().GetElementType (), ctx);
  591. Write7BitEncodedInt (w, val.Length);
  592. foreach (object i in val)
  593. WriteObject (w, i, ctx);
  594. }
  595. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  596. {
  597. Type t = (Type) ReadObject (r, ctx);
  598. int len = Read7BitEncodedInt (r);
  599. Array val = Array.CreateInstance (t, len);
  600. for (int i = 0; i < len; i++)
  601. val.SetValue (ReadObject (r, ctx), i);
  602. return val;
  603. }
  604. protected override Type Type {
  605. get { return typeof (Array); }
  606. }
  607. }
  608. class BinaryObjectFormatter : ObjectFormatter {
  609. protected override void Write (BinaryWriter w, object o, WriterContext ctx)
  610. {
  611. w.Write (PrimaryId);
  612. MemoryStream ms = new MemoryStream (128);
  613. new BinaryFormatter ().Serialize (ms, o);
  614. byte [] buf = ms.GetBuffer ();
  615. Write7BitEncodedInt (w, buf.Length);
  616. w.Write (buf, 0, buf.Length);
  617. }
  618. protected override object Read (byte token, BinaryReader r, ReaderContext ctx)
  619. {
  620. int len = Read7BitEncodedInt (r);
  621. byte [] buf = r.ReadBytes (len);
  622. if (buf.Length != len)
  623. throw new Exception ();
  624. return new BinaryFormatter ().Deserialize (new MemoryStream (buf));
  625. }
  626. protected override Type Type {
  627. get { return typeof (object); }
  628. }
  629. }
  630. #endregion
  631. #endregion
  632. }
  633. }