PageRenderTime 54ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/mcs/class/System.Web/System.Web.UI/Page.cs

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