Page.cs 66 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552
  1. //
  2. // System.Web.UI.Page.cs
  3. //
  4. // Authors:
  5. // Duncan Mak ([email protected])
  6. // Gonzalo Paniagua ([email protected])
  7. // Andreas Nahr ([email protected])
  8. //
  9. // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
  10. // Copyright (C) 2003,2005 Novell, Inc (http://www.novell.com)
  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. using System;
  32. using System.Collections;
  33. using System.Collections.Specialized;
  34. using System.ComponentModel;
  35. using System.ComponentModel.Design;
  36. using System.ComponentModel.Design.Serialization;
  37. using System.Globalization;
  38. using System.IO;
  39. using System.Security.Cryptography;
  40. using System.Security.Permissions;
  41. using System.Security.Principal;
  42. using System.Text;
  43. using System.Threading;
  44. using System.Web;
  45. using System.Web.Caching;
  46. using System.Web.Configuration;
  47. using System.Web.SessionState;
  48. using System.Web.Util;
  49. using System.Web.UI.HtmlControls;
  50. using System.Web.UI.WebControls;
  51. #if NET_2_0
  52. using System.Web.UI.Adapters;
  53. using System.Collections.Generic;
  54. using System.Reflection;
  55. #endif
  56. namespace System.Web.UI
  57. {
  58. // CAS
  59. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  60. [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  61. #if !NET_2_0
  62. [RootDesignerSerializer ("Microsoft.VSDesigner.WebForms.RootCodeDomSerializer, " + Consts.AssemblyMicrosoft_VSDesigner, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design, true)]
  63. #endif
  64. [DefaultEvent ("Load"), DesignerCategory ("ASPXCodeBehind")]
  65. [ToolboxItem (false)]
  66. #if NET_2_0
  67. [Designer ("Microsoft.VisualStudio.Web.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VisualStudio_Web, typeof (IRootDesigner))]
  68. #else
  69. [Designer ("Microsoft.VSDesigner.WebForms.WebFormDesigner, " + Consts.AssemblyMicrosoft_VSDesigner, typeof (IRootDesigner))]
  70. #endif
  71. public partial class Page : TemplateControl, IHttpHandler
  72. {
  73. static string machineKeyConfigPath = "system.web/machineKey";
  74. #if NET_2_0
  75. private PageLifeCycle _lifeCycle = PageLifeCycle.Unknown;
  76. private bool _eventValidation = true;
  77. private object [] _savedControlState;
  78. private bool _doLoadPreviousPage;
  79. string _focusedControlID;
  80. bool _hasEnabledControlArray;
  81. #endif
  82. private bool _viewState = true;
  83. private bool _viewStateMac;
  84. private string _errorPage;
  85. private bool is_validated;
  86. private bool _smartNavigation;
  87. private int _transactionMode;
  88. private HttpContext _context;
  89. private ValidatorCollection _validators;
  90. private bool renderingForm;
  91. private string _savedViewState;
  92. private ArrayList _requiresPostBack;
  93. private ArrayList _requiresPostBackCopy;
  94. private ArrayList requiresPostDataChanged;
  95. private IPostBackEventHandler requiresRaiseEvent;
  96. private NameValueCollection secondPostData;
  97. private bool requiresPostBackScript;
  98. private bool postBackScriptRendered;
  99. bool handleViewState;
  100. string viewStateUserKey;
  101. NameValueCollection _requestValueCollection;
  102. string clientTarget;
  103. ClientScriptManager scriptManager;
  104. bool allow_load; // true when the Form collection belongs to this page (GetTypeHashCode)
  105. PageStatePersister page_state_persister;
  106. [EditorBrowsable (EditorBrowsableState.Never)]
  107. #if NET_2_0
  108. public
  109. #else
  110. protected
  111. #endif
  112. const string postEventArgumentID = "__EVENTARGUMENT";
  113. [EditorBrowsable (EditorBrowsableState.Never)]
  114. #if NET_2_0
  115. public
  116. #else
  117. protected
  118. #endif
  119. const string postEventSourceID = "__EVENTTARGET";
  120. #if NET_2_0
  121. const string ScrollPositionXID = "__SCROLLPOSITIONX";
  122. const string ScrollPositionYID = "__SCROLLPOSITIONY";
  123. const string EnabledControlArrayID = "__enabledControlArray";
  124. #endif
  125. #if NET_2_0
  126. internal const string LastFocusID = "__LASTFOCUS";
  127. internal const string CallbackArgumentID = "__CALLBACKARGUMENT";
  128. internal const string CallbackSourceID = "__CALLBACKTARGET";
  129. internal const string PreviousPageID = "__PREVIOUSPAGE";
  130. HtmlHead htmlHeader;
  131. MasterPage masterPage;
  132. string masterPageFile;
  133. Page previousPage;
  134. bool isCrossPagePostBack;
  135. bool isPostBack;
  136. bool isCallback;
  137. ArrayList requireStateControls;
  138. Hashtable _validatorsByGroup;
  139. HtmlForm _form;
  140. string _title;
  141. string _theme;
  142. string _styleSheetTheme;
  143. Hashtable items;
  144. bool _maintainScrollPositionOnPostBack;
  145. private bool asyncMode = false;
  146. private TimeSpan asyncTimeout;
  147. private const double DefaultAsyncTimeout = 45.0;
  148. private List<PageAsyncTask> parallelTasks;
  149. private List<PageAsyncTask> serialTasks;
  150. private ViewStateEncryptionMode viewStateEncryptionMode;
  151. private bool controlRegisteredForViewStateEncryption = false;
  152. #endif
  153. #region Constructor
  154. public Page ()
  155. {
  156. scriptManager = new ClientScriptManager (this);
  157. Page = this;
  158. ID = "__Page";
  159. #if NET_2_0
  160. PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
  161. if (ps != null) {
  162. asyncTimeout = ps.AsyncTimeout;
  163. viewStateEncryptionMode = ps.ViewStateEncryptionMode;
  164. } else {
  165. asyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
  166. viewStateEncryptionMode = ViewStateEncryptionMode.Auto;
  167. }
  168. #endif
  169. }
  170. #endregion
  171. #region Properties
  172. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  173. [Browsable (false)]
  174. public HttpApplicationState Application
  175. {
  176. get {
  177. if (_context == null)
  178. return null;
  179. return _context.Application;
  180. }
  181. }
  182. [EditorBrowsable (EditorBrowsableState.Never)]
  183. protected bool AspCompatMode
  184. {
  185. #if NET_2_0
  186. get { return false; }
  187. #endif
  188. set { throw new NotImplementedException (); }
  189. }
  190. [EditorBrowsable (EditorBrowsableState.Never)]
  191. #if NET_2_0
  192. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  193. [BrowsableAttribute (false)]
  194. public bool Buffer
  195. {
  196. get { return Response.BufferOutput; }
  197. set { Response.BufferOutput = value; }
  198. }
  199. #else
  200. protected bool Buffer
  201. {
  202. set { Response.BufferOutput = value; }
  203. }
  204. #endif
  205. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  206. [Browsable (false)]
  207. public Cache Cache
  208. {
  209. get {
  210. if (_context == null)
  211. throw new HttpException ("No cache available without a context.");
  212. return _context.Cache;
  213. }
  214. }
  215. #if NET_2_0
  216. [EditorBrowsableAttribute (EditorBrowsableState.Advanced)]
  217. #endif
  218. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  219. [Browsable (false), DefaultValue ("")]
  220. [WebSysDescription ("Value do override the automatic browser detection and force the page to use the specified browser.")]
  221. public string ClientTarget
  222. {
  223. get { return (clientTarget == null) ? "" : clientTarget; }
  224. set {
  225. clientTarget = value;
  226. if (value == "")
  227. clientTarget = null;
  228. }
  229. }
  230. [EditorBrowsable (EditorBrowsableState.Never)]
  231. #if NET_2_0
  232. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  233. [BrowsableAttribute (false)]
  234. public int CodePage
  235. {
  236. get { return Response.ContentEncoding.CodePage; }
  237. set { Response.ContentEncoding = Encoding.GetEncoding (value); }
  238. }
  239. #else
  240. protected int CodePage
  241. {
  242. set { Response.ContentEncoding = Encoding.GetEncoding (value); }
  243. }
  244. #endif
  245. [EditorBrowsable (EditorBrowsableState.Never)]
  246. #if NET_2_0
  247. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  248. [BrowsableAttribute (false)]
  249. public string ContentType
  250. {
  251. get { return Response.ContentType; }
  252. set { Response.ContentType = value; }
  253. }
  254. #else
  255. protected string ContentType
  256. {
  257. set { Response.ContentType = value; }
  258. }
  259. #endif
  260. protected override HttpContext Context
  261. {
  262. get {
  263. if (_context == null)
  264. return HttpContext.Current;
  265. return _context;
  266. }
  267. }
  268. #if NET_2_0
  269. [EditorBrowsable (EditorBrowsableState.Advanced)]
  270. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  271. [BrowsableAttribute (false)]
  272. public string Culture
  273. {
  274. get { return Thread.CurrentThread.CurrentCulture.Name; }
  275. set { Thread.CurrentThread.CurrentCulture = GetPageCulture (value, Thread.CurrentThread.CurrentCulture); }
  276. }
  277. #else
  278. [EditorBrowsable (EditorBrowsableState.Never)]
  279. protected string Culture
  280. {
  281. set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
  282. }
  283. #endif
  284. #if NET_2_0
  285. public virtual bool EnableEventValidation {
  286. get { return _eventValidation; }
  287. set {
  288. if (_lifeCycle > PageLifeCycle.Init)
  289. throw new InvalidOperationException ("The 'EnableEventValidation' property can be set only in the Page_init, the Page directive or in the <pages> configuration section.");
  290. _eventValidation = value;
  291. }
  292. }
  293. internal PageLifeCycle LifeCycle {
  294. get { return _lifeCycle; }
  295. }
  296. #endif
  297. [Browsable (false)]
  298. public override bool EnableViewState
  299. {
  300. get { return _viewState; }
  301. set { _viewState = value; }
  302. }
  303. #if NET_2_0
  304. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  305. [BrowsableAttribute (false)]
  306. #endif
  307. [EditorBrowsable (EditorBrowsableState.Never)]
  308. #if NET_2_0
  309. public
  310. #else
  311. protected
  312. #endif
  313. bool EnableViewStateMac
  314. {
  315. get { return _viewStateMac; }
  316. set { _viewStateMac = value; }
  317. }
  318. #if NET_1_1
  319. internal bool EnableViewStateMacInternal {
  320. get { return _viewStateMac; }
  321. set { _viewStateMac = value; }
  322. }
  323. #endif
  324. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  325. [Browsable (false), DefaultValue ("")]
  326. [WebSysDescription ("The URL of a page used for error redirection.")]
  327. public string ErrorPage
  328. {
  329. get { return _errorPage; }
  330. set {
  331. _errorPage = value;
  332. if (_context != null)
  333. _context.ErrorPage = value;
  334. }
  335. }
  336. #if NET_2_0
  337. [Obsolete]
  338. #endif
  339. [EditorBrowsable (EditorBrowsableState.Never)]
  340. protected ArrayList FileDependencies
  341. {
  342. set {
  343. if (Response != null)
  344. Response.AddFileDependencies (value);
  345. }
  346. }
  347. [Browsable (false)]
  348. #if NET_2_0
  349. [EditorBrowsable (EditorBrowsableState.Never)]
  350. #endif
  351. public override string ID
  352. {
  353. get { return base.ID; }
  354. set { base.ID = value; }
  355. }
  356. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  357. [Browsable (false)]
  358. public bool IsPostBack
  359. {
  360. get {
  361. #if NET_2_0
  362. return isPostBack;
  363. #else
  364. return _requestValueCollection != null;
  365. #endif
  366. }
  367. }
  368. [EditorBrowsable (EditorBrowsableState.Never), Browsable (false)]
  369. public bool IsReusable {
  370. get { return false; }
  371. }
  372. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  373. [Browsable (false)]
  374. public bool IsValid {
  375. get {
  376. if (!is_validated)
  377. throw new HttpException (Locale.GetText ("Page hasn't been validated."));
  378. #if NET_2_0
  379. foreach (IValidator val in Validators)
  380. if (!val.IsValid)
  381. return false;
  382. return true;
  383. #else
  384. return ValidateCollection (_validators);
  385. #endif
  386. }
  387. }
  388. #if NET_2_0
  389. public IDictionary Items {
  390. get {
  391. if (items == null)
  392. items = new Hashtable ();
  393. return items;
  394. }
  395. }
  396. #endif
  397. [EditorBrowsable (EditorBrowsableState.Never)]
  398. #if NET_2_0
  399. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  400. [BrowsableAttribute (false)]
  401. public int LCID {
  402. get { return Thread.CurrentThread.CurrentCulture.LCID; }
  403. set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
  404. }
  405. #else
  406. protected int LCID {
  407. set { Thread.CurrentThread.CurrentCulture = new CultureInfo (value); }
  408. }
  409. #endif
  410. #if NET_2_0
  411. [Browsable (false)]
  412. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  413. public bool MaintainScrollPositionOnPostBack {
  414. get { return _maintainScrollPositionOnPostBack; }
  415. set { _maintainScrollPositionOnPostBack = value; }
  416. }
  417. #endif
  418. #if NET_2_0
  419. public PageAdapter PageAdapter {
  420. get {
  421. return (PageAdapter)Adapter;
  422. }
  423. }
  424. #endif
  425. #if !TARGET_J2EE
  426. internal string theForm {
  427. get {
  428. return "theForm";
  429. }
  430. }
  431. #endif
  432. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  433. [Browsable (false)]
  434. public HttpRequest Request
  435. {
  436. get {
  437. if (_context != null)
  438. return _context.Request;
  439. throw new HttpException("Request is not available without context");
  440. }
  441. }
  442. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  443. [Browsable (false)]
  444. public HttpResponse Response
  445. {
  446. get {
  447. if (_context != null)
  448. return _context.Response;
  449. throw new HttpException ("Response is not available without context");
  450. }
  451. }
  452. [EditorBrowsable (EditorBrowsableState.Never)]
  453. #if NET_2_0
  454. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  455. [BrowsableAttribute (false)]
  456. public string ResponseEncoding
  457. {
  458. get { return Response.ContentEncoding.WebName; }
  459. set { Response.ContentEncoding = Encoding.GetEncoding (value); }
  460. }
  461. #else
  462. protected string ResponseEncoding
  463. {
  464. set { Response.ContentEncoding = Encoding.GetEncoding (value); }
  465. }
  466. #endif
  467. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  468. [Browsable (false)]
  469. public HttpServerUtility Server
  470. {
  471. get {
  472. return Context.Server;
  473. }
  474. }
  475. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  476. [Browsable (false)]
  477. public virtual HttpSessionState Session
  478. {
  479. get {
  480. if (_context == null)
  481. _context = HttpContext.Current;
  482. if (_context == null)
  483. throw new HttpException ("Session is not available without context");
  484. if (_context.Session == null)
  485. throw new HttpException ("Session state can only be used " +
  486. "when enableSessionState is set to true, either " +
  487. "in a configuration file or in the Page directive.");
  488. return _context.Session;
  489. }
  490. }
  491. #if NET_2_0
  492. [FilterableAttribute (false)]
  493. [Obsolete]
  494. #endif
  495. [Browsable (false)]
  496. public bool SmartNavigation
  497. {
  498. get { return _smartNavigation; }
  499. set { _smartNavigation = value; }
  500. }
  501. #if NET_2_0
  502. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  503. [Filterable (false)]
  504. [Browsable (false)]
  505. public virtual string StyleSheetTheme {
  506. get { return _styleSheetTheme; }
  507. set { _styleSheetTheme = value; }
  508. }
  509. [Browsable (false)]
  510. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  511. public virtual string Theme {
  512. get { return _theme; }
  513. set { _theme = value; }
  514. }
  515. void InitializeStyleSheet ()
  516. {
  517. if (_styleSheetTheme == null) {
  518. PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
  519. if (ps != null)
  520. _styleSheetTheme = ps.StyleSheetTheme;
  521. }
  522. if (_styleSheetTheme != null && _styleSheetTheme != "")
  523. _styleSheetPageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_styleSheetTheme, _context);
  524. }
  525. void InitializeTheme ()
  526. {
  527. if (_theme == null) {
  528. PagesSection ps = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
  529. if (ps != null)
  530. _theme = ps.Theme;
  531. }
  532. if (_theme != null && _theme != "") {
  533. _pageTheme = ThemeDirectoryCompiler.GetCompiledInstance (_theme, _context);
  534. _pageTheme.SetPage (this);
  535. }
  536. }
  537. #endif
  538. #if NET_2_0
  539. [Localizable (true)]
  540. [Bindable (true)]
  541. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  542. public string Title {
  543. get {
  544. if (_title == null)
  545. return htmlHeader.Title;
  546. return _title;
  547. }
  548. set {
  549. if (htmlHeader != null)
  550. htmlHeader.Title = value;
  551. else
  552. _title = value;
  553. }
  554. }
  555. #endif
  556. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  557. [Browsable (false)]
  558. public TraceContext Trace
  559. {
  560. get { return Context.Trace; }
  561. }
  562. [EditorBrowsable (EditorBrowsableState.Never)]
  563. #if NET_2_0
  564. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  565. [BrowsableAttribute (false)]
  566. public bool TraceEnabled
  567. {
  568. get { return Trace.IsEnabled; }
  569. set { Trace.IsEnabled = value; }
  570. }
  571. #else
  572. protected bool TraceEnabled
  573. {
  574. set { Trace.IsEnabled = value; }
  575. }
  576. #endif
  577. [EditorBrowsable (EditorBrowsableState.Never)]
  578. #if NET_2_0
  579. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  580. [BrowsableAttribute (false)]
  581. public TraceMode TraceModeValue
  582. {
  583. get { return Trace.TraceMode; }
  584. set { Trace.TraceMode = value; }
  585. }
  586. #else
  587. protected TraceMode TraceModeValue
  588. {
  589. set { Trace.TraceMode = value; }
  590. }
  591. #endif
  592. [EditorBrowsable (EditorBrowsableState.Never)]
  593. protected int TransactionMode
  594. {
  595. #if NET_2_0
  596. get { return _transactionMode; }
  597. #endif
  598. set { _transactionMode = value; }
  599. }
  600. #if !NET_2_0
  601. //
  602. // This method is here just to remove the warning about "_transactionMode" not being
  603. // used. We probably will use it internally at some point.
  604. //
  605. internal int GetTransactionMode ()
  606. {
  607. return _transactionMode;
  608. }
  609. #endif
  610. #if NET_2_0
  611. [EditorBrowsable (EditorBrowsableState.Advanced)]
  612. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  613. [BrowsableAttribute (false)]
  614. public string UICulture
  615. {
  616. get { return Thread.CurrentThread.CurrentUICulture.Name; }
  617. set { Thread.CurrentThread.CurrentUICulture = GetPageCulture (value, Thread.CurrentThread.CurrentUICulture); }
  618. }
  619. #else
  620. [EditorBrowsable (EditorBrowsableState.Never)]
  621. protected string UICulture
  622. {
  623. set { Thread.CurrentThread.CurrentUICulture = new CultureInfo (value); }
  624. }
  625. #endif
  626. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  627. [Browsable (false)]
  628. public IPrincipal User
  629. {
  630. get { return Context.User; }
  631. }
  632. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  633. [Browsable (false)]
  634. public ValidatorCollection Validators
  635. {
  636. get {
  637. if (_validators == null)
  638. _validators = new ValidatorCollection ();
  639. return _validators;
  640. }
  641. }
  642. [MonoTODO ("Use this when encrypting/decrypting ViewState")]
  643. [Browsable (false)]
  644. public string ViewStateUserKey {
  645. get { return viewStateUserKey; }
  646. set { viewStateUserKey = value; }
  647. }
  648. [Browsable (false)]
  649. public override bool Visible
  650. {
  651. get { return base.Visible; }
  652. set { base.Visible = value; }
  653. }
  654. #endregion
  655. #region Methods
  656. #if NET_2_0
  657. CultureInfo GetPageCulture (string culture, CultureInfo deflt)
  658. {
  659. if (culture == null)
  660. return deflt;
  661. CultureInfo ret = null;
  662. if (culture.StartsWith ("auto", StringComparison.InvariantCultureIgnoreCase)) {
  663. #if TARGET_J2EE
  664. if (Context.IsPortletRequest)
  665. return deflt;
  666. #endif
  667. string[] languages = Request.UserLanguages;
  668. try {
  669. if (languages != null && languages.Length > 0)
  670. ret = CultureInfo.CreateSpecificCulture (languages[0]);
  671. } catch {
  672. }
  673. if (ret == null)
  674. ret = deflt;
  675. } else
  676. ret = CultureInfo.CreateSpecificCulture (culture);
  677. return ret;
  678. }
  679. #endif
  680. [EditorBrowsable (EditorBrowsableState.Never)]
  681. protected IAsyncResult AspCompatBeginProcessRequest (HttpContext context,
  682. AsyncCallback cb,
  683. object extraData)
  684. {
  685. throw new NotImplementedException ();
  686. }
  687. [EditorBrowsable (EditorBrowsableState.Never)]
  688. protected void AspCompatEndProcessRequest (IAsyncResult result)
  689. {
  690. throw new NotImplementedException ();
  691. }
  692. [EditorBrowsable (EditorBrowsableState.Advanced)]
  693. protected virtual HtmlTextWriter CreateHtmlTextWriter (TextWriter tw)
  694. {
  695. return new HtmlTextWriter (tw);
  696. }
  697. [EditorBrowsable (EditorBrowsableState.Never)]
  698. public void DesignerInitialize ()
  699. {
  700. InitRecursive (null);
  701. }
  702. [EditorBrowsable (EditorBrowsableState.Advanced)]
  703. protected virtual NameValueCollection DeterminePostBackMode ()
  704. {
  705. if (_context == null)
  706. return null;
  707. HttpRequest req = _context.Request;
  708. if (req == null)
  709. return null;
  710. NameValueCollection coll = null;
  711. if (0 == String.Compare (Request.HttpMethod, "POST", true, CultureInfo.InvariantCulture))
  712. coll = req.Form;
  713. #if TARGET_J2EE
  714. else if (IsPortletRender && req.Form ["__VIEWSTATE"] != null)
  715. coll = req.Form;
  716. #endif
  717. else
  718. coll = req.QueryString;
  719. WebROCollection c = (WebROCollection) coll;
  720. allow_load = !c.GotID;
  721. if (allow_load)
  722. c.ID = GetTypeHashCode ();
  723. else
  724. allow_load = (c.ID == GetTypeHashCode ());
  725. if (coll != null && coll ["__VIEWSTATE"] == null && coll ["__EVENTTARGET"] == null)
  726. return null;
  727. return coll;
  728. }
  729. #if NET_2_0
  730. public override Control FindControl (string id) {
  731. if (id == ID)
  732. return this;
  733. else
  734. return base.FindControl (id);
  735. }
  736. #endif
  737. #if NET_2_0
  738. [Obsolete]
  739. #endif
  740. [EditorBrowsable (EditorBrowsableState.Advanced)]
  741. public string GetPostBackClientEvent (Control control, string argument)
  742. {
  743. return scriptManager.GetPostBackEventReference (control, argument);
  744. }
  745. #if NET_2_0
  746. [Obsolete]
  747. #endif
  748. [EditorBrowsable (EditorBrowsableState.Advanced)]
  749. public string GetPostBackClientHyperlink (Control control, string argument)
  750. {
  751. return scriptManager.GetPostBackClientHyperlink (control, argument);
  752. }
  753. #if NET_2_0
  754. [Obsolete]
  755. #endif
  756. [EditorBrowsable (EditorBrowsableState.Advanced)]
  757. public string GetPostBackEventReference (Control control)
  758. {
  759. return scriptManager.GetPostBackEventReference (control, "");
  760. }
  761. #if NET_2_0
  762. [Obsolete]
  763. #endif
  764. [EditorBrowsable (EditorBrowsableState.Advanced)]
  765. public string GetPostBackEventReference (Control control, string argument)
  766. {
  767. return scriptManager.GetPostBackEventReference (control, argument);
  768. }
  769. internal void RequiresPostBackScript ()
  770. {
  771. #if NET_2_0
  772. if (requiresPostBackScript)
  773. return;
  774. ClientScript.RegisterHiddenField (postEventSourceID, String.Empty);
  775. ClientScript.RegisterHiddenField (postEventArgumentID, String.Empty);
  776. #endif
  777. requiresPostBackScript = true;
  778. }
  779. [EditorBrowsable (EditorBrowsableState.Never)]
  780. public virtual int GetTypeHashCode ()
  781. {
  782. return 0;
  783. }
  784. #if NET_2_0
  785. [MonoTODO("The following properties of OutputCacheParameters are silently ignored: CacheProfile, NoStore, SqlDependency")]
  786. protected internal virtual void InitOutputCache(OutputCacheParameters cacheSettings)
  787. {
  788. if (cacheSettings.Enabled)
  789. InitOutputCache(cacheSettings.Duration,
  790. cacheSettings.VaryByHeader,
  791. cacheSettings.VaryByCustom,
  792. cacheSettings.Location,
  793. cacheSettings.VaryByParam);
  794. }
  795. #endif
  796. [EditorBrowsable (EditorBrowsableState.Never)]
  797. protected virtual void InitOutputCache (int duration,
  798. string varyByHeader,
  799. string varyByCustom,
  800. OutputCacheLocation location,
  801. string varyByParam)
  802. {
  803. HttpCachePolicy cache = _context.Response.Cache;
  804. bool set_vary = false;
  805. switch (location) {
  806. case OutputCacheLocation.Any:
  807. cache.SetCacheability (HttpCacheability.Public);
  808. cache.SetMaxAge (new TimeSpan (0, 0, duration));
  809. cache.SetLastModified (_context.Timestamp);
  810. set_vary = true;
  811. break;
  812. case OutputCacheLocation.Client:
  813. cache.SetCacheability (HttpCacheability.Private);
  814. cache.SetMaxAge (new TimeSpan (0, 0, duration));
  815. cache.SetLastModified (_context.Timestamp);
  816. break;
  817. case OutputCacheLocation.Downstream:
  818. cache.SetCacheability (HttpCacheability.Public);
  819. cache.SetMaxAge (new TimeSpan (0, 0, duration));
  820. cache.SetLastModified (_context.Timestamp);
  821. break;
  822. case OutputCacheLocation.Server:
  823. cache.SetCacheability (HttpCacheability.Server);
  824. set_vary = true;
  825. break;
  826. case OutputCacheLocation.None:
  827. break;
  828. }
  829. if (set_vary) {
  830. if (varyByCustom != null)
  831. cache.SetVaryByCustom (varyByCustom);
  832. if (varyByParam != null && varyByParam.Length > 0) {
  833. string[] prms = varyByParam.Split (';');
  834. foreach (string p in prms)
  835. cache.VaryByParams [p.Trim ()] = true;
  836. cache.VaryByParams.IgnoreParams = false;
  837. } else {
  838. cache.VaryByParams.IgnoreParams = true;
  839. }
  840. if (varyByHeader != null && varyByHeader.Length > 0) {
  841. string[] hdrs = varyByHeader.Split (';');
  842. foreach (string h in hdrs)
  843. cache.VaryByHeaders [h.Trim ()] = true;
  844. }
  845. }
  846. cache.Duration = duration;
  847. cache.SetExpires (_context.Timestamp.AddSeconds (duration));
  848. }
  849. #if NET_2_0
  850. [Obsolete]
  851. #else
  852. [EditorBrowsable (EditorBrowsableState.Advanced)]
  853. #endif
  854. public bool IsClientScriptBlockRegistered (string key)
  855. {
  856. return scriptManager.IsClientScriptBlockRegistered (key);
  857. }
  858. #if NET_2_0
  859. [Obsolete]
  860. #else
  861. [EditorBrowsable (EditorBrowsableState.Advanced)]
  862. #endif
  863. public bool IsStartupScriptRegistered (string key)
  864. {
  865. return scriptManager.IsStartupScriptRegistered (key);
  866. }
  867. public string MapPath (string virtualPath)
  868. {
  869. return Request.MapPath (virtualPath);
  870. }
  871. #if NET_2_0
  872. protected internal override void Render (HtmlTextWriter writer) {
  873. if (MaintainScrollPositionOnPostBack) {
  874. ClientScript.RegisterWebFormClientScript ();
  875. ClientScript.RegisterHiddenField (ScrollPositionXID, Request [ScrollPositionXID]);
  876. ClientScript.RegisterHiddenField (ScrollPositionYID, Request [ScrollPositionYID]);
  877. StringBuilder script = new StringBuilder ();
  878. script.AppendLine ("<script type=\"text/javascript\">");
  879. script.AppendLine ("<!--");
  880. script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
  881. script.AppendLine (theForm + ".submit = WebForm_SaveScrollPositionSubmit;");
  882. script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
  883. script.AppendLine (theForm + ".onsubmit = WebForm_SaveScrollPositionOnSubmit;");
  884. if (IsPostBack) {
  885. script.AppendLine (theForm + ".oldOnLoad = window.onload;");
  886. script.AppendLine ("window.onload = function () { WebForm_RestoreScrollPosition (" + theForm + "); };");
  887. }
  888. script.AppendLine ("// -->");
  889. script.AppendLine ("</script>");
  890. ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
  891. }
  892. base.Render (writer);
  893. }
  894. #endif
  895. private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
  896. {
  897. #if ONLY_1_1
  898. writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
  899. writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
  900. #endif
  901. writer.WriteLine ();
  902. ClientScript.WriteBeginScriptBlock (writer);
  903. #if ONLY_1_1
  904. RenderClientScriptFormDeclaration (writer, formUniqueID);
  905. #endif
  906. writer.WriteLine ("function __doPostBack(eventTarget, eventArgument) {");
  907. writer.WriteLine ("\tvar currForm = {0};", theForm);
  908. #if NET_2_0
  909. writer.WriteLine ("\tcurrForm.__doPostBack(eventTarget, eventArgument);");
  910. writer.WriteLine ("}");
  911. writer.WriteLine ("{0}.__doPostBack = function (eventTarget, eventArgument) {{", theForm);
  912. writer.WriteLine ("\tvar currForm = this;");
  913. writer.WriteLine ("\tif(currForm.onsubmit && currForm.onsubmit() == false) return;");
  914. #else
  915. writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
  916. #endif
  917. writer.WriteLine ("\tcurrForm.{0}.value = eventTarget;", postEventSourceID);
  918. writer.WriteLine ("\tcurrForm.{0}.value = eventArgument;", postEventArgumentID);
  919. writer.WriteLine ("\tcurrForm.submit();");
  920. writer.WriteLine ("}");
  921. ClientScript.WriteEndScriptBlock (writer);
  922. }
  923. void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
  924. {
  925. writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
  926. writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
  927. writer.WriteLine ("\t{0}.isAspForm = true;", theForm);
  928. #if TARGET_J2EE
  929. string serverUrl = Context.ServletResponse.encodeURL (Request.RawUrl);
  930. writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
  931. #endif
  932. }
  933. internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
  934. {
  935. if (renderingForm)
  936. throw new HttpException ("Only 1 HtmlForm is allowed per page.");
  937. renderingForm = true;
  938. writer.WriteLine ();
  939. #if NET_2_0
  940. ClientScript.WriteBeginScriptBlock (writer);
  941. RenderClientScriptFormDeclaration (writer, formUniqueID);
  942. ClientScript.WriteEndScriptBlock (writer);
  943. #endif
  944. if (handleViewState)
  945. scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
  946. scriptManager.WriteHiddenFields (writer);
  947. if (requiresPostBackScript) {
  948. RenderPostBackScript (writer, formUniqueID);
  949. postBackScriptRendered = true;
  950. }
  951. scriptManager.WriteClientScriptIncludes (writer);
  952. scriptManager.WriteClientScriptBlocks (writer);
  953. }
  954. internal IStateFormatter GetFormatter ()
  955. {
  956. return new ObjectStateFormatter (this);
  957. }
  958. internal string GetSavedViewState ()
  959. {
  960. return _savedViewState;
  961. }
  962. internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
  963. {
  964. if (!postBackScriptRendered && requiresPostBackScript)
  965. RenderPostBackScript (writer, formUniqueID);
  966. scriptManager.WriteArrayDeclares (writer);
  967. #if NET_2_0
  968. scriptManager.SaveEventValidationState ();
  969. scriptManager.WriteExpandoAttributes (writer);
  970. #endif
  971. scriptManager.WriteHiddenFields (writer);
  972. scriptManager.WriteClientScriptIncludes (writer);
  973. scriptManager.WriteStartupScriptBlocks (writer);
  974. renderingForm = false;
  975. postBackScriptRendered = false;
  976. }
  977. private void ProcessPostData (NameValueCollection data, bool second)
  978. {
  979. if (data != null) {
  980. Hashtable used = new Hashtable ();
  981. foreach (string id in data.AllKeys){
  982. if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID)
  983. continue;
  984. string real_id = id;
  985. int dot = real_id.IndexOf ('.');
  986. if (dot >= 1)
  987. real_id = real_id.Substring (0, dot);
  988. if (real_id == null || used.ContainsKey (real_id))
  989. continue;
  990. used.Add (real_id, real_id);
  991. Control ctrl = FindControl (real_id);
  992. if (ctrl != null){
  993. IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
  994. IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
  995. if (pbdh == null) {
  996. if (pbeh != null)
  997. RegisterRequiresRaiseEvent (pbeh);
  998. continue;
  999. }
  1000. if (pbdh.LoadPostData (real_id, data) == true) {
  1001. if (requiresPostDataChanged == null)
  1002. requiresPostDataChanged = new ArrayList ();
  1003. requiresPostDataChanged.Add (pbdh);
  1004. }
  1005. if (_requiresPostBackCopy != null)
  1006. _requiresPostBackCopy.Remove (real_id);
  1007. } else if (!second) {
  1008. if (secondPostData == null)
  1009. secondPostData = new NameValueCollection ();
  1010. secondPostData.Add (real_id, data [id]);
  1011. }
  1012. }
  1013. }
  1014. ArrayList list1 = null;
  1015. if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
  1016. string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
  1017. foreach (string id in handlers) {
  1018. IPostBackDataHandler pbdh = FindControl (id) as IPostBackDataHandler;
  1019. if (pbdh != null) {
  1020. _requiresPostBackCopy.Remove (id);
  1021. if (pbdh.LoadPostData (id, data)) {
  1022. if (requiresPostDataChanged == null)
  1023. requiresPostDataChanged = new ArrayList ();
  1024. requiresPostDataChanged.Add (pbdh);
  1025. }
  1026. } else if (!second) {
  1027. if (list1 == null)
  1028. list1 = new ArrayList ();
  1029. list1.Add (id);
  1030. }
  1031. }
  1032. }
  1033. _requiresPostBackCopy = second ? null : list1;
  1034. if (second)
  1035. secondPostData = null;
  1036. }
  1037. [EditorBrowsable (EditorBrowsableState.Never)]
  1038. #if NET_2_0
  1039. public virtual void ProcessRequest (HttpContext context)
  1040. #else
  1041. public void ProcessRequest (HttpContext context)
  1042. #endif
  1043. {
  1044. #if NET_2_0
  1045. _lifeCycle = PageLifeCycle.Unknown;
  1046. #endif
  1047. _context = context;
  1048. if (clientTarget != null)
  1049. Request.ClientTarget = clientTarget;
  1050. WireupAutomaticEvents ();
  1051. //-- Control execution lifecycle in the docs
  1052. // Save culture information because it can be modified in FrameworkInitialize()
  1053. CultureInfo culture = Thread.CurrentThread.CurrentCulture;
  1054. CultureInfo uiculture = Thread.CurrentThread.CurrentUICulture;
  1055. FrameworkInitialize ();
  1056. context.ErrorPage = _errorPage;
  1057. try {
  1058. InternalProcessRequest ();
  1059. } catch (ThreadAbortException) {
  1060. // Do nothing, just ignore it by now.
  1061. } catch (Exception e) {
  1062. context.AddError (e); // OnError might access LastError
  1063. OnError (EventArgs.Empty);
  1064. context.ClearError (e);
  1065. // We want to remove that error, as we're rethrowing to stop
  1066. // further processing.
  1067. Trace.Warn ("Unhandled Exception", e.ToString (), e);
  1068. throw;
  1069. } finally {
  1070. try {
  1071. #if NET_2_0
  1072. _lifeCycle = PageLifeCycle.Unload;
  1073. #endif
  1074. RenderTrace ();
  1075. UnloadRecursive (true);
  1076. #if NET_2_0
  1077. _lifeCycle = PageLifeCycle.End;
  1078. #endif
  1079. } catch {}
  1080. if (Thread.CurrentThread.CurrentCulture.Equals (culture) == false)
  1081. Thread.CurrentThread.CurrentCulture = culture;
  1082. if (Thread.CurrentThread.CurrentUICulture.Equals (uiculture) == false)
  1083. Thread.CurrentThread.CurrentUICulture = uiculture;
  1084. }
  1085. }
  1086. #if NET_2_0
  1087. delegate void ProcessRequestDelegate (HttpContext context);
  1088. private sealed class DummyAsyncResult : IAsyncResult
  1089. {
  1090. readonly object state;
  1091. readonly WaitHandle asyncWaitHandle;
  1092. readonly bool completedSynchronously;
  1093. readonly bool isCompleted;
  1094. public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
  1095. {
  1096. this.isCompleted = isCompleted;
  1097. this.completedSynchronously = completedSynchronously;
  1098. this.state = state;
  1099. if (isCompleted) {
  1100. asyncWaitHandle = new ManualResetEvent (true);
  1101. }
  1102. else {
  1103. asyncWaitHandle = new ManualResetEvent (false);
  1104. }
  1105. }
  1106. #region IAsyncResult Members
  1107. public object AsyncState {
  1108. get { return state; }
  1109. }
  1110. public WaitHandle AsyncWaitHandle {
  1111. get { return asyncWaitHandle; }
  1112. }
  1113. public bool CompletedSynchronously {
  1114. get { return completedSynchronously; }
  1115. }
  1116. public bool IsCompleted {
  1117. get { return isCompleted; }
  1118. }
  1119. #endregion
  1120. }
  1121. protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
  1122. {
  1123. ProcessRequest (context);
  1124. DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
  1125. if (callback != null) {
  1126. callback (asyncResult);
  1127. }
  1128. return asyncResult;
  1129. }
  1130. protected void AsyncPageEndProcessRequest (IAsyncResult result)
  1131. {
  1132. }
  1133. internal void ProcessCrossPagePostBack (HttpContext context)
  1134. {
  1135. isCrossPagePostBack = true;
  1136. ProcessRequest (context);
  1137. }
  1138. #endif
  1139. void InternalProcessRequest ()
  1140. {
  1141. _requestValueCollection = this.DeterminePostBackMode();
  1142. #if NET_2_0
  1143. _lifeCycle = PageLifeCycle.Start;
  1144. // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
  1145. if (_requestValueCollection != null) {
  1146. if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
  1147. _doLoadPreviousPage = true;
  1148. }
  1149. else {
  1150. isCallback = _requestValueCollection [CallbackArgumentID] != null;
  1151. // LAMESPEC: on Callback IsPostBack is set to false, but true.
  1152. //isPostBack = !isCallback;
  1153. isPostBack = true;
  1154. }
  1155. string lastFocus = _requestValueCollection [LastFocusID];
  1156. if (!String.IsNullOrEmpty (lastFocus)) {
  1157. _focusedControlID = UniqueID2ClientID (lastFocus);
  1158. }
  1159. }
  1160. // if request was transfered from other page - track Prev. Page
  1161. previousPage = _context.LastPage;
  1162. _context.LastPage = this;
  1163. _lifeCycle = PageLifeCycle.PreInit;
  1164. OnPreInit (EventArgs.Empty);
  1165. InitializeTheme ();
  1166. ApplyMasterPage ();
  1167. _lifeCycle = PageLifeCycle.Init;
  1168. #endif
  1169. Trace.Write ("aspx.page", "Begin Init");
  1170. InitRecursive (null);
  1171. Trace.Write ("aspx.page", "End Init");
  1172. #if NET_2_0
  1173. _lifeCycle = PageLifeCycle.InitComplete;
  1174. OnInitComplete (EventArgs.Empty);
  1175. #endif
  1176. renderingForm = false;
  1177. #if NET_2_0
  1178. if (IsPostBack || IsCallback) {
  1179. _lifeCycle = PageLifeCycle.PreLoad;
  1180. if (_requestValueCollection != null)
  1181. scriptManager.RestoreEventValidationState (_requestValueCollection [scriptManager.EventStateFieldName]);
  1182. #else
  1183. if (IsPostBack) {
  1184. #endif
  1185. Trace.Write ("aspx.page", "Begin LoadViewState");
  1186. LoadPageViewState ();
  1187. Trace.Write ("aspx.page", "End LoadViewState");
  1188. Trace.Write ("aspx.page", "Begin ProcessPostData");
  1189. ProcessPostData (_requestValueCollection, false);
  1190. Trace.Write ("aspx.page", "End ProcessPostData");
  1191. }
  1192. #if NET_2_0
  1193. OnPreLoad (EventArgs.Empty);
  1194. _lifeCycle = PageLifeCycle.Load;
  1195. #endif
  1196. LoadRecursive ();
  1197. #if NET_2_0
  1198. if (IsPostBack || IsCallback) {
  1199. _lifeCycle = PageLifeCycle.ControlEvents;
  1200. #else
  1201. if (IsPostBack) {
  1202. #endif
  1203. Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
  1204. ProcessPostData (secondPostData, true);
  1205. Trace.Write ("aspx.page", "End ProcessPostData Second Try");
  1206. Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
  1207. RaiseChangedEvents ();
  1208. Trace.Write ("aspx.page", "End Raise ChangedEvents");
  1209. Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
  1210. RaisePostBackEvents ();
  1211. Trace.Write ("aspx.page", "End Raise PostBackEvent");
  1212. }
  1213. #if NET_2_0
  1214. _lifeCycle = PageLifeCycle.LoadComplete;
  1215. OnLoadComplete (EventArgs.Empty);
  1216. if (IsCrossPagePostBack)
  1217. return;
  1218. if (IsCallback) {
  1219. string result = ProcessCallbackData ();
  1220. HtmlTextWriter callbackOutput = new HtmlTextWriter (_context.Response.Output);
  1221. callbackOutput.Write (result);
  1222. callbackOutput.Flush ();
  1223. return;
  1224. }
  1225. _lifeCycle = PageLifeCycle.PreRender;
  1226. #endif
  1227. Trace.Write ("aspx.page", "Begin PreRender");
  1228. PreRenderRecursiveInternal ();
  1229. Trace.Write ("aspx.page", "End PreRender");
  1230. #if NET_2_0
  1231. ExecuteRegisteredAsyncTasks ();
  1232. _lifeCycle = PageLifeCycle.PreRenderComplete;
  1233. OnPreRenderComplete (EventArgs.Empty);
  1234. #endif
  1235. Trace.Write ("aspx.page", "Begin SaveViewState");
  1236. SavePageViewState ();
  1237. Trace.Write ("aspx.page", "End SaveViewState");
  1238. #if NET_2_0
  1239. _lifeCycle = PageLifeCycle.SaveStateComplete;
  1240. OnSaveStateComplete (EventArgs.Empty);
  1241. #if TARGET_J2EE
  1242. if (OnSaveStateCompleteForPortlet ())
  1243. return;
  1244. #endif // TARGET_J2EE
  1245. #endif // NET_2_0
  1246. #if NET_2_0
  1247. _lifeCycle = PageLifeCycle.Render;
  1248. #endif
  1249. //--
  1250. Trace.Write ("aspx.page", "Begin Render");
  1251. HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
  1252. RenderControl (output);
  1253. Trace.Write ("aspx.page", "End Render");
  1254. }
  1255. private void RenderTrace ()
  1256. {
  1257. TraceManager traceManager = HttpRuntime.TraceManager;
  1258. if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
  1259. return;
  1260. Trace.SaveData ();
  1261. if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
  1262. return;
  1263. if (!traceManager.LocalOnly || Context.Request.IsLocal) {
  1264. HtmlTextWriter output = new HtmlTextWriter (_context.Response.Output);
  1265. Trace.Render (output);
  1266. }
  1267. }
  1268. #if NET_2_0
  1269. bool CheckForValidationSupport (Control targetControl)
  1270. {
  1271. if (targetControl == null)
  1272. return false;
  1273. Type type = targetControl.GetType ();
  1274. object[] attributes = type.GetCustomAttributes (false);
  1275. foreach (object attr in attributes)
  1276. if (attr is SupportsEventValidationAttribute)
  1277. return true;
  1278. return false;
  1279. }
  1280. #endif
  1281. void RaisePostBackEvents ()
  1282. {
  1283. #if NET_2_0
  1284. Control targetControl;
  1285. #endif
  1286. if (requiresRaiseEvent != null) {
  1287. RaisePostBackEvent (requiresRaiseEvent, null);
  1288. return;
  1289. }
  1290. NameValueCollection postdata = _requestValueCollection;
  1291. if (postdata == null)
  1292. return;
  1293. string eventTarget = postdata [postEventSourceID];
  1294. if (eventTarget == null || eventTarget.Length == 0) {
  1295. Validate ();
  1296. return;
  1297. }
  1298. #if NET_2_0
  1299. targetControl = FindControl (eventTarget);
  1300. IPostBackEventHandler target = targetControl as IPostBackEventHandler;
  1301. #else
  1302. IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
  1303. #endif
  1304. if (target == null)
  1305. return;
  1306. string eventArgument = postdata [postEventArgumentID];
  1307. RaisePostBackEvent (target, eventArgument);
  1308. }
  1309. internal void RaiseChangedEvents ()
  1310. {
  1311. if (requiresPostDataChanged == null)
  1312. return;
  1313. foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
  1314. ipdh.RaisePostDataChangedEvent ();
  1315. requiresPostDataChanged = null;
  1316. }
  1317. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1318. protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
  1319. {
  1320. #if NET_2_0
  1321. Control targetControl = sourceControl as Control;
  1322. if (targetControl != null && CheckForValidationSupport (targetControl))
  1323. scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
  1324. #endif
  1325. sourceControl.RaisePostBackEvent (eventArgument);
  1326. }
  1327. #if NET_2_0
  1328. [Obsolete]
  1329. #endif
  1330. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1331. public void RegisterArrayDeclaration (string arrayName, string arrayValue)
  1332. {
  1333. scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
  1334. }
  1335. #if NET_2_0
  1336. [Obsolete]
  1337. #endif
  1338. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1339. public virtual void RegisterClientScriptBlock (string key, string script)
  1340. {
  1341. scriptManager.RegisterClientScriptBlock (key, script);
  1342. }
  1343. #if NET_2_0
  1344. [Obsolete]
  1345. #endif
  1346. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1347. public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
  1348. {
  1349. scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  1350. }
  1351. [MonoTODO("Not implemented, Used in HtmlForm")]
  1352. internal void RegisterClientScriptFile (string a, string b, string c)
  1353. {
  1354. throw new NotImplementedException ();
  1355. }
  1356. #if NET_2_0
  1357. [Obsolete]
  1358. #endif
  1359. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1360. public void RegisterOnSubmitStatement (string key, string script)
  1361. {
  1362. scriptManager.RegisterOnSubmitStatement (key, script);
  1363. }
  1364. internal string GetSubmitStatements ()
  1365. {
  1366. return scriptManager.WriteSubmitStatements ();
  1367. }
  1368. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1369. public void RegisterRequiresPostBack (Control control)
  1370. {
  1371. #if NET_2_0
  1372. if (!(control is IPostBackDataHandler))
  1373. throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
  1374. #endif
  1375. if (_requiresPostBack == null)
  1376. _requiresPostBack = new ArrayList ();
  1377. if (_requiresPostBack.Contains (control.UniqueID))
  1378. return;
  1379. _requiresPostBack.Add (control.UniqueID);
  1380. }
  1381. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1382. public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
  1383. {
  1384. requiresRaiseEvent = control;
  1385. }
  1386. #if NET_2_0
  1387. [Obsolete]
  1388. #endif
  1389. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1390. public virtual void RegisterStartupScript (string key, string script)
  1391. {
  1392. scriptManager.RegisterStartupScript (key, script);
  1393. }
  1394. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1395. public void RegisterViewStateHandler ()
  1396. {
  1397. handleViewState = true;
  1398. }
  1399. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1400. protected virtual void SavePageStateToPersistenceMedium (object viewState)
  1401. {
  1402. PageStatePersister persister = this.PageStatePersister;
  1403. if (persister == null)
  1404. return;
  1405. Pair pair = viewState as Pair;
  1406. if (pair != null) {
  1407. persister.ViewState = pair.First;
  1408. persister.ControlState = pair.Second;
  1409. } else
  1410. persister.ViewState = viewState;
  1411. persister.Save ();
  1412. }
  1413. internal string RawViewState {
  1414. get {
  1415. NameValueCollection postdata = _requestValueCollection;
  1416. string view_state;
  1417. if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
  1418. return null;
  1419. if (view_state == "")
  1420. return null;
  1421. return view_state;
  1422. }
  1423. set { _savedViewState = value; }
  1424. }
  1425. #if NET_2_0
  1426. protected virtual
  1427. #else
  1428. internal
  1429. #endif
  1430. PageStatePersister PageStatePersister {
  1431. get {
  1432. if (page_state_persister == null)
  1433. page_state_persister = new HiddenFieldPageStatePersister (this);
  1434. return page_state_persister;
  1435. }
  1436. }
  1437. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1438. protected virtual object LoadPageStateFromPersistenceMedium ()
  1439. {
  1440. PageStatePersister persister = this.PageStatePersister;
  1441. if (persister == null)
  1442. return null;
  1443. persister.Load ();
  1444. return new Pair (persister.ViewState, persister.ControlState);
  1445. }
  1446. internal void LoadPageViewState()
  1447. {
  1448. Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
  1449. if (sState != null) {
  1450. if (allow_load) {
  1451. #if NET_2_0
  1452. LoadPageControlState (sState.Second);
  1453. #endif
  1454. Pair vsr = sState.First as Pair;
  1455. if (vsr != null) {
  1456. LoadViewStateRecursive (vsr.First);
  1457. _requiresPostBackCopy = vsr.Second as ArrayList;
  1458. }
  1459. }
  1460. }
  1461. }
  1462. internal void SavePageViewState ()
  1463. {
  1464. if (!handleViewState)
  1465. return;
  1466. #if NET_2_0
  1467. object controlState = SavePageControlState ();
  1468. #endif
  1469. object viewState = SaveViewStateRecursive ();
  1470. object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
  1471. Pair vsr = null;
  1472. if (viewState != null || reqPostback != null)
  1473. vsr = new Pair (viewState, reqPostback);
  1474. Pair pair = new Pair ();
  1475. pair.First = vsr;
  1476. #if NET_2_0
  1477. pair.Second = controlState;
  1478. #else
  1479. pair.Second = null;
  1480. #endif
  1481. if (pair.First == null && pair.Second == null)
  1482. SavePageStateToPersistenceMedium (null);
  1483. else
  1484. SavePageStateToPersistenceMedium (pair);
  1485. }
  1486. public virtual void Validate ()
  1487. {
  1488. is_validated = true;
  1489. ValidateCollection (_validators);
  1490. }
  1491. #if NET_2_0
  1492. internal bool AreValidatorsUplevel () {
  1493. return AreValidatorsUplevel (String.Empty);
  1494. }
  1495. internal bool AreValidatorsUplevel (string valGroup)
  1496. #else
  1497. internal virtual bool AreValidatorsUplevel ()
  1498. #endif
  1499. {
  1500. bool uplevel = false;
  1501. foreach (IValidator v in Validators) {
  1502. BaseValidator bv = v as BaseValidator;
  1503. if (bv == null) continue;
  1504. #if NET_2_0
  1505. if (valGroup != bv.ValidationGroup)
  1506. continue;
  1507. #endif
  1508. if (bv.GetRenderUplevel()) {
  1509. uplevel = true;
  1510. break;
  1511. }
  1512. }
  1513. return uplevel;
  1514. }
  1515. bool ValidateCollection (ValidatorCollection validators)
  1516. {
  1517. #if NET_2_0
  1518. if (!_eventValidation)
  1519. return true;
  1520. #endif
  1521. if (validators == null || validators.Count == 0)
  1522. return true;
  1523. bool all_valid = true;
  1524. foreach (IValidator v in validators){
  1525. v.Validate ();
  1526. if (v.IsValid == false)
  1527. all_valid = false;
  1528. }
  1529. return all_valid;
  1530. }
  1531. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1532. public virtual void VerifyRenderingInServerForm (Control control)
  1533. {
  1534. if (_context == null)
  1535. return;
  1536. #if NET_2_0
  1537. if (IsCallback)
  1538. return;
  1539. #endif
  1540. if (!renderingForm)
  1541. throw new HttpException ("Control '" +
  1542. control.ClientID +
  1543. "' of type '" +
  1544. control.GetType ().Name +
  1545. "' must be placed inside a form tag with runat=server.");
  1546. }
  1547. protected override void FrameworkInitialize ()
  1548. {
  1549. base.FrameworkInitialize ();
  1550. #if NET_2_0
  1551. InitializeStyleSheet ();
  1552. #endif
  1553. }
  1554. #endregion
  1555. #if NET_2_0
  1556. public
  1557. #else
  1558. internal
  1559. #endif
  1560. ClientScriptManager ClientScript {
  1561. get { return scriptManager; }
  1562. }
  1563. #if NET_2_0
  1564. static readonly object InitCompleteEvent = new object ();
  1565. static readonly object LoadCompleteEvent = new object ();
  1566. static readonly object PreInitEvent = new object ();
  1567. static readonly object PreLoadEvent = new object ();
  1568. static readonly object PreRenderCompleteEvent = new object ();
  1569. static readonly object SaveStateCompleteEvent = new object ();
  1570. int event_mask;
  1571. const int initcomplete_mask = 1;
  1572. const int loadcomplete_mask = 1 << 1;
  1573. const int preinit_mask = 1 << 2;
  1574. const int preload_mask = 1 << 3;
  1575. const int prerendercomplete_mask = 1 << 4;
  1576. const int savestatecomplete_mask = 1 << 5;
  1577. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1578. public event EventHandler InitComplete {
  1579. add {
  1580. event_mask |= initcomplete_mask;
  1581. Events.AddHandler (InitCompleteEvent, value);
  1582. }
  1583. remove { Events.RemoveHandler (InitCompleteEvent, value); }
  1584. }
  1585. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1586. public event EventHandler LoadComplete {
  1587. add {
  1588. event_mask |= loadcomplete_mask;
  1589. Events.AddHandler (LoadCompleteEvent, value);
  1590. }
  1591. remove { Events.RemoveHandler (LoadCompleteEvent, value); }
  1592. }
  1593. public event EventHandler PreInit {
  1594. add {
  1595. event_mask |= preinit_mask;
  1596. Events.AddHandler (PreInitEvent, value);
  1597. }
  1598. remove { Events.RemoveHandler (PreInitEvent, value); }
  1599. }
  1600. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1601. public event EventHandler PreLoad {
  1602. add {
  1603. event_mask |= preload_mask;
  1604. Events.AddHandler (PreLoadEvent, value);
  1605. }
  1606. remove { Events.RemoveHandler (PreLoadEvent, value); }
  1607. }
  1608. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1609. public event EventHandler PreRenderComplete {
  1610. add {
  1611. event_mask |= prerendercomplete_mask;
  1612. Events.AddHandler (PreRenderCompleteEvent, value);
  1613. }
  1614. remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
  1615. }
  1616. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1617. public event EventHandler SaveStateComplete {
  1618. add {
  1619. event_mask |= savestatecomplete_mask;
  1620. Events.AddHandler (SaveStateCompleteEvent, value);
  1621. }
  1622. remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
  1623. }
  1624. protected virtual void OnInitComplete (EventArgs e)
  1625. {
  1626. if ((event_mask & initcomplete_mask) != 0) {
  1627. EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
  1628. if (eh != null) eh (this, e);
  1629. }
  1630. }
  1631. protected virtual void OnLoadComplete (EventArgs e)
  1632. {
  1633. if ((event_mask & loadcomplete_mask) != 0) {
  1634. EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
  1635. if (eh != null) eh (this, e);
  1636. }
  1637. }
  1638. protected virtual void OnPreInit (EventArgs e)
  1639. {
  1640. if ((event_mask & preinit_mask) != 0) {
  1641. EventHandler eh = (EventHandler) (Events [PreInitEvent]);
  1642. if (eh != null) eh (this, e);
  1643. }
  1644. }
  1645. protected virtual void OnPreLoad (EventArgs e)
  1646. {
  1647. if ((event_mask & preload_mask) != 0) {
  1648. EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
  1649. if (eh != null) eh (this, e);
  1650. }
  1651. }
  1652. protected virtual void OnPreRenderComplete (EventArgs e)
  1653. {
  1654. if ((event_mask & prerendercomplete_mask) != 0) {
  1655. EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
  1656. if (eh != null) eh (this, e);
  1657. }
  1658. if (Form == null)
  1659. return;
  1660. if (!Form.DetermineRenderUplevel ())
  1661. return;
  1662. /* figure out if we have some control we're going to focus */
  1663. if (String.IsNullOrEmpty (_focusedControlID)) {
  1664. _focusedControlID = Form.DefaultFocus;
  1665. if (String.IsNullOrEmpty (_focusedControlID))
  1666. _focusedControlID = Form.DefaultButton;
  1667. }
  1668. if (!String.IsNullOrEmpty (_focusedControlID)) {
  1669. ClientScript.RegisterWebFormClientScript ();
  1670. ClientScript.RegisterStartupScript ("HtmlForm-DefaultButton-StartupScript",
  1671. String.Format ("<script type=\"text/javascript\">\n" +
  1672. "<!--\n" +
  1673. "WebForm_AutoFocus('{0}');// -->\n" +
  1674. "</script>\n", _focusedControlID));
  1675. }
  1676. if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
  1677. ClientScript.RegisterWebFormClientScript ();
  1678. ClientScript.RegisterOnSubmitStatement ("HtmlForm-SubmitDisabledControls-SubmitStatement",
  1679. "WebForm_ReEnableControls(this);");
  1680. }
  1681. }
  1682. internal void RegisterEnabledControl (Control control)
  1683. {
  1684. if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
  1685. return;
  1686. _hasEnabledControlArray = true;
  1687. Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Format ("'{0}'", control.ClientID));
  1688. }
  1689. protected virtual void OnSaveStateComplete (EventArgs e)
  1690. {
  1691. if ((event_mask & savestatecomplete_mask) != 0) {
  1692. EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
  1693. if (eh != null) eh (this, e);
  1694. }
  1695. }
  1696. public HtmlForm Form {
  1697. get { return _form; }
  1698. }
  1699. internal void RegisterForm (HtmlForm form)
  1700. {
  1701. _form = form;
  1702. }
  1703. [BrowsableAttribute (false)]
  1704. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1705. public Page PreviousPage {
  1706. get {
  1707. if (_doLoadPreviousPage) {
  1708. _doLoadPreviousPage = false;
  1709. LoadPreviousPageReference ();
  1710. }
  1711. return previousPage;
  1712. }
  1713. }
  1714. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1715. [BrowsableAttribute (false)]
  1716. public bool IsCallback {
  1717. get { return isCallback; }
  1718. }
  1719. [BrowsableAttribute (false)]
  1720. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1721. public bool IsCrossPagePostBack {
  1722. get { return isCrossPagePostBack; }
  1723. }
  1724. public new virtual char IdSeparator {
  1725. get {
  1726. //TODO: why override?
  1727. return base.IdSeparator;
  1728. }
  1729. }
  1730. string ProcessCallbackData ()
  1731. {
  1732. string callbackTarget = _requestValueCollection [CallbackSourceID];
  1733. if (callbackTarget == null || callbackTarget.Length == 0)
  1734. throw new HttpException ("Callback target not provided.");
  1735. Control targetControl = FindControl (callbackTarget);
  1736. ICallbackEventHandler target = targetControl as ICallbackEventHandler;
  1737. if (target == null)
  1738. throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
  1739. string callbackEventError = String.Empty;
  1740. string callBackResult;
  1741. string callbackArgument = _requestValueCollection [CallbackArgumentID];
  1742. try {
  1743. target.RaiseCallbackEvent (callbackArgument);
  1744. }
  1745. catch (Exception ex) {
  1746. callbackEventError = String.Format ("e{0}", ex.Message);
  1747. }
  1748. try {
  1749. callBackResult = target.GetCallbackResult ();
  1750. }
  1751. catch (Exception ex) {
  1752. return String.Format ("e{0}", ex.Message);
  1753. }
  1754. string eventValidation = ClientScript.GetEventValidationStateFormatted ();
  1755. return String.Format ("{0}{1}|{2}{3}", callbackEventError, eventValidation == null ? 0 : eventValidation.Length, eventValidation, callBackResult);
  1756. }
  1757. [BrowsableAttribute (false)]
  1758. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1759. public HtmlHead Header {
  1760. get { return htmlHeader; }
  1761. }
  1762. internal void SetHeader (HtmlHead header)
  1763. {
  1764. htmlHeader = header;
  1765. if (_title != null) {
  1766. htmlHeader.Title = _title;
  1767. _title = null;
  1768. }
  1769. }
  1770. protected bool AsyncMode {
  1771. get { return asyncMode; }
  1772. set { asyncMode = value; }
  1773. }
  1774. public TimeSpan AsyncTimeout {
  1775. get { return asyncTimeout; }
  1776. set { asyncTimeout = value; }
  1777. }
  1778. public bool IsAsync {
  1779. get { return AsyncMode; }
  1780. }
  1781. [MonoTODO ("Not Implemented")]
  1782. protected internal virtual string UniqueFilePathSuffix {
  1783. get {
  1784. throw new NotImplementedException ();
  1785. }
  1786. }
  1787. [MonoTODO ("Not Implemented")]
  1788. public int MaxPageStateFieldLength {
  1789. get {
  1790. throw new NotImplementedException ();
  1791. }
  1792. set {
  1793. throw new NotImplementedException ();
  1794. }
  1795. }
  1796. public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
  1797. {
  1798. AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
  1799. }
  1800. public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
  1801. {
  1802. if (!IsAsync) {
  1803. throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
  1804. }
  1805. if (_lifeCycle >= PageLifeCycle.PreRender) {
  1806. throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before PreRender.");
  1807. }
  1808. if (beginHandler == null) {
  1809. throw new ArgumentNullException ("beginHandler");
  1810. }
  1811. if (endHandler == null) {
  1812. throw new ArgumentNullException ("endHandler");
  1813. }
  1814. RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
  1815. }
  1816. private List<PageAsyncTask> ParallelTasks {
  1817. get
  1818. {
  1819. if (parallelTasks == null) {
  1820. parallelTasks = new List<PageAsyncTask>();
  1821. }
  1822. return parallelTasks;
  1823. }
  1824. }
  1825. private List<PageAsyncTask> SerialTasks {
  1826. get {
  1827. if (serialTasks == null) {
  1828. serialTasks = new List<PageAsyncTask> ();
  1829. }
  1830. return serialTasks;
  1831. }
  1832. }
  1833. public void RegisterAsyncTask (PageAsyncTask task)
  1834. {
  1835. if (task == null) {
  1836. throw new ArgumentNullException ("task");
  1837. }
  1838. if (task.ExecuteInParallel) {
  1839. ParallelTasks.Add (task);
  1840. }
  1841. else {
  1842. SerialTasks.Add (task);
  1843. }
  1844. }
  1845. public void ExecuteRegisteredAsyncTasks ()
  1846. {
  1847. if ((parallelTasks == null || parallelTasks.Count == 0) &&
  1848. (serialTasks == null || serialTasks.Count == 0)){
  1849. return;
  1850. }
  1851. if (parallelTasks != null) {
  1852. DateTime startExecution = DateTime.Now;
  1853. List<PageAsyncTask> localParallelTasks = parallelTasks;
  1854. parallelTasks = null; // Shouldn't execute tasks twice
  1855. List<IAsyncResult> asyncResults = new List<IAsyncResult>();
  1856. foreach (PageAsyncTask parallelTask in localParallelTasks) {
  1857. IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
  1858. if (result.CompletedSynchronously) {
  1859. parallelTask.EndHandler (result);
  1860. }
  1861. else {
  1862. asyncResults.Add (result);
  1863. }
  1864. }
  1865. if (asyncResults.Count > 0) {
  1866. WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
  1867. int i = 0;
  1868. for (i = 0; i < asyncResults.Count; i++) {
  1869. waitArray [i] = asyncResults [i].AsyncWaitHandle;
  1870. }
  1871. bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
  1872. if (!allSignalled) {
  1873. for (i = 0; i < asyncResults.Count; i++) {
  1874. if (!asyncResults [i].IsCompleted) {
  1875. localParallelTasks [i].TimeoutHandler (asyncResults [i]);
  1876. }
  1877. }
  1878. }
  1879. }
  1880. DateTime endWait = DateTime.Now;
  1881. TimeSpan elapsed = endWait - startExecution;
  1882. if (elapsed <= AsyncTimeout) {
  1883. AsyncTimeout -= elapsed;
  1884. }
  1885. else {
  1886. AsyncTimeout = TimeSpan.FromTicks(0);
  1887. }
  1888. }
  1889. if (serialTasks != null) {
  1890. List<PageAsyncTask> localSerialTasks = serialTasks;
  1891. serialTasks = null; // Shouldn't execute tasks twice
  1892. foreach (PageAsyncTask serialTask in localSerialTasks) {
  1893. DateTime startExecution = DateTime.Now;
  1894. IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
  1895. if (result.CompletedSynchronously) {
  1896. serialTask.EndHandler (result);
  1897. }
  1898. else {
  1899. bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
  1900. if (!done && !result.IsCompleted) {
  1901. serialTask.TimeoutHandler (result);
  1902. }
  1903. }
  1904. DateTime endWait = DateTime.Now;
  1905. TimeSpan elapsed = endWait - startExecution;
  1906. if (elapsed <= AsyncTimeout) {
  1907. AsyncTimeout -= elapsed;
  1908. }
  1909. else {
  1910. AsyncTimeout = TimeSpan.FromTicks (0);
  1911. }
  1912. }
  1913. }
  1914. AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
  1915. }
  1916. void EndAsyncTaskCallback (IAsyncResult result)
  1917. {
  1918. PageAsyncTask task = (PageAsyncTask)result.AsyncState;
  1919. task.EndHandler (result);
  1920. }
  1921. public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
  1922. {
  1923. Type htmlTextWriterType = typeof (HtmlTextWriter);
  1924. if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
  1925. throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
  1926. }
  1927. ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
  1928. if (constructor == null) {
  1929. throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
  1930. }
  1931. return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
  1932. }
  1933. public ViewStateEncryptionMode ViewStateEncryptionMode {
  1934. get { return viewStateEncryptionMode; }
  1935. set { viewStateEncryptionMode = value; }
  1936. }
  1937. public void RegisterRequiresViewStateEncryption ()
  1938. {
  1939. controlRegisteredForViewStateEncryption = true;
  1940. }
  1941. private static byte [] AES_IV = null;
  1942. private static byte [] TripleDES_IV = null;
  1943. private static object locker = new object ();
  1944. private static bool isEncryptionInitialized = false;
  1945. private static void InitializeEncryption ()
  1946. {
  1947. if (isEncryptionInitialized) {
  1948. return;
  1949. }
  1950. lock (locker) {
  1951. if (isEncryptionInitialized) {
  1952. return;
  1953. }
  1954. string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
  1955. AES_IV = new byte [16];
  1956. TripleDES_IV = new byte [8];
  1957. int i;
  1958. for (i = 0; i < AES_IV.Length; i++) {
  1959. AES_IV [i] = (byte) iv_string [i];
  1960. }
  1961. for (i = 0; i < TripleDES_IV.Length; i++) {
  1962. TripleDES_IV [i] = (byte) iv_string [i];
  1963. }
  1964. isEncryptionInitialized = true;
  1965. }
  1966. }
  1967. internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
  1968. {
  1969. ICryptoTransform transform = null;
  1970. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
  1971. byte [] vk = config.ValidationKeyBytes;
  1972. switch (config.Validation) {
  1973. case MachineKeyValidation.SHA1:
  1974. transform = SHA1.Create ();
  1975. break;
  1976. case MachineKeyValidation.MD5:
  1977. transform = MD5.Create ();
  1978. break;
  1979. case MachineKeyValidation.AES:
  1980. if (cryptoStreamMode == CryptoStreamMode.Read){
  1981. transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
  1982. } else {
  1983. transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
  1984. }
  1985. break;
  1986. case MachineKeyValidation.TripleDES:
  1987. if (cryptoStreamMode == CryptoStreamMode.Read){
  1988. transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
  1989. } else {
  1990. transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
  1991. }
  1992. break;
  1993. }
  1994. return transform;
  1995. }
  1996. internal bool NeedViewStateEncryption {
  1997. get {
  1998. return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
  1999. (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
  2000. controlRegisteredForViewStateEncryption));
  2001. }
  2002. }
  2003. void ApplyMasterPage ()
  2004. {
  2005. if (masterPageFile != null && masterPageFile.Length > 0) {
  2006. ArrayList appliedMasterPageFiles = new ArrayList ();
  2007. if (Master != null) {
  2008. MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
  2009. Master.Page = this;
  2010. Controls.Clear ();
  2011. Controls.Add (Master);
  2012. }
  2013. }
  2014. }
  2015. [DefaultValueAttribute ("")]
  2016. public virtual string MasterPageFile {
  2017. get { return masterPageFile; }
  2018. set {
  2019. masterPageFile = value;
  2020. masterPage = null;
  2021. }
  2022. }
  2023. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  2024. [BrowsableAttribute (false)]
  2025. public MasterPage Master {
  2026. get {
  2027. if (Context == null || String.IsNullOrEmpty (masterPageFile))
  2028. return null;
  2029. if (masterPage == null)
  2030. masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
  2031. return masterPage;
  2032. }
  2033. }
  2034. public void SetFocus (string clientID)
  2035. {
  2036. if (String.IsNullOrEmpty (clientID))
  2037. throw new ArgumentNullException ("control");
  2038. if (_lifeCycle > PageLifeCycle.PreRender)
  2039. throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
  2040. if(Form==null)
  2041. throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
  2042. _focusedControlID = clientID;
  2043. }
  2044. public void SetFocus (Control control)
  2045. {
  2046. if (control == null)
  2047. throw new ArgumentNullException ("control");
  2048. SetFocus (control.ClientID);
  2049. }
  2050. [EditorBrowsable (EditorBrowsableState.Advanced)]
  2051. public void RegisterRequiresControlState (Control control)
  2052. {
  2053. if (control == null)
  2054. throw new ArgumentNullException ("control");
  2055. if (RequiresControlState (control))
  2056. return;
  2057. if (requireStateControls == null)
  2058. requireStateControls = new ArrayList ();
  2059. int n = requireStateControls.Add (control);
  2060. if (_savedControlState == null || n >= _savedControlState.Length)
  2061. return;
  2062. for (Control parent = control.Parent; parent != null; parent = parent.Parent)
  2063. if (parent.IsChildControlStateCleared)
  2064. return;
  2065. object state = _savedControlState [n];
  2066. if (state != null)
  2067. control.LoadControlState (state);
  2068. }
  2069. public bool RequiresControlState (Control control)
  2070. {
  2071. if (requireStateControls == null) return false;
  2072. return requireStateControls.Contains (control);
  2073. }
  2074. [EditorBrowsable (EditorBrowsableState.Advanced)]
  2075. public void UnregisterRequiresControlState (Control control)
  2076. {
  2077. if (requireStateControls != null)
  2078. requireStateControls.Remove (control);
  2079. }
  2080. public ValidatorCollection GetValidators (string validationGroup)
  2081. {
  2082. string valgr = validationGroup;
  2083. if (valgr == null)
  2084. valgr = String.Empty;
  2085. if (_validatorsByGroup == null) _validatorsByGroup = new Hashtable ();
  2086. ValidatorCollection col = _validatorsByGroup [valgr] as ValidatorCollection;
  2087. if (col == null) {
  2088. col = new ValidatorCollection ();
  2089. _validatorsByGroup [valgr] = col;
  2090. }
  2091. return col;
  2092. }
  2093. public virtual void Validate (string validationGroup)
  2094. {
  2095. is_validated = true;
  2096. if (validationGroup == null)
  2097. ValidateCollection (_validatorsByGroup [String.Empty] as ValidatorCollection);
  2098. else if (_validatorsByGroup != null) {
  2099. ValidateCollection (_validatorsByGroup [validationGroup] as ValidatorCollection);
  2100. }
  2101. }
  2102. object SavePageControlState ()
  2103. {
  2104. if (requireStateControls == null) return null;
  2105. object[] state = new object [requireStateControls.Count];
  2106. bool allNull = true;
  2107. for (int n=0; n<state.Length; n++) {
  2108. state [n] = ((Control) requireStateControls [n]).SaveControlState ();
  2109. if (state [n] != null) allNull = false;
  2110. }
  2111. if (allNull) return null;
  2112. else return state;
  2113. }
  2114. void LoadPageControlState (object data)
  2115. {
  2116. _savedControlState = (object []) data;
  2117. if (requireStateControls == null) return;
  2118. int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
  2119. for (int n=0; n < max; n++) {
  2120. Control ctl = (Control) requireStateControls [n];
  2121. ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
  2122. }
  2123. }
  2124. void LoadPreviousPageReference ()
  2125. {
  2126. if (_requestValueCollection != null) {
  2127. string prevPage = _requestValueCollection [PreviousPageID];
  2128. if (prevPage != null) {
  2129. previousPage = (Page) PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
  2130. previousPage.ProcessCrossPagePostBack (_context);
  2131. }
  2132. }
  2133. }
  2134. Hashtable contentTemplates;
  2135. [EditorBrowsable (EditorBrowsableState.Never)]
  2136. protected internal void AddContentTemplate (string templateName, ITemplate template)
  2137. {
  2138. if (contentTemplates == null)
  2139. contentTemplates = new Hashtable ();
  2140. contentTemplates [templateName] = template;
  2141. }
  2142. PageTheme _pageTheme;
  2143. internal PageTheme PageTheme {
  2144. get { return _pageTheme; }
  2145. }
  2146. PageTheme _styleSheetPageTheme;
  2147. internal PageTheme StyleSheetPageTheme {
  2148. get { return _styleSheetPageTheme; }
  2149. }
  2150. Stack dataItemCtx;
  2151. internal void PushDataItemContext (object o) {
  2152. if (dataItemCtx == null)
  2153. dataItemCtx = new Stack ();
  2154. dataItemCtx.Push (o);
  2155. }
  2156. internal void PopDataItemContext () {
  2157. if (dataItemCtx == null)
  2158. throw new InvalidOperationException ();
  2159. dataItemCtx.Pop ();
  2160. }
  2161. public object GetDataItem() {
  2162. if (dataItemCtx == null || dataItemCtx.Count == 0)
  2163. throw new InvalidOperationException ("No data item");
  2164. return dataItemCtx.Peek ();
  2165. }
  2166. protected internal override void OnInit (EventArgs e)
  2167. {
  2168. base.OnInit (e);
  2169. ArrayList themes = new ArrayList();
  2170. if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
  2171. themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
  2172. if (PageTheme != null && PageTheme.GetStyleSheets () != null)
  2173. themes.AddRange (PageTheme.GetStyleSheets ());
  2174. if (themes.Count > 0 && Header == null)
  2175. throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
  2176. foreach (string lss in themes) {
  2177. HtmlLink hl = new HtmlLink ();
  2178. hl.Href = ResolveUrl (lss);
  2179. hl.Attributes["type"] = "text/css";
  2180. hl.Attributes["rel"] = "stylesheet";
  2181. Header.Controls.Add (hl);
  2182. }
  2183. }
  2184. #endif
  2185. #if NET_2_0
  2186. [MonoTODO ("Not implemented. Only used by .net aspx parser")]
  2187. protected object GetWrappedFileDependencies (string [] list)
  2188. {
  2189. return list;
  2190. }
  2191. [MonoTODO ("Does nothing. Used by .net aspx parser")]
  2192. protected virtual void InitializeCulture ()
  2193. {
  2194. }
  2195. [MonoTODO ("Does nothing. Used by .net aspx parser")]
  2196. protected internal void AddWrappedFileDependencies (object virtualFileDependencies)
  2197. {
  2198. }
  2199. #endif
  2200. }
  2201. }