Page.cs 74 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811
  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. string webForm = IsMultiForm ? theForm + "." : null;
  926. StringBuilder script = new StringBuilder ();
  927. script.AppendLine ("<script type=\"text/javascript\">");
  928. script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_START);
  929. script.AppendLine (theForm + ".oldSubmit = " + theForm + ".submit;");
  930. script.AppendLine (theForm + ".submit = function () { " + webForm + "WebForm_SaveScrollPositionSubmit(); }");
  931. script.AppendLine (theForm + ".oldOnSubmit = " + theForm + ".onsubmit;");
  932. script.AppendLine (theForm + ".onsubmit = function () { " + webForm + "WebForm_SaveScrollPositionOnSubmit(); }");
  933. if (IsPostBack) {
  934. script.AppendLine (theForm + ".oldOnLoad = window.onload;");
  935. script.AppendLine ("window.onload = function () { " + webForm + "WebForm_RestoreScrollPosition (); };");
  936. }
  937. script.AppendLine (ClientScriptManager.SCRIPT_BLOCK_END);
  938. script.AppendLine ("</script>");
  939. ClientScript.RegisterStartupScript (typeof (Page), "MaintainScrollPositionOnPostBackStartup", script.ToString());
  940. }
  941. base.Render (writer);
  942. }
  943. #endif
  944. private void RenderPostBackScript (HtmlTextWriter writer, string formUniqueID)
  945. {
  946. #if ONLY_1_1
  947. writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventSourceID);
  948. writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" value=\"\" />", postEventArgumentID);
  949. #endif
  950. writer.WriteLine ();
  951. ClientScriptManager.WriteBeginScriptBlock (writer);
  952. #if ONLY_1_1
  953. RenderClientScriptFormDeclaration (writer, formUniqueID);
  954. #endif
  955. if (IsMultiForm) {
  956. writer.WriteLine ("{0}._form = {0};", theForm);
  957. writer.Write (theForm + ".");
  958. } else {
  959. writer.WriteLine ("window._form = {0};", theForm);
  960. }
  961. writer.WriteLine ("__doPostBack = function (eventTarget, eventArgument) {");
  962. #if NET_2_0
  963. writer.WriteLine ("\tif(this._form.onsubmit && this._form.onsubmit() == false) return;");
  964. #else
  965. writer.WriteLine ("\tif(document.ValidatorOnSubmit && !ValidatorOnSubmit()) return;");
  966. #endif
  967. writer.WriteLine ("\tthis._form.{0}.value = eventTarget;", postEventSourceID);
  968. writer.WriteLine ("\tthis._form.{0}.value = eventArgument;", postEventArgumentID);
  969. writer.WriteLine ("\tthis._form.submit();");
  970. writer.WriteLine ("}");
  971. ClientScriptManager.WriteEndScriptBlock (writer);
  972. }
  973. void RenderClientScriptFormDeclaration (HtmlTextWriter writer, string formUniqueID)
  974. {
  975. writer.WriteLine ("\tvar {0};\n\tif (document.getElementById) {{ {0} = document.getElementById ('{1}'); }}", theForm, formUniqueID);
  976. writer.WriteLine ("\telse {{ {0} = document.{1}; }}", theForm, formUniqueID);
  977. writer.WriteLine ("\t{0}._instanceVariableName = '{0}';", theForm);
  978. #if TARGET_J2EE
  979. // TODO implement callback on portlet
  980. string serverUrl = Request.RawUrl;
  981. writer.WriteLine ("\t{0}.serverURL = {1};", theForm, ClientScriptManager.GetScriptLiteral (serverUrl));
  982. writer.WriteLine ("\twindow.TARGET_J2EE = true;");
  983. writer.WriteLine ("\twindow.IsMultiForm = {0};", IsMultiForm ? "true" : "false");
  984. #endif
  985. }
  986. internal void OnFormRender (HtmlTextWriter writer, string formUniqueID)
  987. {
  988. if (renderingForm)
  989. throw new HttpException ("Only 1 HtmlForm is allowed per page.");
  990. renderingForm = true;
  991. writer.WriteLine ();
  992. #if NET_2_0
  993. ClientScriptManager.WriteBeginScriptBlock (writer);
  994. RenderClientScriptFormDeclaration (writer, formUniqueID);
  995. ClientScriptManager.WriteEndScriptBlock (writer);
  996. #endif
  997. if (handleViewState)
  998. #if TARGET_J2EE
  999. if (getFacesContext () != null) {
  1000. javax.faces.application.ViewHandler viewHandler = getFacesContext ().getApplication ().getViewHandler ();
  1001. javax.faces.context.ResponseWriter oldFacesWriter = SetupResponseWriter (writer);
  1002. try {
  1003. viewHandler.writeState (getFacesContext ());
  1004. }
  1005. finally {
  1006. getFacesContext ().setResponseWriter (oldFacesWriter);
  1007. }
  1008. }
  1009. #endif
  1010. scriptManager.RegisterHiddenField ("__VIEWSTATE", _savedViewState);
  1011. scriptManager.WriteHiddenFields (writer);
  1012. if (requiresPostBackScript) {
  1013. RenderPostBackScript (writer, formUniqueID);
  1014. postBackScriptRendered = true;
  1015. }
  1016. #if NET_2_0
  1017. scriptManager.WriteWebFormClientScript (writer);
  1018. #endif
  1019. scriptManager.WriteClientScriptBlocks (writer);
  1020. }
  1021. internal IStateFormatter GetFormatter ()
  1022. {
  1023. return new ObjectStateFormatter (this);
  1024. }
  1025. internal string GetSavedViewState ()
  1026. {
  1027. return _savedViewState;
  1028. }
  1029. internal void OnFormPostRender (HtmlTextWriter writer, string formUniqueID)
  1030. {
  1031. #if NET_2_0
  1032. scriptManager.SaveEventValidationState ();
  1033. scriptManager.WriteExpandoAttributes (writer);
  1034. #endif
  1035. scriptManager.WriteHiddenFields (writer);
  1036. if (!postBackScriptRendered && requiresPostBackScript)
  1037. RenderPostBackScript (writer, formUniqueID);
  1038. #if NET_2_0
  1039. scriptManager.WriteWebFormClientScript (writer);
  1040. #endif
  1041. scriptManager.WriteArrayDeclares (writer);
  1042. scriptManager.WriteStartupScriptBlocks (writer);
  1043. renderingForm = false;
  1044. postBackScriptRendered = false;
  1045. }
  1046. private void ProcessPostData (NameValueCollection data, bool second)
  1047. {
  1048. NameValueCollection requestValues = _requestValueCollection == null ?
  1049. new NameValueCollection () :
  1050. _requestValueCollection;
  1051. if (data != null && data.Count > 0) {
  1052. Hashtable used = new Hashtable ();
  1053. foreach (string id in data.AllKeys){
  1054. if (id == "__VIEWSTATE" || id == postEventSourceID || id == postEventArgumentID ||
  1055. id == ClientScriptManager.EventStateFieldName)
  1056. continue;
  1057. if (used.ContainsKey (id))
  1058. continue;
  1059. used.Add (id, id);
  1060. Control ctrl = FindControl (id, true);
  1061. if (ctrl != null){
  1062. IPostBackDataHandler pbdh = ctrl as IPostBackDataHandler;
  1063. IPostBackEventHandler pbeh = ctrl as IPostBackEventHandler;
  1064. if (pbdh == null) {
  1065. if (pbeh != null)
  1066. RegisterRequiresRaiseEvent (pbeh);
  1067. continue;
  1068. }
  1069. if (pbdh.LoadPostData (id, requestValues) == true) {
  1070. if (requiresPostDataChanged == null)
  1071. requiresPostDataChanged = new ArrayList ();
  1072. requiresPostDataChanged.Add (pbdh);
  1073. }
  1074. if (_requiresPostBackCopy != null)
  1075. _requiresPostBackCopy.Remove (id);
  1076. } else if (!second) {
  1077. if (secondPostData == null)
  1078. secondPostData = new NameValueCollection ();
  1079. secondPostData.Add (id, data [id]);
  1080. }
  1081. }
  1082. }
  1083. ArrayList list1 = null;
  1084. if (_requiresPostBackCopy != null && _requiresPostBackCopy.Count > 0) {
  1085. string [] handlers = (string []) _requiresPostBackCopy.ToArray (typeof (string));
  1086. foreach (string id in handlers) {
  1087. IPostBackDataHandler pbdh = FindControl (id, true) as IPostBackDataHandler;
  1088. if (pbdh != null) {
  1089. _requiresPostBackCopy.Remove (id);
  1090. if (pbdh.LoadPostData (id, requestValues)) {
  1091. if (requiresPostDataChanged == null)
  1092. requiresPostDataChanged = new ArrayList ();
  1093. requiresPostDataChanged.Add (pbdh);
  1094. }
  1095. } else if (!second) {
  1096. if (list1 == null)
  1097. list1 = new ArrayList ();
  1098. list1.Add (id);
  1099. }
  1100. }
  1101. }
  1102. _requiresPostBackCopy = second ? null : list1;
  1103. if (second)
  1104. secondPostData = null;
  1105. }
  1106. [EditorBrowsable (EditorBrowsableState.Never)]
  1107. #if NET_2_0
  1108. public virtual void ProcessRequest (HttpContext context)
  1109. #else
  1110. public void ProcessRequest (HttpContext context)
  1111. #endif
  1112. {
  1113. SetContext (context);
  1114. #if TARGET_J2EE
  1115. bool wasException = false;
  1116. IHttpHandler jsfHandler = getFacesContext () != null ? EnterThread () : null;
  1117. #endif
  1118. if (clientTarget != null)
  1119. Request.ClientTarget = clientTarget;
  1120. WireupAutomaticEvents ();
  1121. //-- Control execution lifecycle in the docs
  1122. // Save culture information because it can be modified in FrameworkInitialize()
  1123. _appCulture = Thread.CurrentThread.CurrentCulture;
  1124. _appUICulture = Thread.CurrentThread.CurrentUICulture;
  1125. FrameworkInitialize ();
  1126. context.ErrorPage = _errorPage;
  1127. try {
  1128. InternalProcessRequest ();
  1129. #if TARGET_J2EE
  1130. } catch (Exception ex) {
  1131. wasException = true;
  1132. HandleException (ex);
  1133. #else
  1134. } catch (ThreadAbortException taex) {
  1135. if (context.Response.FlagEnd == taex.ExceptionState)
  1136. Thread.ResetAbort ();
  1137. else
  1138. throw;
  1139. } catch (Exception e) {
  1140. ProcessException (e);
  1141. #endif
  1142. } finally {
  1143. #if TARGET_J2EE
  1144. if (getFacesContext () != null)
  1145. ExitThread (jsfHandler);
  1146. else if (!wasException)
  1147. #endif
  1148. ProcessUnload ();
  1149. }
  1150. }
  1151. void ProcessException (Exception e) {
  1152. // We want to remove that error, as we're rethrowing to stop
  1153. // further processing.
  1154. Trace.Warn ("Unhandled Exception", e.ToString (), e);
  1155. _context.AddError (e); // OnError might access LastError
  1156. OnError (EventArgs.Empty);
  1157. if (_context.HasError (e)) {
  1158. _context.ClearError (e);
  1159. #if TARGET_JVM
  1160. vmw.common.TypeUtils.Throw (e);
  1161. #else
  1162. throw new TargetInvocationException (e);
  1163. #endif
  1164. }
  1165. }
  1166. void ProcessUnload () {
  1167. try {
  1168. RenderTrace ();
  1169. UnloadRecursive (true);
  1170. } catch {}
  1171. #if TARGET_J2EE
  1172. if (getFacesContext () != null) {
  1173. if(IsCrossPagePostBack)
  1174. _context.Items [CrossPagePostBack] = this;
  1175. }
  1176. #endif
  1177. if (Thread.CurrentThread.CurrentCulture.Equals (_appCulture) == false)
  1178. Thread.CurrentThread.CurrentCulture = _appCulture;
  1179. if (Thread.CurrentThread.CurrentUICulture.Equals (_appUICulture) == false)
  1180. Thread.CurrentThread.CurrentUICulture = _appUICulture;
  1181. _appCulture = null;
  1182. _appUICulture = null;
  1183. }
  1184. #if NET_2_0
  1185. delegate void ProcessRequestDelegate (HttpContext context);
  1186. private sealed class DummyAsyncResult : IAsyncResult
  1187. {
  1188. readonly object state;
  1189. readonly WaitHandle asyncWaitHandle;
  1190. readonly bool completedSynchronously;
  1191. readonly bool isCompleted;
  1192. public DummyAsyncResult (bool isCompleted, bool completedSynchronously, object state)
  1193. {
  1194. this.isCompleted = isCompleted;
  1195. this.completedSynchronously = completedSynchronously;
  1196. this.state = state;
  1197. if (isCompleted) {
  1198. asyncWaitHandle = new ManualResetEvent (true);
  1199. }
  1200. else {
  1201. asyncWaitHandle = new ManualResetEvent (false);
  1202. }
  1203. }
  1204. #region IAsyncResult Members
  1205. public object AsyncState {
  1206. get { return state; }
  1207. }
  1208. public WaitHandle AsyncWaitHandle {
  1209. get { return asyncWaitHandle; }
  1210. }
  1211. public bool CompletedSynchronously {
  1212. get { return completedSynchronously; }
  1213. }
  1214. public bool IsCompleted {
  1215. get { return isCompleted; }
  1216. }
  1217. #endregion
  1218. }
  1219. protected IAsyncResult AsyncPageBeginProcessRequest (HttpContext context, AsyncCallback callback, object extraData)
  1220. {
  1221. ProcessRequest (context);
  1222. DummyAsyncResult asyncResult = new DummyAsyncResult (true, true, extraData);
  1223. if (callback != null) {
  1224. callback (asyncResult);
  1225. }
  1226. return asyncResult;
  1227. }
  1228. protected void AsyncPageEndProcessRequest (IAsyncResult result)
  1229. {
  1230. }
  1231. #endif
  1232. void InternalProcessRequest ()
  1233. {
  1234. _requestValueCollection = this.DeterminePostBackMode();
  1235. #if NET_2_0
  1236. // http://msdn2.microsoft.com/en-us/library/ms178141.aspx
  1237. if (_requestValueCollection != null) {
  1238. if (!isCrossPagePostBack && _requestValueCollection [PreviousPageID] != null && _requestValueCollection [PreviousPageID] != Request.FilePath) {
  1239. _doLoadPreviousPage = true;
  1240. }
  1241. else {
  1242. isCallback = _requestValueCollection [CallbackArgumentID] != null;
  1243. // LAMESPEC: on Callback IsPostBack is set to false, but true.
  1244. //isPostBack = !isCallback;
  1245. isPostBack = true;
  1246. }
  1247. string lastFocus = _requestValueCollection [LastFocusID];
  1248. if (!String.IsNullOrEmpty (lastFocus)) {
  1249. _focusedControlID = UniqueID2ClientID (lastFocus);
  1250. }
  1251. }
  1252. if (!isCrossPagePostBack) {
  1253. if (_context.PreviousHandler is Page) {
  1254. previousPage = (Page) _context.PreviousHandler;
  1255. }
  1256. }
  1257. Trace.Write ("aspx.page", "Begin PreInit");
  1258. OnPreInit (EventArgs.Empty);
  1259. Trace.Write ("aspx.page", "End PreInit");
  1260. InitializeTheme ();
  1261. ApplyMasterPage ();
  1262. #endif
  1263. Trace.Write ("aspx.page", "Begin Init");
  1264. InitRecursive (null);
  1265. Trace.Write ("aspx.page", "End Init");
  1266. #if NET_2_0
  1267. Trace.Write ("aspx.page", "Begin InitComplete");
  1268. OnInitComplete (EventArgs.Empty);
  1269. Trace.Write ("aspx.page", "End InitComplete");
  1270. #endif
  1271. renderingForm = false;
  1272. #if TARGET_J2EE
  1273. if (getFacesContext () != null)
  1274. if (IsPostBack || IsCallback)
  1275. return;
  1276. #endif
  1277. RestorePageState ();
  1278. ProcessPostData ();
  1279. ProcessRaiseEvents ();
  1280. if (ProcessLoadComplete ())
  1281. return;
  1282. #if TARGET_J2EE
  1283. if (getFacesContext () != null) {
  1284. getFacesContext ().renderResponse ();
  1285. return;
  1286. }
  1287. #endif
  1288. RenderPage ();
  1289. }
  1290. void RestorePageState () {
  1291. #if NET_2_0
  1292. if (IsPostBack || IsCallback) {
  1293. if (_requestValueCollection != null)
  1294. scriptManager.RestoreEventValidationState (
  1295. _requestValueCollection [ClientScriptManager.EventStateFieldName]);
  1296. #else
  1297. if (IsPostBack) {
  1298. #endif
  1299. Trace.Write ("aspx.page", "Begin LoadViewState");
  1300. LoadPageViewState ();
  1301. Trace.Write ("aspx.page", "End LoadViewState");
  1302. }
  1303. }
  1304. void ProcessPostData () {
  1305. #if NET_2_0
  1306. if (IsPostBack || IsCallback) {
  1307. #else
  1308. if (IsPostBack) {
  1309. #endif
  1310. Trace.Write ("aspx.page", "Begin ProcessPostData");
  1311. ProcessPostData (_requestValueCollection, false);
  1312. Trace.Write ("aspx.page", "End ProcessPostData");
  1313. }
  1314. ProcessLoad ();
  1315. #if NET_2_0
  1316. if (IsPostBack || IsCallback) {
  1317. #else
  1318. if (IsPostBack) {
  1319. #endif
  1320. Trace.Write ("aspx.page", "Begin ProcessPostData Second Try");
  1321. ProcessPostData (secondPostData, true);
  1322. Trace.Write ("aspx.page", "End ProcessPostData Second Try");
  1323. }
  1324. }
  1325. void ProcessLoad () {
  1326. #if NET_2_0
  1327. Trace.Write ("aspx.page", "Begin PreLoad");
  1328. OnPreLoad (EventArgs.Empty);
  1329. Trace.Write ("aspx.page", "End PreLoad");
  1330. #endif
  1331. Trace.Write ("aspx.page", "Begin Load");
  1332. LoadRecursive ();
  1333. Trace.Write ("aspx.page", "End Load");
  1334. }
  1335. void ProcessRaiseEvents () {
  1336. #if NET_2_0
  1337. if (IsPostBack || IsCallback) {
  1338. #else
  1339. if (IsPostBack) {
  1340. #endif
  1341. Trace.Write ("aspx.page", "Begin Raise ChangedEvents");
  1342. RaiseChangedEvents ();
  1343. Trace.Write ("aspx.page", "End Raise ChangedEvents");
  1344. Trace.Write ("aspx.page", "Begin Raise PostBackEvent");
  1345. RaisePostBackEvents ();
  1346. Trace.Write ("aspx.page", "End Raise PostBackEvent");
  1347. }
  1348. }
  1349. bool ProcessLoadComplete() {
  1350. #if NET_2_0
  1351. Trace.Write ("aspx.page", "Begin LoadComplete");
  1352. OnLoadComplete (EventArgs.Empty);
  1353. Trace.Write ("aspx.page", "End LoadComplete");
  1354. if (IsCrossPagePostBack)
  1355. return true;
  1356. if (IsCallback) {
  1357. #if TARGET_J2EE
  1358. if (getFacesContext () != null) {
  1359. _callbackTarget = GetCallbackTarget ();
  1360. ProcessRaiseCallbackEvent (_callbackTarget, ref _callbackEventError);
  1361. return true;
  1362. }
  1363. #endif
  1364. string result = ProcessCallbackData ();
  1365. HtmlTextWriter callbackOutput = new HtmlTextWriter (Response.Output);
  1366. callbackOutput.Write (result);
  1367. callbackOutput.Flush ();
  1368. return true;
  1369. }
  1370. #endif
  1371. Trace.Write ("aspx.page", "Begin PreRender");
  1372. PreRenderRecursiveInternal ();
  1373. Trace.Write ("aspx.page", "End PreRender");
  1374. #if NET_2_0
  1375. ExecuteRegisteredAsyncTasks ();
  1376. Trace.Write ("aspx.page", "Begin PreRenderComplete");
  1377. OnPreRenderComplete (EventArgs.Empty);
  1378. Trace.Write ("aspx.page", "End PreRenderComplete");
  1379. #endif
  1380. Trace.Write ("aspx.page", "Begin SaveViewState");
  1381. SavePageViewState ();
  1382. Trace.Write ("aspx.page", "End SaveViewState");
  1383. #if NET_2_0
  1384. Trace.Write ("aspx.page", "Begin SaveStateComplete");
  1385. OnSaveStateComplete (EventArgs.Empty);
  1386. Trace.Write ("aspx.page", "End SaveStateComplete");
  1387. #endif // NET_2_0
  1388. return false;
  1389. }
  1390. internal void RenderPage () {
  1391. #if NET_2_0
  1392. scriptManager.ResetEventValidationState ();
  1393. #endif
  1394. //--
  1395. Trace.Write ("aspx.page", "Begin Render");
  1396. HtmlTextWriter output = new HtmlTextWriter (Response.Output);
  1397. #if TARGET_J2EE
  1398. if (getFacesContext () != null)
  1399. SetupResponseWriter (output);
  1400. #endif
  1401. RenderControl (output);
  1402. Trace.Write ("aspx.page", "End Render");
  1403. }
  1404. void SetContext (HttpContext context) {
  1405. _context = context;
  1406. _application = context.Application;
  1407. _response = context.Response;
  1408. _request = context.Request;
  1409. _cache = context.Cache;
  1410. }
  1411. private void RenderTrace ()
  1412. {
  1413. TraceManager traceManager = HttpRuntime.TraceManager;
  1414. if (Trace.HaveTrace && !Trace.IsEnabled || !Trace.HaveTrace && !traceManager.Enabled)
  1415. return;
  1416. Trace.SaveData ();
  1417. if (!Trace.HaveTrace && traceManager.Enabled && !traceManager.PageOutput)
  1418. return;
  1419. if (!traceManager.LocalOnly || Context.Request.IsLocal) {
  1420. HtmlTextWriter output = new HtmlTextWriter (Response.Output);
  1421. Trace.Render (output);
  1422. }
  1423. }
  1424. #if NET_2_0
  1425. bool CheckForValidationSupport (Control targetControl)
  1426. {
  1427. if (targetControl == null)
  1428. return false;
  1429. Type type = targetControl.GetType ();
  1430. object[] attributes = type.GetCustomAttributes (false);
  1431. foreach (object attr in attributes)
  1432. if (attr is SupportsEventValidationAttribute)
  1433. return true;
  1434. return false;
  1435. }
  1436. #endif
  1437. void RaisePostBackEvents ()
  1438. {
  1439. #if NET_2_0
  1440. Control targetControl;
  1441. #endif
  1442. if (requiresRaiseEvent != null) {
  1443. RaisePostBackEvent (requiresRaiseEvent, null);
  1444. return;
  1445. }
  1446. NameValueCollection postdata = _requestValueCollection;
  1447. if (postdata == null)
  1448. return;
  1449. string eventTarget = postdata [postEventSourceID];
  1450. if (eventTarget == null || eventTarget.Length == 0) {
  1451. Validate ();
  1452. return;
  1453. }
  1454. #if NET_2_0
  1455. targetControl = FindControl (eventTarget, true);
  1456. IPostBackEventHandler target = targetControl as IPostBackEventHandler;
  1457. #else
  1458. IPostBackEventHandler target = FindControl (eventTarget) as IPostBackEventHandler;
  1459. #endif
  1460. if (target == null)
  1461. return;
  1462. string eventArgument = postdata [postEventArgumentID];
  1463. RaisePostBackEvent (target, eventArgument);
  1464. }
  1465. internal void RaiseChangedEvents ()
  1466. {
  1467. if (requiresPostDataChanged == null)
  1468. return;
  1469. foreach (IPostBackDataHandler ipdh in requiresPostDataChanged)
  1470. ipdh.RaisePostDataChangedEvent ();
  1471. requiresPostDataChanged = null;
  1472. }
  1473. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1474. protected virtual void RaisePostBackEvent (IPostBackEventHandler sourceControl, string eventArgument)
  1475. {
  1476. #if NET_2_0
  1477. Control targetControl = sourceControl as Control;
  1478. if (targetControl != null && CheckForValidationSupport (targetControl))
  1479. scriptManager.ValidateEvent (targetControl.UniqueID, eventArgument);
  1480. #endif
  1481. sourceControl.RaisePostBackEvent (eventArgument);
  1482. }
  1483. #if NET_2_0
  1484. [Obsolete]
  1485. #endif
  1486. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1487. public void RegisterArrayDeclaration (string arrayName, string arrayValue)
  1488. {
  1489. scriptManager.RegisterArrayDeclaration (arrayName, arrayValue);
  1490. }
  1491. #if NET_2_0
  1492. [Obsolete]
  1493. #endif
  1494. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1495. public virtual void RegisterClientScriptBlock (string key, string script)
  1496. {
  1497. scriptManager.RegisterClientScriptBlock (key, script);
  1498. }
  1499. #if NET_2_0
  1500. [Obsolete]
  1501. #endif
  1502. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1503. public virtual void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
  1504. {
  1505. scriptManager.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  1506. }
  1507. [MonoTODO("Not implemented, Used in HtmlForm")]
  1508. internal void RegisterClientScriptFile (string a, string b, string c)
  1509. {
  1510. throw new NotImplementedException ();
  1511. }
  1512. #if NET_2_0
  1513. [Obsolete]
  1514. #endif
  1515. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1516. public void RegisterOnSubmitStatement (string key, string script)
  1517. {
  1518. scriptManager.RegisterOnSubmitStatement (key, script);
  1519. }
  1520. internal string GetSubmitStatements ()
  1521. {
  1522. return scriptManager.WriteSubmitStatements ();
  1523. }
  1524. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1525. public void RegisterRequiresPostBack (Control control)
  1526. {
  1527. #if NET_2_0
  1528. if (!(control is IPostBackDataHandler))
  1529. throw new HttpException ("The control to register does not implement the IPostBackDataHandler interface.");
  1530. #endif
  1531. if (_requiresPostBack == null)
  1532. _requiresPostBack = new ArrayList ();
  1533. if (_requiresPostBack.Contains (control.UniqueID))
  1534. return;
  1535. _requiresPostBack.Add (control.UniqueID);
  1536. }
  1537. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1538. public virtual void RegisterRequiresRaiseEvent (IPostBackEventHandler control)
  1539. {
  1540. requiresRaiseEvent = control;
  1541. }
  1542. #if NET_2_0
  1543. [Obsolete]
  1544. #endif
  1545. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1546. public virtual void RegisterStartupScript (string key, string script)
  1547. {
  1548. scriptManager.RegisterStartupScript (key, script);
  1549. }
  1550. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1551. public void RegisterViewStateHandler ()
  1552. {
  1553. handleViewState = true;
  1554. }
  1555. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1556. protected virtual void SavePageStateToPersistenceMedium (object viewState)
  1557. {
  1558. PageStatePersister persister = this.PageStatePersister;
  1559. if (persister == null)
  1560. return;
  1561. Pair pair = viewState as Pair;
  1562. if (pair != null) {
  1563. persister.ViewState = pair.First;
  1564. persister.ControlState = pair.Second;
  1565. } else
  1566. persister.ViewState = viewState;
  1567. persister.Save ();
  1568. }
  1569. internal string RawViewState {
  1570. get {
  1571. NameValueCollection postdata = _requestValueCollection;
  1572. string view_state;
  1573. if (postdata == null || (view_state = postdata ["__VIEWSTATE"]) == null)
  1574. return null;
  1575. if (view_state == "")
  1576. return null;
  1577. return view_state;
  1578. }
  1579. set { _savedViewState = value; }
  1580. }
  1581. #if NET_2_0
  1582. protected virtual
  1583. #else
  1584. internal
  1585. #endif
  1586. PageStatePersister PageStatePersister {
  1587. get {
  1588. if (page_state_persister == null)
  1589. #if TARGET_J2EE
  1590. if (getFacesContext () != null)
  1591. return new FacesPageStatePersister (this);
  1592. else
  1593. #endif
  1594. page_state_persister = new HiddenFieldPageStatePersister (this);
  1595. return page_state_persister;
  1596. }
  1597. }
  1598. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1599. protected virtual object LoadPageStateFromPersistenceMedium ()
  1600. {
  1601. PageStatePersister persister = this.PageStatePersister;
  1602. if (persister == null)
  1603. return null;
  1604. persister.Load ();
  1605. return new Pair (persister.ViewState, persister.ControlState);
  1606. }
  1607. internal void LoadPageViewState()
  1608. {
  1609. Pair sState = LoadPageStateFromPersistenceMedium () as Pair;
  1610. if (sState != null) {
  1611. if (allow_load) {
  1612. #if NET_2_0
  1613. LoadPageControlState (sState.Second);
  1614. #endif
  1615. Pair vsr = sState.First as Pair;
  1616. if (vsr != null) {
  1617. LoadViewStateRecursive (vsr.First);
  1618. _requiresPostBackCopy = vsr.Second as ArrayList;
  1619. }
  1620. }
  1621. }
  1622. }
  1623. internal void SavePageViewState ()
  1624. {
  1625. if (!handleViewState)
  1626. return;
  1627. #if NET_2_0
  1628. object controlState = SavePageControlState ();
  1629. #endif
  1630. object viewState = SaveViewStateRecursive ();
  1631. object reqPostback = (_requiresPostBack != null && _requiresPostBack.Count > 0) ? _requiresPostBack : null;
  1632. Pair vsr = null;
  1633. if (viewState != null || reqPostback != null)
  1634. vsr = new Pair (viewState, reqPostback);
  1635. Pair pair = new Pair ();
  1636. pair.First = vsr;
  1637. #if NET_2_0
  1638. pair.Second = controlState;
  1639. #else
  1640. pair.Second = null;
  1641. #endif
  1642. if (pair.First == null && pair.Second == null)
  1643. SavePageStateToPersistenceMedium (null);
  1644. else
  1645. SavePageStateToPersistenceMedium (pair);
  1646. }
  1647. public virtual void Validate ()
  1648. {
  1649. is_validated = true;
  1650. ValidateCollection (_validators);
  1651. }
  1652. #if NET_2_0
  1653. internal bool AreValidatorsUplevel () {
  1654. return AreValidatorsUplevel (String.Empty);
  1655. }
  1656. internal bool AreValidatorsUplevel (string valGroup)
  1657. #else
  1658. internal virtual bool AreValidatorsUplevel ()
  1659. #endif
  1660. {
  1661. bool uplevel = false;
  1662. foreach (IValidator v in Validators) {
  1663. BaseValidator bv = v as BaseValidator;
  1664. if (bv == null) continue;
  1665. #if NET_2_0
  1666. if (valGroup != bv.ValidationGroup)
  1667. continue;
  1668. #endif
  1669. if (bv.GetRenderUplevel()) {
  1670. uplevel = true;
  1671. break;
  1672. }
  1673. }
  1674. return uplevel;
  1675. }
  1676. bool ValidateCollection (ValidatorCollection validators)
  1677. {
  1678. #if NET_2_0
  1679. if (!_eventValidation)
  1680. return true;
  1681. #endif
  1682. if (validators == null || validators.Count == 0)
  1683. return true;
  1684. bool all_valid = true;
  1685. foreach (IValidator v in validators){
  1686. v.Validate ();
  1687. if (v.IsValid == false)
  1688. all_valid = false;
  1689. }
  1690. return all_valid;
  1691. }
  1692. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1693. public virtual void VerifyRenderingInServerForm (Control control)
  1694. {
  1695. if (Context == null)
  1696. return;
  1697. #if NET_2_0
  1698. if (IsCallback)
  1699. return;
  1700. #endif
  1701. if (!renderingForm)
  1702. throw new HttpException ("Control '" +
  1703. control.ClientID +
  1704. "' of type '" +
  1705. control.GetType ().Name +
  1706. "' must be placed inside a form tag with runat=server.");
  1707. }
  1708. protected override void FrameworkInitialize ()
  1709. {
  1710. base.FrameworkInitialize ();
  1711. #if NET_2_0
  1712. InitializeStyleSheet ();
  1713. #endif
  1714. }
  1715. #endregion
  1716. #if NET_2_0
  1717. public
  1718. #else
  1719. internal
  1720. #endif
  1721. ClientScriptManager ClientScript {
  1722. get { return scriptManager; }
  1723. }
  1724. #if NET_2_0
  1725. static readonly object InitCompleteEvent = new object ();
  1726. static readonly object LoadCompleteEvent = new object ();
  1727. static readonly object PreInitEvent = new object ();
  1728. static readonly object PreLoadEvent = new object ();
  1729. static readonly object PreRenderCompleteEvent = new object ();
  1730. static readonly object SaveStateCompleteEvent = new object ();
  1731. int event_mask;
  1732. const int initcomplete_mask = 1;
  1733. const int loadcomplete_mask = 1 << 1;
  1734. const int preinit_mask = 1 << 2;
  1735. const int preload_mask = 1 << 3;
  1736. const int prerendercomplete_mask = 1 << 4;
  1737. const int savestatecomplete_mask = 1 << 5;
  1738. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1739. public event EventHandler InitComplete {
  1740. add {
  1741. event_mask |= initcomplete_mask;
  1742. Events.AddHandler (InitCompleteEvent, value);
  1743. }
  1744. remove { Events.RemoveHandler (InitCompleteEvent, value); }
  1745. }
  1746. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1747. public event EventHandler LoadComplete {
  1748. add {
  1749. event_mask |= loadcomplete_mask;
  1750. Events.AddHandler (LoadCompleteEvent, value);
  1751. }
  1752. remove { Events.RemoveHandler (LoadCompleteEvent, value); }
  1753. }
  1754. public event EventHandler PreInit {
  1755. add {
  1756. event_mask |= preinit_mask;
  1757. Events.AddHandler (PreInitEvent, value);
  1758. }
  1759. remove { Events.RemoveHandler (PreInitEvent, value); }
  1760. }
  1761. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1762. public event EventHandler PreLoad {
  1763. add {
  1764. event_mask |= preload_mask;
  1765. Events.AddHandler (PreLoadEvent, value);
  1766. }
  1767. remove { Events.RemoveHandler (PreLoadEvent, value); }
  1768. }
  1769. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1770. public event EventHandler PreRenderComplete {
  1771. add {
  1772. event_mask |= prerendercomplete_mask;
  1773. Events.AddHandler (PreRenderCompleteEvent, value);
  1774. }
  1775. remove { Events.RemoveHandler (PreRenderCompleteEvent, value); }
  1776. }
  1777. [EditorBrowsable (EditorBrowsableState.Advanced)]
  1778. public event EventHandler SaveStateComplete {
  1779. add {
  1780. event_mask |= savestatecomplete_mask;
  1781. Events.AddHandler (SaveStateCompleteEvent, value);
  1782. }
  1783. remove { Events.RemoveHandler (SaveStateCompleteEvent, value); }
  1784. }
  1785. protected virtual void OnInitComplete (EventArgs e)
  1786. {
  1787. if ((event_mask & initcomplete_mask) != 0) {
  1788. EventHandler eh = (EventHandler) (Events [InitCompleteEvent]);
  1789. if (eh != null) eh (this, e);
  1790. }
  1791. }
  1792. protected virtual void OnLoadComplete (EventArgs e)
  1793. {
  1794. if ((event_mask & loadcomplete_mask) != 0) {
  1795. EventHandler eh = (EventHandler) (Events [LoadCompleteEvent]);
  1796. if (eh != null) eh (this, e);
  1797. }
  1798. }
  1799. protected virtual void OnPreInit (EventArgs e)
  1800. {
  1801. if ((event_mask & preinit_mask) != 0) {
  1802. EventHandler eh = (EventHandler) (Events [PreInitEvent]);
  1803. if (eh != null) eh (this, e);
  1804. }
  1805. }
  1806. protected virtual void OnPreLoad (EventArgs e)
  1807. {
  1808. if ((event_mask & preload_mask) != 0) {
  1809. EventHandler eh = (EventHandler) (Events [PreLoadEvent]);
  1810. if (eh != null) eh (this, e);
  1811. }
  1812. }
  1813. protected virtual void OnPreRenderComplete (EventArgs e)
  1814. {
  1815. if ((event_mask & prerendercomplete_mask) != 0) {
  1816. EventHandler eh = (EventHandler) (Events [PreRenderCompleteEvent]);
  1817. if (eh != null) eh (this, e);
  1818. }
  1819. if (Form == null)
  1820. return;
  1821. if (!Form.DetermineRenderUplevel ())
  1822. return;
  1823. string defaultButtonId = Form.DefaultButton;
  1824. /* figure out if we have some control we're going to focus */
  1825. if (String.IsNullOrEmpty (_focusedControlID)) {
  1826. _focusedControlID = Form.DefaultFocus;
  1827. if (String.IsNullOrEmpty (_focusedControlID))
  1828. _focusedControlID = defaultButtonId;
  1829. }
  1830. if (!String.IsNullOrEmpty (_focusedControlID)) {
  1831. ClientScript.RegisterWebFormClientScript ();
  1832. string webForm;
  1833. if (IsMultiForm)
  1834. webForm = theForm + ".";
  1835. else
  1836. webForm = String.Empty;
  1837. ClientScript.RegisterStartupScript (
  1838. typeof(Page),
  1839. "HtmlForm-DefaultButton-StartupScript",
  1840. "\n" + webForm + "WebForm_AutoFocus('" + _focusedControlID + "');\n", true);
  1841. }
  1842. if (Form.SubmitDisabledControls && _hasEnabledControlArray) {
  1843. ClientScript.RegisterWebFormClientScript ();
  1844. string webForm;
  1845. if (IsMultiForm)
  1846. webForm = theForm + ".";
  1847. else
  1848. webForm = String.Empty;
  1849. ClientScript.RegisterOnSubmitStatement (
  1850. typeof (Page),
  1851. "HtmlForm-SubmitDisabledControls-SubmitStatement",
  1852. webForm + "WebForm_ReEnableControls();");
  1853. }
  1854. }
  1855. internal void RegisterEnabledControl (Control control)
  1856. {
  1857. if (Form == null || !Page.Form.SubmitDisabledControls || !Page.Form.DetermineRenderUplevel ())
  1858. return;
  1859. _hasEnabledControlArray = true;
  1860. Page.ClientScript.RegisterArrayDeclaration (EnabledControlArrayID, String.Concat ("'", control.ClientID, "'"));
  1861. }
  1862. protected virtual void OnSaveStateComplete (EventArgs e)
  1863. {
  1864. if ((event_mask & savestatecomplete_mask) != 0) {
  1865. EventHandler eh = (EventHandler) (Events [SaveStateCompleteEvent]);
  1866. if (eh != null) eh (this, e);
  1867. }
  1868. }
  1869. public HtmlForm Form {
  1870. get { return _form; }
  1871. }
  1872. internal void RegisterForm (HtmlForm form)
  1873. {
  1874. _form = form;
  1875. }
  1876. [BrowsableAttribute (false)]
  1877. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1878. public Page PreviousPage {
  1879. get {
  1880. if (_doLoadPreviousPage) {
  1881. _doLoadPreviousPage = false;
  1882. LoadPreviousPageReference ();
  1883. }
  1884. return previousPage;
  1885. }
  1886. }
  1887. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1888. [BrowsableAttribute (false)]
  1889. public bool IsCallback {
  1890. get { return isCallback; }
  1891. }
  1892. [BrowsableAttribute (false)]
  1893. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1894. public bool IsCrossPagePostBack {
  1895. get { return isCrossPagePostBack; }
  1896. }
  1897. public new virtual char IdSeparator {
  1898. get {
  1899. //TODO: why override?
  1900. return base.IdSeparator;
  1901. }
  1902. }
  1903. string ProcessCallbackData ()
  1904. {
  1905. ICallbackEventHandler target = GetCallbackTarget ();
  1906. string callbackEventError = String.Empty;
  1907. ProcessRaiseCallbackEvent (target, ref callbackEventError);
  1908. return ProcessGetCallbackResult (target, callbackEventError);
  1909. }
  1910. ICallbackEventHandler GetCallbackTarget () {
  1911. string callbackTarget = _requestValueCollection [CallbackSourceID];
  1912. if (callbackTarget == null || callbackTarget.Length == 0)
  1913. throw new HttpException ("Callback target not provided.");
  1914. Control targetControl = FindControl (callbackTarget, true);
  1915. ICallbackEventHandler target = targetControl as ICallbackEventHandler;
  1916. if (target == null)
  1917. throw new HttpException (string.Format ("Invalid callback target '{0}'.", callbackTarget));
  1918. return target;
  1919. }
  1920. void ProcessRaiseCallbackEvent (ICallbackEventHandler target, ref string callbackEventError) {
  1921. string callbackArgument = _requestValueCollection [CallbackArgumentID];
  1922. try {
  1923. target.RaiseCallbackEvent (callbackArgument);
  1924. } catch (Exception ex) {
  1925. callbackEventError = String.Concat ("e", ex.Message);
  1926. }
  1927. }
  1928. string ProcessGetCallbackResult (ICallbackEventHandler target, string callbackEventError) {
  1929. string callBackResult;
  1930. try {
  1931. callBackResult = target.GetCallbackResult ();
  1932. } catch (Exception ex) {
  1933. return String.Concat ("e", ex.Message);
  1934. }
  1935. string eventValidation = ClientScript.GetEventValidationStateFormatted ();
  1936. return callbackEventError + (eventValidation == null ? "0" : eventValidation.Length.ToString ()) + "|" +
  1937. eventValidation + callBackResult;
  1938. }
  1939. [BrowsableAttribute (false)]
  1940. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  1941. public HtmlHead Header {
  1942. get { return htmlHeader; }
  1943. }
  1944. internal void SetHeader (HtmlHead header)
  1945. {
  1946. htmlHeader = header;
  1947. if (_title != null) {
  1948. htmlHeader.Title = _title;
  1949. _title = null;
  1950. }
  1951. }
  1952. protected bool AsyncMode {
  1953. get { return asyncMode; }
  1954. set { asyncMode = value; }
  1955. }
  1956. public TimeSpan AsyncTimeout {
  1957. get { return asyncTimeout; }
  1958. set { asyncTimeout = value; }
  1959. }
  1960. public bool IsAsync {
  1961. get { return AsyncMode; }
  1962. }
  1963. [MonoTODO ("Not Implemented")]
  1964. protected internal virtual string UniqueFilePathSuffix {
  1965. get {
  1966. throw new NotImplementedException ();
  1967. }
  1968. }
  1969. [MonoTODO ("Not Implemented")]
  1970. public int MaxPageStateFieldLength {
  1971. get {
  1972. throw new NotImplementedException ();
  1973. }
  1974. set {
  1975. throw new NotImplementedException ();
  1976. }
  1977. }
  1978. public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler)
  1979. {
  1980. AddOnPreRenderCompleteAsync (beginHandler, endHandler, null);
  1981. }
  1982. public void AddOnPreRenderCompleteAsync (BeginEventHandler beginHandler, EndEventHandler endHandler, Object state)
  1983. {
  1984. if (!IsAsync) {
  1985. throw new InvalidOperationException ("AddOnPreRenderCompleteAsync called and Page.IsAsync == false");
  1986. }
  1987. if (IsPrerendered) {
  1988. throw new InvalidOperationException ("AddOnPreRenderCompleteAsync can only be called before and during PreRender.");
  1989. }
  1990. if (beginHandler == null) {
  1991. throw new ArgumentNullException ("beginHandler");
  1992. }
  1993. if (endHandler == null) {
  1994. throw new ArgumentNullException ("endHandler");
  1995. }
  1996. RegisterAsyncTask (new PageAsyncTask (beginHandler, endHandler, null, state, false));
  1997. }
  1998. private List<PageAsyncTask> ParallelTasks {
  1999. get {
  2000. if (parallelTasks == null) {
  2001. parallelTasks = new List<PageAsyncTask>();
  2002. }
  2003. return parallelTasks;
  2004. }
  2005. }
  2006. private List<PageAsyncTask> SerialTasks {
  2007. get {
  2008. if (serialTasks == null) {
  2009. serialTasks = new List<PageAsyncTask> ();
  2010. }
  2011. return serialTasks;
  2012. }
  2013. }
  2014. public void RegisterAsyncTask (PageAsyncTask task)
  2015. {
  2016. if (task == null) {
  2017. throw new ArgumentNullException ("task");
  2018. }
  2019. if (task.ExecuteInParallel) {
  2020. ParallelTasks.Add (task);
  2021. }
  2022. else {
  2023. SerialTasks.Add (task);
  2024. }
  2025. }
  2026. public void ExecuteRegisteredAsyncTasks ()
  2027. {
  2028. if ((parallelTasks == null || parallelTasks.Count == 0) &&
  2029. (serialTasks == null || serialTasks.Count == 0)){
  2030. return;
  2031. }
  2032. if (parallelTasks != null) {
  2033. DateTime startExecution = DateTime.Now;
  2034. List<PageAsyncTask> localParallelTasks = parallelTasks;
  2035. parallelTasks = null; // Shouldn't execute tasks twice
  2036. List<IAsyncResult> asyncResults = new List<IAsyncResult>();
  2037. foreach (PageAsyncTask parallelTask in localParallelTasks) {
  2038. IAsyncResult result = parallelTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), parallelTask.State);
  2039. if (result.CompletedSynchronously) {
  2040. parallelTask.EndHandler (result);
  2041. }
  2042. else {
  2043. asyncResults.Add (result);
  2044. }
  2045. }
  2046. if (asyncResults.Count > 0) {
  2047. #if TARGET_JVM
  2048. TimeSpan timeout = AsyncTimeout;
  2049. long t1 = DateTime.Now.Ticks;
  2050. bool signalled = true;
  2051. for (int i = 0; i < asyncResults.Count; i++) {
  2052. if (asyncResults [i].IsCompleted)
  2053. continue;
  2054. if (signalled)
  2055. signalled = asyncResults [i].AsyncWaitHandle.WaitOne (timeout, false);
  2056. if (signalled) {
  2057. long t2 = DateTime.Now.Ticks;
  2058. timeout = AsyncTimeout - TimeSpan.FromTicks (t2 - t1);
  2059. if (timeout.Ticks <= 0)
  2060. signalled = false;
  2061. }
  2062. else {
  2063. localParallelTasks [i].TimeoutHandler (asyncResults [i]);
  2064. }
  2065. }
  2066. #else
  2067. WaitHandle [] waitArray = new WaitHandle [asyncResults.Count];
  2068. int i = 0;
  2069. for (i = 0; i < asyncResults.Count; i++) {
  2070. waitArray [i] = asyncResults [i].AsyncWaitHandle;
  2071. }
  2072. bool allSignalled = WaitHandle.WaitAll (waitArray, AsyncTimeout, false);
  2073. if (!allSignalled) {
  2074. for (i = 0; i < asyncResults.Count; i++) {
  2075. if (!asyncResults [i].IsCompleted) {
  2076. localParallelTasks [i].TimeoutHandler (asyncResults [i]);
  2077. }
  2078. }
  2079. }
  2080. #endif
  2081. }
  2082. DateTime endWait = DateTime.Now;
  2083. TimeSpan elapsed = endWait - startExecution;
  2084. if (elapsed <= AsyncTimeout) {
  2085. AsyncTimeout -= elapsed;
  2086. }
  2087. else {
  2088. AsyncTimeout = TimeSpan.FromTicks(0);
  2089. }
  2090. }
  2091. if (serialTasks != null) {
  2092. List<PageAsyncTask> localSerialTasks = serialTasks;
  2093. serialTasks = null; // Shouldn't execute tasks twice
  2094. foreach (PageAsyncTask serialTask in localSerialTasks) {
  2095. DateTime startExecution = DateTime.Now;
  2096. IAsyncResult result = serialTask.BeginHandler (this, EventArgs.Empty, new AsyncCallback (EndAsyncTaskCallback), serialTask);
  2097. if (result.CompletedSynchronously) {
  2098. serialTask.EndHandler (result);
  2099. }
  2100. else {
  2101. bool done = result.AsyncWaitHandle.WaitOne (AsyncTimeout, false);
  2102. if (!done && !result.IsCompleted) {
  2103. serialTask.TimeoutHandler (result);
  2104. }
  2105. }
  2106. DateTime endWait = DateTime.Now;
  2107. TimeSpan elapsed = endWait - startExecution;
  2108. if (elapsed <= AsyncTimeout) {
  2109. AsyncTimeout -= elapsed;
  2110. }
  2111. else {
  2112. AsyncTimeout = TimeSpan.FromTicks (0);
  2113. }
  2114. }
  2115. }
  2116. AsyncTimeout = TimeSpan.FromSeconds (DefaultAsyncTimeout);
  2117. }
  2118. void EndAsyncTaskCallback (IAsyncResult result)
  2119. {
  2120. PageAsyncTask task = (PageAsyncTask)result.AsyncState;
  2121. task.EndHandler (result);
  2122. }
  2123. public static HtmlTextWriter CreateHtmlTextWriterFromType (TextWriter tw, Type writerType)
  2124. {
  2125. Type htmlTextWriterType = typeof (HtmlTextWriter);
  2126. if (!htmlTextWriterType.IsAssignableFrom (writerType)) {
  2127. throw new HttpException (String.Format ("Type '{0}' cannot be assigned to HtmlTextWriter", writerType.FullName));
  2128. }
  2129. ConstructorInfo constructor = writerType.GetConstructor (new Type [] { typeof (TextWriter) });
  2130. if (constructor == null) {
  2131. throw new HttpException (String.Format ("Type '{0}' does not have a consturctor that takes a TextWriter as parameter", writerType.FullName));
  2132. }
  2133. return (HtmlTextWriter) Activator.CreateInstance(writerType, tw);
  2134. }
  2135. public ViewStateEncryptionMode ViewStateEncryptionMode {
  2136. get { return viewStateEncryptionMode; }
  2137. set { viewStateEncryptionMode = value; }
  2138. }
  2139. public void RegisterRequiresViewStateEncryption ()
  2140. {
  2141. controlRegisteredForViewStateEncryption = true;
  2142. }
  2143. private static byte [] AES_IV = null;
  2144. private static byte [] TripleDES_IV = null;
  2145. private static object locker = new object ();
  2146. private static bool isEncryptionInitialized = false;
  2147. private static void InitializeEncryption ()
  2148. {
  2149. if (isEncryptionInitialized) {
  2150. return;
  2151. }
  2152. lock (locker) {
  2153. if (isEncryptionInitialized) {
  2154. return;
  2155. }
  2156. string iv_string = "0BA48A9E-736D-40f8-954B-B2F62241F282";
  2157. AES_IV = new byte [16];
  2158. TripleDES_IV = new byte [8];
  2159. int i;
  2160. for (i = 0; i < AES_IV.Length; i++) {
  2161. AES_IV [i] = (byte) iv_string [i];
  2162. }
  2163. for (i = 0; i < TripleDES_IV.Length; i++) {
  2164. TripleDES_IV [i] = (byte) iv_string [i];
  2165. }
  2166. isEncryptionInitialized = true;
  2167. }
  2168. }
  2169. internal ICryptoTransform GetCryptoTransform (CryptoStreamMode cryptoStreamMode)
  2170. {
  2171. ICryptoTransform transform = null;
  2172. MachineKeySection config = (MachineKeySection) WebConfigurationManager.GetSection (machineKeyConfigPath);
  2173. byte [] vk = MachineKeySectionUtils.ValidationKeyBytes (config);
  2174. switch (config.Validation) {
  2175. case MachineKeyValidation.SHA1:
  2176. transform = SHA1.Create ();
  2177. break;
  2178. case MachineKeyValidation.MD5:
  2179. transform = MD5.Create ();
  2180. break;
  2181. case MachineKeyValidation.AES:
  2182. if (cryptoStreamMode == CryptoStreamMode.Read){
  2183. transform = Rijndael.Create().CreateDecryptor(vk, AES_IV);
  2184. } else {
  2185. transform = Rijndael.Create().CreateEncryptor(vk, AES_IV);
  2186. }
  2187. break;
  2188. case MachineKeyValidation.TripleDES:
  2189. if (cryptoStreamMode == CryptoStreamMode.Read){
  2190. transform = TripleDES.Create().CreateDecryptor(vk, TripleDES_IV);
  2191. } else {
  2192. transform = TripleDES.Create().CreateEncryptor(vk, TripleDES_IV);
  2193. }
  2194. break;
  2195. }
  2196. return transform;
  2197. }
  2198. internal bool NeedViewStateEncryption {
  2199. get {
  2200. return (ViewStateEncryptionMode == ViewStateEncryptionMode.Always ||
  2201. (ViewStateEncryptionMode == ViewStateEncryptionMode.Auto &&
  2202. controlRegisteredForViewStateEncryption));
  2203. }
  2204. }
  2205. void ApplyMasterPage ()
  2206. {
  2207. if (masterPageFile != null && masterPageFile.Length > 0) {
  2208. ArrayList appliedMasterPageFiles = new ArrayList ();
  2209. if (Master != null) {
  2210. MasterPage.ApplyMasterPageRecursive (Master, appliedMasterPageFiles);
  2211. Master.Page = this;
  2212. Controls.Clear ();
  2213. Controls.Add (Master);
  2214. }
  2215. }
  2216. }
  2217. [DefaultValueAttribute ("")]
  2218. public virtual string MasterPageFile {
  2219. get { return masterPageFile; }
  2220. set {
  2221. masterPageFile = value;
  2222. masterPage = null;
  2223. }
  2224. }
  2225. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  2226. [BrowsableAttribute (false)]
  2227. public MasterPage Master {
  2228. get {
  2229. if (Context == null || String.IsNullOrEmpty (masterPageFile))
  2230. return null;
  2231. if (masterPage == null)
  2232. masterPage = MasterPage.CreateMasterPage (this, Context, masterPageFile, contentTemplates);
  2233. return masterPage;
  2234. }
  2235. }
  2236. public void SetFocus (string clientID)
  2237. {
  2238. if (String.IsNullOrEmpty (clientID))
  2239. throw new ArgumentNullException ("control");
  2240. if (IsPrerendered)
  2241. throw new InvalidOperationException ("SetFocus can only be called before and during PreRender.");
  2242. if(Form==null)
  2243. throw new InvalidOperationException ("A form tag with runat=server must exist on the Page to use SetFocus() or the Focus property.");
  2244. _focusedControlID = clientID;
  2245. }
  2246. public void SetFocus (Control control)
  2247. {
  2248. if (control == null)
  2249. throw new ArgumentNullException ("control");
  2250. SetFocus (control.ClientID);
  2251. }
  2252. [EditorBrowsable (EditorBrowsableState.Advanced)]
  2253. public void RegisterRequiresControlState (Control control)
  2254. {
  2255. if (control == null)
  2256. throw new ArgumentNullException ("control");
  2257. if (RequiresControlState (control))
  2258. return;
  2259. if (requireStateControls == null)
  2260. requireStateControls = new ArrayList ();
  2261. int n = requireStateControls.Add (control);
  2262. if (_savedControlState == null || n >= _savedControlState.Length)
  2263. return;
  2264. for (Control parent = control.Parent; parent != null; parent = parent.Parent)
  2265. if (parent.IsChildControlStateCleared)
  2266. return;
  2267. object state = _savedControlState [n];
  2268. if (state != null)
  2269. control.LoadControlState (state);
  2270. }
  2271. public bool RequiresControlState (Control control)
  2272. {
  2273. if (requireStateControls == null) return false;
  2274. return requireStateControls.Contains (control);
  2275. }
  2276. [EditorBrowsable (EditorBrowsableState.Advanced)]
  2277. public void UnregisterRequiresControlState (Control control)
  2278. {
  2279. if (requireStateControls != null)
  2280. requireStateControls.Remove (control);
  2281. }
  2282. public ValidatorCollection GetValidators (string validationGroup)
  2283. {
  2284. if (validationGroup == String.Empty)
  2285. validationGroup = null;
  2286. ValidatorCollection col = new ValidatorCollection ();
  2287. if (_validators == null)
  2288. return col;
  2289. foreach (IValidator v in _validators)
  2290. if (BelongsToGroup(v, validationGroup))
  2291. col.Add(v);
  2292. return col;
  2293. }
  2294. bool BelongsToGroup(IValidator v, string validationGroup) {
  2295. BaseValidator validator = v as BaseValidator;
  2296. if (validationGroup == null)
  2297. return validator == null || String.IsNullOrEmpty (validator.ValidationGroup);
  2298. else
  2299. return validator != null && validator.ValidationGroup == validationGroup;
  2300. }
  2301. public virtual void Validate (string validationGroup)
  2302. {
  2303. is_validated = true;
  2304. ValidateCollection (GetValidators (validationGroup));
  2305. }
  2306. object SavePageControlState ()
  2307. {
  2308. if (requireStateControls == null) return null;
  2309. object[] state = new object [requireStateControls.Count];
  2310. bool allNull = true;
  2311. for (int n=0; n<state.Length; n++) {
  2312. state [n] = ((Control) requireStateControls [n]).SaveControlState ();
  2313. if (state [n] != null) allNull = false;
  2314. TraceContext trace = (Context != null && Context.Trace.IsEnabled) ? Context.Trace : null;
  2315. if (trace != null)
  2316. trace.SaveControlState ((Control) requireStateControls [n], state [n]);
  2317. }
  2318. if (allNull) return null;
  2319. else return state;
  2320. }
  2321. void LoadPageControlState (object data)
  2322. {
  2323. _savedControlState = (object []) data;
  2324. if (requireStateControls == null) return;
  2325. int max = Math.Min (requireStateControls.Count, _savedControlState != null ? _savedControlState.Length : requireStateControls.Count);
  2326. for (int n=0; n < max; n++) {
  2327. Control ctl = (Control) requireStateControls [n];
  2328. ctl.LoadControlState (_savedControlState != null ? _savedControlState [n] : null);
  2329. }
  2330. }
  2331. void LoadPreviousPageReference ()
  2332. {
  2333. if (_requestValueCollection != null) {
  2334. string prevPage = _requestValueCollection [PreviousPageID];
  2335. if (prevPage != null) {
  2336. #if TARGET_J2EE
  2337. if (getFacesContext () != null) {
  2338. IHttpHandler handler = Context.ApplicationInstance.GetHandler (Context, prevPage);
  2339. Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
  2340. if (_context.Items.Contains (CrossPagePostBack)) {
  2341. previousPage = (Page) _context.Items [CrossPagePostBack];
  2342. _context.Items.Remove (CrossPagePostBack);
  2343. }
  2344. return;
  2345. }
  2346. #else
  2347. IHttpHandler handler = PageParser.GetCompiledPageInstance (prevPage, Server.MapPath (prevPage), Context);
  2348. previousPage = (Page) handler;
  2349. previousPage.isCrossPagePostBack = true;
  2350. Server.Execute (handler, null, true, _context.Request.CurrentExecutionFilePath, null, false, false);
  2351. #endif
  2352. }
  2353. }
  2354. }
  2355. Hashtable contentTemplates;
  2356. [EditorBrowsable (EditorBrowsableState.Never)]
  2357. protected internal void AddContentTemplate (string templateName, ITemplate template)
  2358. {
  2359. if (contentTemplates == null)
  2360. contentTemplates = new Hashtable ();
  2361. contentTemplates [templateName] = template;
  2362. }
  2363. PageTheme _pageTheme;
  2364. internal PageTheme PageTheme {
  2365. get { return _pageTheme; }
  2366. }
  2367. PageTheme _styleSheetPageTheme;
  2368. internal PageTheme StyleSheetPageTheme {
  2369. get { return _styleSheetPageTheme; }
  2370. }
  2371. Stack dataItemCtx;
  2372. internal void PushDataItemContext (object o) {
  2373. if (dataItemCtx == null)
  2374. dataItemCtx = new Stack ();
  2375. dataItemCtx.Push (o);
  2376. }
  2377. internal void PopDataItemContext () {
  2378. if (dataItemCtx == null)
  2379. throw new InvalidOperationException ();
  2380. dataItemCtx.Pop ();
  2381. }
  2382. public object GetDataItem() {
  2383. if (dataItemCtx == null || dataItemCtx.Count == 0)
  2384. throw new InvalidOperationException ("No data item");
  2385. return dataItemCtx.Peek ();
  2386. }
  2387. protected internal override void OnInit (EventArgs e)
  2388. {
  2389. base.OnInit (e);
  2390. ArrayList themes = new ArrayList();
  2391. if (StyleSheetPageTheme != null && StyleSheetPageTheme.GetStyleSheets () != null)
  2392. themes.AddRange (StyleSheetPageTheme.GetStyleSheets ());
  2393. if (PageTheme != null && PageTheme.GetStyleSheets () != null)
  2394. themes.AddRange (PageTheme.GetStyleSheets ());
  2395. if (themes.Count > 0 && Header == null)
  2396. throw new InvalidOperationException ("Using themed css files requires a header control on the page.");
  2397. foreach (string lss in themes) {
  2398. HtmlLink hl = new HtmlLink ();
  2399. hl.Href = lss;
  2400. hl.Attributes["type"] = "text/css";
  2401. hl.Attributes["rel"] = "stylesheet";
  2402. Header.Controls.Add (hl);
  2403. }
  2404. }
  2405. #endif
  2406. #if NET_2_0
  2407. [MonoTODO ("Not implemented. Only used by .net aspx parser")]
  2408. protected object GetWrappedFileDependencies (string [] list)
  2409. {
  2410. return list;
  2411. }
  2412. [MonoTODO ("Does nothing. Used by .net aspx parser")]
  2413. protected virtual void InitializeCulture ()
  2414. {
  2415. }
  2416. [MonoTODO ("Does nothing. Used by .net aspx parser")]
  2417. protected internal void AddWrappedFileDependencies (object virtualFileDependencies)
  2418. {
  2419. }
  2420. #endif
  2421. }
  2422. }