Page.cs 78 KB

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