PageRenderTime 81ms CodeModel.GetById 38ms RepoModel.GetById 1ms app.codeStats 0ms

/AjaxControlToolkitEx/UpdatePanelEx.cs

http://AjaxControlToolkitEx.codeplex.com
C# | 582 lines | 546 code | 36 blank | 0 comment | 37 complexity | f06b1deb694e7a958fb78043bb77953d MD5 | raw file
  1. using System;
  2. using System.Data;
  3. using System.Configuration;
  4. using System.Web;
  5. using System.Web.Security;
  6. using System.Web.UI;
  7. using System.Web.UI.HtmlControls;
  8. using System.Web.UI.WebControls;
  9. using System.Web.UI.WebControls.WebParts;
  10. using System.IO;
  11. using System.Globalization;
  12. using System.Text.RegularExpressions;
  13. using System.Collections;
  14. using System.IO.Compression;
  15. using System.Collections.Generic;
  16. using AjaxControlToolkit;
  17. namespace AjaxControlToolkitEx
  18. {
  19. public class PageEx : Page
  20. {
  21. protected virtual string TempFolder
  22. {
  23. get
  24. {
  25. throw new NotImplementedException();
  26. }
  27. }
  28. private string PageStateUID;
  29. private string PageStateFileName
  30. {
  31. get
  32. {
  33. if (this.DesignMode)
  34. return Server.MapPath(String.Format("{0}/{1}_{2}_{3}.tmp", TempFolder, "DesignTimeSession", Request.ServerVariables["Path_Info"].Replace("/", "_"), PageStateUID));
  35. return Server.MapPath(String.Format("{0}/{1}_{2}_{3}.tmp", TempFolder, Session.SessionID, Request.ServerVariables["Path_Info"].Replace("/", "_"), PageStateUID));
  36. }
  37. }
  38. protected override object LoadPageStateFromPersistenceMedium()
  39. {
  40. PageStatePersister pageStatePersister = this.PageStatePersister;
  41. try
  42. {
  43. pageStatePersister.Load();
  44. PageStateUID = pageStatePersister.ViewState as string;
  45. }
  46. catch
  47. {
  48. PageStateUID = Guid.NewGuid().ToString();
  49. }
  50. string m_viewState;
  51. LosFormatter m_formatter;
  52. object viewStateBag;
  53. string file = PageStateFileName;
  54. StreamReader sr = new StreamReader(file);
  55. m_viewState = sr.ReadToEnd();
  56. sr.Close();
  57. m_formatter = new LosFormatter();
  58. try
  59. {
  60. viewStateBag = m_formatter.Deserialize(m_viewState);
  61. }
  62. catch
  63. {
  64. throw new HttpException("The View State is invalid or corrupted");
  65. }
  66. return viewStateBag;
  67. }
  68. protected override void SavePageStateToPersistenceMedium(object viewStateBag)
  69. {
  70. if (string.IsNullOrEmpty(PageStateUID))
  71. PageStateUID = Guid.NewGuid().ToString();
  72. string file = PageStateFileName;
  73. StreamWriter sw = new StreamWriter(file);
  74. LosFormatter m_formatter = new LosFormatter();
  75. m_formatter.Serialize(sw, viewStateBag);
  76. sw.Close();
  77. PageStatePersister pageStatePersister = this.PageStatePersister;
  78. pageStatePersister.ViewState = PageStateUID;
  79. pageStatePersister.Save();
  80. return;
  81. }
  82. private PageStatePersister persistor;
  83. protected override PageStatePersister PageStatePersister
  84. {
  85. get
  86. {
  87. if (this.persistor == null)
  88. this.persistor = new CompressedPageStatePersister(Page);
  89. return this.persistor;
  90. }
  91. }
  92. internal static class Compressor
  93. {
  94. public static byte[] Compress(byte[] data)
  95. {
  96. MemoryStream output = new MemoryStream();
  97. GZipStream gzip = new GZipStream(output,
  98. CompressionMode.Compress, true);
  99. gzip.Write(data, 0, data.Length);
  100. gzip.Close();
  101. return output.ToArray();
  102. }
  103. public static byte[] Decompress(byte[] data)
  104. {
  105. MemoryStream input = new MemoryStream();
  106. input.Write(data, 0, data.Length);
  107. input.Position = 0;
  108. GZipStream gzip = new GZipStream(input,
  109. CompressionMode.Decompress, true);
  110. MemoryStream output = new MemoryStream();
  111. byte[] buff = new byte[64];
  112. int read = -1;
  113. read = gzip.Read(buff, 0, buff.Length);
  114. while (read > 0)
  115. {
  116. output.Write(buff, 0, read);
  117. read = gzip.Read(buff, 0, buff.Length);
  118. }
  119. gzip.Close();
  120. return output.ToArray();
  121. }
  122. }
  123. internal class CompressedPageStatePersister : PageStatePersister
  124. {
  125. public CompressedPageStatePersister(Page page)
  126. : base(page)
  127. {
  128. }
  129. public override void Load()
  130. {
  131. string viewState = Page.Request.Form["__VSTATE"];
  132. byte[] bytes = Convert.FromBase64String(viewState);
  133. bytes = Compressor.Decompress(bytes);
  134. LosFormatter formatter = new LosFormatter();
  135. object obj = formatter.Deserialize(Convert.ToBase64String(bytes));
  136. Pair pair = (Pair)obj;
  137. ViewState = pair.First;
  138. ControlState = pair.Second;
  139. }
  140. public override void Save()
  141. {
  142. Pair pair = new Pair(ViewState, ControlState);
  143. LosFormatter formatter = new LosFormatter();
  144. StringWriter writer = new StringWriter();
  145. formatter.Serialize(writer, pair);
  146. string viewStateString = writer.ToString();
  147. byte[] bytes = Convert.FromBase64String(viewStateString);
  148. bytes = Compressor.Compress(bytes);
  149. ScriptManager.RegisterHiddenField(Page, "__VSTATE", Convert.ToBase64String(bytes));
  150. }
  151. }
  152. #region id map
  153. internal static Dictionary<string, string> GetIDMap(Page page)
  154. {
  155. if (page.Session["cIDMap" + page.UniqueID] == null)
  156. page.Session["cIDMap" + page.UniqueID] = new Dictionary<string, string>();
  157. return page.Session["cIDMap" + page.UniqueID] as Dictionary<string, string>;
  158. }
  159. internal static void SetIDMap(Page page, Dictionary<string, string> idmap)
  160. {
  161. page.Session["cIDMap" + page.UniqueID] = idmap;
  162. }
  163. internal static Dictionary<string, string> GetIDMap2(Page page)
  164. {
  165. if (page.Session["cIDMap2" + page.UniqueID] == null)
  166. page.Session["cIDMap2" + page.UniqueID] = new Dictionary<string, string>();
  167. return page.Session["cIDMap2" + page.UniqueID] as Dictionary<string, string>;
  168. }
  169. internal static void SetIDMap2(Page page, Dictionary<string, string> idmap)
  170. {
  171. page.Session["cIDMap2" + page.UniqueID] = idmap;
  172. }
  173. public static string GetUniqueID(Page page, string baseUniqueID)
  174. {
  175. Dictionary<string, string> idmap = GetIDMap(page);
  176. Dictionary<string, string> idmap2 = GetIDMap2(page);
  177. if (!idmap.ContainsKey(baseUniqueID))
  178. {
  179. int i = idmap.Keys.Count;
  180. bool found = false;
  181. string newid = baseUniqueID;
  182. do
  183. {
  184. newid = string.Format("c{0}", i++);
  185. found = idmap.ContainsValue(newid);
  186. } while (found);
  187. idmap.Add(baseUniqueID, newid);
  188. idmap2.Add(newid, baseUniqueID);
  189. SetIDMap(page, idmap);
  190. SetIDMap2(page, idmap2);
  191. }
  192. return idmap[baseUniqueID];
  193. }
  194. #endregion
  195. public override Control FindControl(string id)
  196. {
  197. if (this.DesignMode)
  198. return base.FindControl(id);
  199. Dictionary<string, string> idmap2 = GetIDMap2(this);
  200. if (idmap2.ContainsKey(id))
  201. return base.FindControl(idmap2[id]);
  202. return base.FindControl(id);
  203. }
  204. protected override Control FindControl(string id, int pathOffset)
  205. {
  206. if (this.DesignMode)
  207. return base.FindControl(id, pathOffset);
  208. Dictionary<string, string> idmap2 = GetIDMap2(this);
  209. if (idmap2.ContainsKey(id))
  210. return base.FindControl(idmap2[id], pathOffset);
  211. return base.FindControl(id, pathOffset);
  212. }
  213. }
  214. public class Helper
  215. {
  216. private static Regex reg = new Regex(@"(?<=[^])\t{2,}|(?<=[>])\s{2,}(?=[<])|(?<=[>])\s{2,11}(?=[<])|(?=[\n])\s{2,}");
  217. public static string Trim(string content)
  218. {
  219. return content; // reg.Replace(content, string.Empty);
  220. }
  221. public static void RunScript(Control control, Type type, string key, string script, bool addScriptTags)
  222. {
  223. ScriptManager.RegisterStartupScript(control, type, key, Trim(script), addScriptTags);
  224. }
  225. public static void SetupScript(Control control, Type type, string key, string script, bool addScriptTags)
  226. {
  227. ScriptManager.RegisterClientScriptBlock(control, type, key, Trim(script), addScriptTags);
  228. }
  229. }
  230. public class UpdatePanelEx : UpdatePanel
  231. {
  232. private bool _rendered;
  233. protected override void RenderChildren(HtmlTextWriter writer)
  234. {
  235. if (this.IsInPartialRendering)
  236. {
  237. if (this._rendered)
  238. {
  239. return;
  240. }
  241. HtmlTextWriter writer2 = new HtmlTextWriter(new StringWriter(CultureInfo.CurrentCulture));
  242. base.RenderChildren(writer2);
  243. string content = writer2.InnerWriter.ToString();
  244. {
  245. int pos = content.IndexOf('|');
  246. if (pos >= 0)
  247. {
  248. int length = Convert.ToInt32(content.Substring(0, pos));
  249. content = content.Substring(pos + 1);
  250. pos = content.IndexOf('|');
  251. if (pos >= 0)
  252. {
  253. string type = content.Substring(0, pos);
  254. content = content.Substring(pos + 1);
  255. pos = content.IndexOf('|');
  256. if (pos >= 0)
  257. {
  258. string id = content.Substring(0, pos);
  259. content = content.Substring(pos + 1);
  260. pos = content.LastIndexOf('|');
  261. if (pos >= 0)
  262. {
  263. content = content.Substring(0, pos);
  264. }
  265. }
  266. }
  267. }
  268. }
  269. EncodeStringEx(writer, "updatePanel", this.ClientID, content);
  270. }
  271. else
  272. {
  273. HtmlTextWriter writer2 = new HtmlTextWriter(new StringWriter(CultureInfo.CurrentCulture));
  274. base.RenderChildren(writer2);
  275. string content = writer2.InnerWriter.ToString();
  276. writer.Write(Helper.Trim(content));
  277. }
  278. this._rendered = true;
  279. }
  280. internal static void EncodeStringEx(TextWriter writer, string type, string id, string content)
  281. {
  282. if (id == null)
  283. {
  284. id = string.Empty;
  285. }
  286. if (content == null)
  287. {
  288. content = string.Empty;
  289. }
  290. content = Helper.Trim(content);
  291. int num = 0;
  292. for (int i = 0; i < content.Length; i++)
  293. {
  294. if (content[i] == '\x00ff')
  295. {
  296. num++;
  297. }
  298. else if (content[i] == '\0')
  299. {
  300. num += 2;
  301. }
  302. }
  303. writer.Write((content.Length + num).ToString(CultureInfo.InvariantCulture));
  304. writer.Write('|');
  305. writer.Write(type);
  306. writer.Write('|');
  307. writer.Write(id);
  308. writer.Write('|');
  309. int index = 0;
  310. char[] buffer = content.ToCharArray();
  311. for (int j = 0; j < buffer.Length; j++)
  312. {
  313. if (buffer[j] == '\x00ff')
  314. {
  315. writer.Write(buffer, index, j - index);
  316. writer.Write("\x00ff\x00ff");
  317. index = j + 1;
  318. }
  319. else if (buffer[j] == '\0')
  320. {
  321. writer.Write(buffer, index, j - index);
  322. writer.Write("\\\x00ff\\");
  323. index = j + 1;
  324. }
  325. }
  326. writer.Write(buffer, index, buffer.Length - index);
  327. writer.Write('|');
  328. }
  329. private string m_cachedUniqueID = null;
  330. public override string UniqueID
  331. {
  332. get
  333. {
  334. if (this.DesignMode)
  335. return base.UniqueID;
  336. if (m_cachedUniqueID == null)
  337. m_cachedUniqueID = GetUniqueID(Page, base.UniqueID);
  338. return m_cachedUniqueID;
  339. }
  340. }
  341. private static Dictionary<string, string> GetIDMap(Page page)
  342. {
  343. if (page.Session["uIDMap" + page.UniqueID] == null)
  344. page.Session["uIDMap" + page.UniqueID] = new Dictionary<string, string>();
  345. return page.Session["uIDMap" + page.UniqueID] as Dictionary<string, string>;
  346. }
  347. private static void SetIDMap(Page page, Dictionary<string, string> idmap)
  348. {
  349. page.Session["uIDMap" + page.UniqueID] = idmap;
  350. }
  351. internal static string GetUniqueID(Page page, string baseUniqueID)
  352. {
  353. Dictionary<string, string> idmap = GetIDMap(page);
  354. if (!idmap.ContainsKey(baseUniqueID))
  355. {
  356. int i = idmap.Keys.Count;
  357. bool found = false;
  358. string newid = baseUniqueID;
  359. do
  360. {
  361. newid = string.Format("u{0}", i++);
  362. found = idmap.ContainsValue(newid);
  363. } while (found);
  364. idmap.Add(baseUniqueID, newid);
  365. SetIDMap(page, idmap);
  366. }
  367. return idmap[baseUniqueID];
  368. }
  369. }
  370. public class ExtenderControlBaseEx : ExtenderControlBase
  371. {
  372. public override Control FindControl(string id)
  373. {
  374. Dictionary<string, string> idmap2 = PageEx.GetIDMap2(Page);
  375. if (idmap2.ContainsKey(id))
  376. return base.FindControl(idmap2[id]);
  377. return base.FindControl(id);
  378. }
  379. protected override Control FindControl(string id, int pathOffset)
  380. {
  381. Dictionary<string, string> idmap2 = PageEx.GetIDMap2(Page);
  382. if (idmap2.ContainsKey(id))
  383. return base.FindControl(idmap2[id], pathOffset);
  384. return base.FindControl(id, pathOffset);
  385. }
  386. internal class HiddenFieldEx : HiddenField
  387. {
  388. private string m_cachedUniqueID = null;
  389. public override string UniqueID
  390. {
  391. get
  392. {
  393. if (this.DesignMode)
  394. return base.UniqueID;
  395. if (m_cachedUniqueID == null)
  396. m_cachedUniqueID = PageEx.GetUniqueID(Page, base.UniqueID);
  397. return m_cachedUniqueID;
  398. }
  399. }
  400. }
  401. }
  402. public class AppHelper
  403. {
  404. public static void BeginCompression()
  405. {
  406. string acceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"];
  407. if (string.IsNullOrEmpty(acceptEncoding))
  408. return;
  409. acceptEncoding = acceptEncoding.ToLower();
  410. string urlAbsolutePath = HttpContext.Current.Request.Url.AbsolutePath;
  411. if (!string.IsNullOrEmpty(urlAbsolutePath))
  412. {
  413. urlAbsolutePath = urlAbsolutePath.ToLower();
  414. if (urlAbsolutePath.EndsWith(".ashx") || urlAbsolutePath.EndsWith(".axd"))
  415. return;
  416. }
  417. if (HttpContext.Current.Request.QueryString["_TSM_HiddenField_"] != null)
  418. return;
  419. Stream filterstream = HttpContext.Current.Response.Filter;
  420. if ((acceptEncoding.Contains("gzip") || acceptEncoding.Contains("x-gzip") || acceptEncoding.Contains("*")))
  421. {
  422. if (HttpContext.Current.CurrentHandler is System.Web.UI.Page
  423. && HttpContext.Current.Request["HTTP_X_MICROSOFTAJAX"] != null
  424. && HttpContext.Current.Request["X-MICROSOFTAJAX"] != null
  425. )
  426. {
  427. GZipStream2 newstream = new GZipStream2();
  428. HttpContext.Current.Response.Filter = newstream;
  429. HttpContext.Current.Items["CompressionStream"] = newstream;
  430. }
  431. else
  432. {
  433. HttpContext.Current.Response.Filter = new GZipStream(filterstream, CompressionMode.Compress);
  434. }
  435. HttpContext.Current.Response.AppendHeader("Content-Encoding", "gzip");
  436. }
  437. else if (acceptEncoding.Contains("deflate"))
  438. {
  439. HttpContext.Current.Response.Filter = new DeflateStream(filterstream, CompressionMode.Compress);
  440. HttpContext.Current.Response.AppendHeader("Content-Encoding", "deflate");
  441. }
  442. }
  443. public static void EndCompression()
  444. {
  445. GZipStream2 stream = (GZipStream2)HttpContext.Current.Items["CompressionStream"];
  446. if (stream != null)
  447. stream.CloseAndWriteAll(HttpContext.Current.Response.OutputStream);
  448. }
  449. }
  450. #region Stream
  451. internal class GZipStream2 : Stream
  452. {
  453. private MemoryStream _ms;
  454. private GZipStream _gzip;
  455. public GZipStream2()
  456. {
  457. _ms = new MemoryStream(1024);
  458. _gzip = new GZipStream(_ms, CompressionMode.Compress);
  459. }
  460. public override bool CanRead
  461. {
  462. get { return _gzip.CanRead; }
  463. }
  464. public override bool CanSeek
  465. {
  466. get { return _gzip.CanSeek; }
  467. }
  468. public override bool CanWrite
  469. {
  470. get { return _gzip.CanWrite; }
  471. }
  472. public override void Flush()
  473. {
  474. }
  475. public override long Length
  476. {
  477. get { return _gzip.Length; }
  478. }
  479. public override long Position
  480. {
  481. get
  482. {
  483. return _gzip.Position;
  484. }
  485. set
  486. {
  487. _gzip.Position = value;
  488. }
  489. }
  490. public override int Read(byte[] buffer, int offset, int count)
  491. {
  492. return _gzip.Read(buffer, offset, count);
  493. }
  494. public override long Seek(long offset, SeekOrigin origin)
  495. {
  496. return _gzip.Seek(offset, origin);
  497. }
  498. public override void SetLength(long value)
  499. {
  500. _gzip.SetLength(value);
  501. }
  502. public override void Write(byte[] buffer, int offset, int count)
  503. {
  504. _gzip.Write(buffer, offset, count);
  505. }
  506. public void CloseAndWriteAll(Stream outStream)
  507. {
  508. _gzip.Close();
  509. _ms.Close();
  510. byte[] buffer = _ms.ToArray();
  511. outStream.Write(_ms.ToArray(), 0, buffer.Length);
  512. }
  513. }
  514. #endregion
  515. }