LosFormatter.cs 13 KB

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