Page.cs 77 KB

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