Page.cs 77 KB

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