Page.cs 73 KB

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