LosFormatter.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. //
  2. // System.Web.UI.LosFormatter
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002 Ximian, Inc (http://www.ximian.com)
  8. //
  9. using System;
  10. using System.Collections;
  11. using System.Drawing;
  12. using System.IO;
  13. using System.Runtime.Serialization.Formatters.Binary;
  14. using System.Text;
  15. using System.Web.UI;
  16. using System.Web.UI.WebControls;
  17. using System.Web.Util;
  18. namespace System.Web.UI
  19. {
  20. public sealed class LosFormatter
  21. {
  22. delegate void WriteObject (LosFormatter formatter, TextWriter writer, object value);
  23. static char [] specialChars = new char [] {'<', '>', ';'};
  24. const char booleanID = 'o';
  25. const char stringID = 's';
  26. const char charID = 'c';
  27. const char int16ID = 'i';
  28. const char int32ID = 'I';
  29. const char int64ID = 'l';
  30. const char colorID = 'C';
  31. const char pairID = 'p';
  32. const char tripletID = 't';
  33. const char arrayListID = 'L';
  34. const char hashtableID = 'h';
  35. const char binaryID = 'b';
  36. const char arrayID = 'a';
  37. const char dateTimeID = 'd';
  38. const char unitID = 'u';
  39. const char fontUnitID = 'f';
  40. static Hashtable specialTypes;
  41. static Hashtable idToType;
  42. static LosFormatter ()
  43. {
  44. specialTypes = new Hashtable ();
  45. specialTypes.Add (typeof (Boolean), new WriteObject (WriteBoolean));
  46. specialTypes.Add (typeof (Pair), new WriteObject (WritePair));
  47. specialTypes.Add (typeof (Triplet), new WriteObject (WriteTriplet));
  48. specialTypes.Add (typeof (Color), new WriteObject (WriteColor));
  49. specialTypes.Add (typeof (ArrayList), new WriteObject (WriteArrayList));
  50. specialTypes.Add (typeof (Hashtable), new WriteObject (WriteHashtable));
  51. specialTypes.Add (typeof (Array), new WriteObject (WriteArray));
  52. specialTypes.Add (typeof (DateTime), new WriteObject (WriteDateTime));
  53. specialTypes.Add (typeof (Unit), new WriteObject (WriteUnit));
  54. specialTypes.Add (typeof (FontUnit), new WriteObject (WriteFontUnit));
  55. idToType = new Hashtable ();
  56. idToType.Add (typeof (string), stringID);
  57. idToType.Add (typeof (char), charID);
  58. idToType.Add (typeof (Int16), int16ID);
  59. idToType.Add (typeof (Int32), int32ID);
  60. idToType.Add (typeof (Int64), int64ID);
  61. idToType.Add (typeof (Boolean), booleanID);
  62. idToType.Add (typeof (Pair), pairID);
  63. idToType.Add (typeof (Triplet), tripletID);
  64. idToType.Add (typeof (Color), colorID);
  65. idToType.Add (typeof (ArrayList), arrayListID);
  66. idToType.Add (typeof (Hashtable), hashtableID);
  67. idToType.Add (typeof (Array), arrayID);
  68. idToType.Add (typeof (Unit), unitID);
  69. idToType.Add (typeof (FontUnit), fontUnitID);
  70. }
  71. public object Deserialize (Stream stream)
  72. {
  73. if (stream == null)
  74. throw new ArgumentNullException ("stream");
  75. return Deserialize (new StreamReader (stream));
  76. }
  77. public object Deserialize (TextReader input)
  78. {
  79. if (input == null)
  80. throw new ArgumentNullException ("input");
  81. return Deserialize (input.ReadToEnd ());
  82. }
  83. public object Deserialize (string input)
  84. {
  85. if (input == null)
  86. throw new ArgumentNullException ("input");
  87. string real_input = WebEncoding.Encoding.GetString (Convert.FromBase64String (input));
  88. return DeserializeObject (real_input);
  89. }
  90. private static string UnEscapeSpecialChars (string str)
  91. {
  92. if (str.IndexOf ('\\') == -1)
  93. return str;
  94. string result = str.Replace ("\\;", ";");
  95. result = result.Replace ("\\>", ">");
  96. result = result.Replace ("\\<", "<");
  97. result = result.Replace ("\\\\", "\\");
  98. return result;
  99. }
  100. private static string GetEnclosedString (string input)
  101. {
  102. if (input [0] != '<')
  103. throw new ArgumentException (input);
  104. int count = 1;
  105. bool escaped = false;
  106. StringBuilder result = new StringBuilder ();
  107. for (int i = 1; count != 0 && i < input.Length; i++) {
  108. char c = input [i];
  109. if (escaped)
  110. escaped = false;
  111. else if (c == '\\')
  112. escaped = true;
  113. else if (c == '<')
  114. count++;
  115. else if (c == '>')
  116. count--;
  117. result.Append (c);
  118. }
  119. result.Length--;
  120. return result.ToString ();
  121. }
  122. private static string [] GetStringValues (string input)
  123. {
  124. if (input == null || input.Length == 0)
  125. return new string [0];
  126. int length = input.Length;
  127. bool escaped = false;
  128. int opened = 0;
  129. ArrayList list = new ArrayList ();
  130. StringBuilder builder = new StringBuilder ();
  131. for (int i = 0; i < length; i++) {
  132. char c = input [i];
  133. if (escaped)
  134. escaped = false;
  135. else if (c == '\\')
  136. escaped = true;
  137. else if (c == '<')
  138. opened++;
  139. else if (c == '>')
  140. opened--;
  141. else if (c == ';' && opened == 0) {
  142. list.Add (builder.ToString ());
  143. builder = new StringBuilder ();
  144. continue;
  145. }
  146. builder.Append (c);
  147. }
  148. list.Add (builder.ToString ());
  149. string [] result = new string [list.Count];
  150. list.CopyTo (result, 0);
  151. return result;
  152. }
  153. private object DeserializeObject (string input)
  154. {
  155. if (input == null || input.Length < 2)
  156. return null;
  157. object obj;
  158. string enclosed = GetEnclosedString (input.Substring (1));
  159. string [] splitted;
  160. switch (input [0]) {
  161. case booleanID:
  162. obj = enclosed.Length == 1;
  163. break;
  164. case stringID:
  165. obj = UnEscapeSpecialChars (enclosed);
  166. break;
  167. case int16ID:
  168. obj = Int16.Parse (enclosed);
  169. break;
  170. case int32ID:
  171. obj = Int32.Parse (enclosed);
  172. break;
  173. case int64ID:
  174. obj = Int64.Parse (enclosed);
  175. break;
  176. case colorID:
  177. obj = Color.FromArgb (Int32.Parse (enclosed));
  178. break;
  179. case pairID:
  180. Pair pair = new Pair ();
  181. obj = pair;
  182. splitted = GetStringValues (enclosed);
  183. if (splitted.Length > 0) {
  184. pair.First = DeserializeObject (splitted [0]);
  185. if (splitted.Length > 1)
  186. pair.Second = DeserializeObject (splitted [1]);
  187. }
  188. break;
  189. case tripletID:
  190. Triplet triplet = new Triplet ();
  191. obj = triplet;
  192. splitted = GetStringValues (enclosed);
  193. if (splitted.Length == 0)
  194. break;
  195. triplet.First = DeserializeObject (splitted [0]);
  196. if (splitted.Length < 1)
  197. break;
  198. triplet.Second = DeserializeObject (splitted [1]);
  199. if (splitted.Length < 2)
  200. break;
  201. triplet.Third = DeserializeObject (splitted [2]);
  202. break;
  203. case arrayListID:
  204. case arrayID:
  205. ArrayList list = new ArrayList ();
  206. obj = list;
  207. splitted = GetStringValues (enclosed);
  208. foreach (string s in splitted) {
  209. object o = DeserializeObject (s);
  210. list.Add (o);
  211. }
  212. if (input [0] == arrayID)
  213. obj = list.ToArray (typeof (object));
  214. break;
  215. case hashtableID:
  216. object key;
  217. object value;
  218. Hashtable hash = new Hashtable ();
  219. obj = hash;
  220. splitted = GetStringValues (enclosed);
  221. int length = splitted.Length;
  222. for (int i = 0; i < length; i++) {
  223. key = DeserializeObject (splitted [i++]);
  224. if (i < length)
  225. value = DeserializeObject (splitted [i]);
  226. else
  227. value = null;
  228. hash.Add (key, value);
  229. }
  230. break;
  231. case binaryID:
  232. byte [] buffer = Convert.FromBase64String (enclosed);
  233. MemoryStream ms = new MemoryStream (buffer);
  234. BinaryFormatter fmt = new BinaryFormatter ();
  235. obj = fmt.Deserialize (ms);
  236. break;
  237. case dateTimeID:
  238. obj = new DateTime (Int64.Parse (enclosed));
  239. break;
  240. case unitID:
  241. obj = Unit.Parse (enclosed);
  242. break;
  243. case fontUnitID:
  244. obj = FontUnit.Parse (enclosed);
  245. break;
  246. default:
  247. throw new ArgumentException ("input");
  248. }
  249. return obj;
  250. }
  251. public void Serialize (Stream stream, object value)
  252. {
  253. if (stream == null)
  254. throw new ArgumentNullException ("stream");
  255. if (value == null)
  256. throw new ArgumentNullException ("value");
  257. StreamWriter writer = new StreamWriter (stream);
  258. Serialize (writer, value);
  259. writer.Flush ();
  260. }
  261. public void Serialize (TextWriter output, object value)
  262. {
  263. if (value == null)
  264. return;
  265. if (output == null)
  266. throw new ArgumentNullException ("output");
  267. StringBuilder builder = new StringBuilder ();
  268. StringWriter writer = new StringWriter (builder);
  269. SerializeObject (writer, value);
  270. byte [] bytes = WebEncoding.Encoding.GetBytes (builder.ToString ());
  271. output.Write (Convert.ToBase64String (bytes));
  272. }
  273. private static void WriteBoolean (LosFormatter formatter, TextWriter output, object value)
  274. {
  275. if (value == null)
  276. return;
  277. output.Write (booleanID);
  278. bool b = (bool) value;
  279. output.Write (b ? "<t>" : "<>");
  280. }
  281. private static void WritePair (LosFormatter formatter, TextWriter output, object value)
  282. {
  283. if (value == null)
  284. return;
  285. output.Write (pairID);
  286. Pair pair = (Pair) value;
  287. output.Write ('<');
  288. formatter.SerializeObject (output, pair.First);
  289. output.Write (';');
  290. formatter.SerializeObject (output, pair.Second);
  291. output.Write ('>');
  292. }
  293. private static void WriteTriplet (LosFormatter formatter, TextWriter output, object value)
  294. {
  295. if (value == null)
  296. return;
  297. output.Write (tripletID);
  298. Triplet triplet = (Triplet) value;
  299. output.Write ('<');
  300. formatter.SerializeObject (output, triplet.First);
  301. output.Write (';');
  302. formatter.SerializeObject (output, triplet.Second);
  303. output.Write (';');
  304. formatter.SerializeObject (output, triplet.Third);
  305. output.Write ('>');
  306. }
  307. private static void WriteColor (LosFormatter formatter, TextWriter output, object value)
  308. {
  309. if (value == null)
  310. return;
  311. Color c = (Color) value;
  312. output.Write (String.Format ("{0}<{1}>", colorID, c.ToArgb ()));
  313. }
  314. private static void WriteArrayList (LosFormatter formatter, TextWriter output, object value)
  315. {
  316. if (value == null)
  317. return;
  318. output.Write (arrayListID);
  319. output.Write ('<');
  320. ArrayList list = (ArrayList) value;
  321. for (int i = 0; i < list.Count; i++) {
  322. formatter.SerializeObject (output, list [i]);
  323. if (i != list.Count - 1)
  324. output.Write (';');
  325. }
  326. output.Write('>');
  327. }
  328. private static void WriteArray (LosFormatter formatter, TextWriter output, object value)
  329. {
  330. if (value == null)
  331. return;
  332. output.Write (arrayID);
  333. output.Write ('<');
  334. Array array = (Array) value;
  335. for (int i = 0; i < array.Length; i++) {
  336. formatter.SerializeObject (output, array.GetValue (i));
  337. if (i != array.Length - 1)
  338. output.Write (';');
  339. }
  340. output.Write('>');
  341. }
  342. private static void WriteHashtable (LosFormatter formatter, TextWriter output, object value)
  343. {
  344. if (value == null)
  345. return;
  346. output.Write (hashtableID);
  347. output.Write ('<');
  348. Hashtable hash = (Hashtable) value;
  349. int i = 0;
  350. foreach (DictionaryEntry entry in hash) {
  351. formatter.SerializeObject (output, entry.Key);
  352. output.Write (';');
  353. formatter.SerializeObject (output, entry.Value);
  354. if (i != hash.Count - 1)
  355. output.Write (';');
  356. i++;
  357. }
  358. output.Write('>');
  359. }
  360. private static void WriteDateTime (LosFormatter formatter, TextWriter output, object value)
  361. {
  362. if (value == null)
  363. return;
  364. output.Write (dateTimeID);
  365. output.Write ('<');
  366. output.Write (((DateTime) value).Ticks);
  367. output.Write('>');
  368. }
  369. static void WriteUnit (LosFormatter formatter, TextWriter output, object value)
  370. {
  371. if (value == null)
  372. return;
  373. output.Write (unitID);
  374. output.Write ('<');
  375. output.Write (((Unit) value).ToString ());
  376. output.Write('>');
  377. }
  378. static void WriteFontUnit (LosFormatter formatter, TextWriter output, object value)
  379. {
  380. if (value == null)
  381. return;
  382. output.Write (fontUnitID);
  383. output.Write ('<');
  384. output.Write (((FontUnit) value).ToString ());
  385. output.Write('>');
  386. }
  387. private static string EscapeSpecialChars (string str)
  388. {
  389. if (str.IndexOfAny (specialChars) == -1)
  390. return str;
  391. string result = str.Replace ("\\", "\\\\");
  392. result = result.Replace ("<", "\\<");
  393. result = result.Replace (">", "\\>");
  394. result = result.Replace (";", "\\;");
  395. return result;
  396. }
  397. private void SerializeBinary (TextWriter output, object value)
  398. {
  399. WebTrace.PushContext ("LosFormatter.SerializeBinary");
  400. /* This is just for debugging purposes */
  401. /*if (value is Array) {
  402. Array array = (Array) value;
  403. for (int i = 0; i < array.Length; i++) {
  404. object o = array.GetValue (i);
  405. if (o == null)
  406. WebTrace.WriteLine ("\t{0} is null", i);
  407. else
  408. WebTrace.WriteLine ("\t{0} {1} {2}", i, o.GetType (), o);
  409. }
  410. }
  411. */
  412. BinaryFormatter fmt = new BinaryFormatter ();
  413. MemoryStream stream = new MemoryStream ();
  414. fmt.Serialize (stream, value);
  415. output.Write (binaryID);
  416. output.Write ('<');
  417. byte [] buffer = stream.GetBuffer ();
  418. output.Write (Convert.ToBase64String (buffer));
  419. output.Write ('>');
  420. WebTrace.PopContext ();
  421. }
  422. private void SerializeObject (TextWriter output, object value)
  423. {
  424. WebTrace.PushContext ("LosFormatter.SerializeObject");
  425. if (value == null) {
  426. WebTrace.WriteLine ("value is null");
  427. WebTrace.PopContext ();
  428. return;
  429. }
  430. Type t = value.GetType ();
  431. if (t.IsArray)
  432. t = typeof (Array);
  433. if (specialTypes.Contains (t)) {
  434. WriteObject w = (WriteObject) specialTypes [t];
  435. w (this, output, value);
  436. WebTrace.WriteLine ("special type: {0}", value.GetType ());
  437. WebTrace.PopContext ();
  438. return;
  439. }
  440. if (idToType.Contains (t)) {
  441. char c = (char) idToType [t];
  442. string s = EscapeSpecialChars (value.ToString ());
  443. output.Write (String.Format ("{0}<{1}>", c, value.ToString ()));
  444. WebTrace.WriteLine ("regular type: {0}", value.GetType ());
  445. WebTrace.PopContext ();
  446. return;
  447. }
  448. SerializeBinary (output, value);
  449. WebTrace.PopContext ();
  450. }
  451. }
  452. }