Page.cs 75 KB

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