Page.cs 73 KB

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