Page.cs 76 KB

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