ScriptManager.cs 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  1. //
  2. // ScriptManager.cs
  3. //
  4. // Author:
  5. // Igor Zelmanovich <[email protected]>
  6. //
  7. // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
  8. //
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections.Generic;
  31. using System.Text;
  32. using System.ComponentModel;
  33. using System.Security.Permissions;
  34. using System.Collections.Specialized;
  35. using System.Collections;
  36. using System.Web.Handlers;
  37. using System.Reflection;
  38. using System.Web.Configuration;
  39. using System.Web.UI.HtmlControls;
  40. using System.IO;
  41. using System.Globalization;
  42. using System.Threading;
  43. using System.Web.Script.Serialization;
  44. using System.Web.Script.Services;
  45. using System.Xml;
  46. namespace System.Web.UI
  47. {
  48. [ParseChildrenAttribute (true)]
  49. [DefaultPropertyAttribute ("Scripts")]
  50. [DesignerAttribute ("System.Web.UI.Design.ScriptManagerDesigner, System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
  51. [NonVisualControlAttribute]
  52. [PersistChildrenAttribute (false)]
  53. [AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  54. [AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  55. public class ScriptManager : Control, IPostBackDataHandler
  56. {
  57. // the keywords are used in fomatting async response
  58. const string updatePanel = "updatePanel";
  59. const string hiddenField = "hiddenField";
  60. const string arrayDeclaration = "arrayDeclaration";
  61. const string scriptBlock = "scriptBlock";
  62. const string expando = "expando";
  63. const string onSubmit = "onSubmit";
  64. const string asyncPostBackControlIDs = "asyncPostBackControlIDs";
  65. const string postBackControlIDs = "postBackControlIDs";
  66. const string updatePanelIDs = "updatePanelIDs";
  67. const string asyncPostBackTimeout = "asyncPostBackTimeout";
  68. const string childUpdatePanelIDs = "childUpdatePanelIDs";
  69. const string panelsToRefreshIDs = "panelsToRefreshIDs";
  70. const string formAction = "formAction";
  71. const string dataItem = "dataItem";
  72. const string dataItemJson = "dataItemJson";
  73. const string scriptDispose = "scriptDispose";
  74. const string pageRedirect = "pageRedirect";
  75. const string error = "error";
  76. const string pageTitle = "pageTitle";
  77. const string focus = "focus";
  78. const string scriptContentNoTags = "ScriptContentNoTags";
  79. const string scriptContentWithTags = "ScriptContentWithTags";
  80. const string scriptPath = "ScriptPath";
  81. static readonly object ScriptManagerKey = new object ();
  82. int _asyncPostBackTimeout = 90;
  83. List<Control> _asyncPostBackControls;
  84. List<Control> _postBackControls;
  85. List<UpdatePanel> _childUpdatePanels;
  86. List<UpdatePanel> _panelsToRefresh;
  87. List<UpdatePanel> _updatePanels;
  88. ScriptReferenceCollection _scripts;
  89. ServiceReferenceCollection _services;
  90. bool _isInAsyncPostBack;
  91. bool _isInPartialRendering;
  92. string _asyncPostBackSourceElementID;
  93. ScriptMode _scriptMode = ScriptMode.Auto;
  94. bool _enableScriptGlobalization;
  95. bool _enableScriptLocalization;
  96. string _scriptPath;
  97. ScriptEntry _clientScriptBlocks;
  98. ScriptEntry _startupScriptBlocks;
  99. ScriptEntry _scriptIncludes;
  100. ScriptEntry _onSubmitStatements;
  101. List<ArrayDeclaration> _arrayDeclarations;
  102. Hashtable _hiddenFields;
  103. List<IScriptControl> _registeredScriptControls;
  104. Dictionary<IExtenderControl, Control> _registeredExtenderControls;
  105. bool? _supportsPartialRendering;
  106. bool _enablePartialRendering = true;
  107. bool _init;
  108. string _panelToRefreshID;
  109. Dictionary<Control, DataItemEntry> _dataItems;
  110. bool _enablePageMethods;
  111. string _controlIDToFocus;
  112. bool _allowCustomErrorsRedirect = true;
  113. string _asyncPostBackErrorMessage;
  114. List<DisposeScriptEntry> _disposeScripts;
  115. List<ScriptReferenceEntry> _scriptToRegister;
  116. bool _loadScriptsBeforeUI = true;
  117. AuthenticationServiceManager _authenticationService;
  118. ProfileServiceManager _profileService;
  119. [DefaultValue (true)]
  120. [Category ("Behavior")]
  121. public bool AllowCustomErrorsRedirect {
  122. get {
  123. return _allowCustomErrorsRedirect;
  124. }
  125. set {
  126. _allowCustomErrorsRedirect = value;
  127. }
  128. }
  129. [Category ("Behavior")]
  130. [DefaultValue ("")]
  131. public string AsyncPostBackErrorMessage {
  132. get {
  133. if (String.IsNullOrEmpty (_asyncPostBackErrorMessage))
  134. return String.Empty;
  135. return _asyncPostBackErrorMessage;
  136. }
  137. set {
  138. _asyncPostBackErrorMessage = value;
  139. }
  140. }
  141. [Browsable (false)]
  142. public string AsyncPostBackSourceElementID {
  143. get {
  144. if (_asyncPostBackSourceElementID == null)
  145. return String.Empty;
  146. return _asyncPostBackSourceElementID;
  147. }
  148. }
  149. [DefaultValue (90)]
  150. [Category ("Behavior")]
  151. public int AsyncPostBackTimeout {
  152. get {
  153. return _asyncPostBackTimeout;
  154. }
  155. set {
  156. _asyncPostBackTimeout = value;
  157. }
  158. }
  159. [Category ("Behavior")]
  160. [MergableProperty (false)]
  161. [DefaultValue ("")]
  162. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  163. [PersistenceMode (PersistenceMode.InnerProperty)]
  164. public AuthenticationServiceManager AuthenticationService {
  165. get {
  166. if (_authenticationService == null)
  167. _authenticationService = new AuthenticationServiceManager ();
  168. return _authenticationService;
  169. }
  170. }
  171. [Category ("Behavior")]
  172. [DefaultValue (false)]
  173. public bool EnablePageMethods {
  174. get {
  175. return _enablePageMethods;
  176. }
  177. set {
  178. _enablePageMethods = value;
  179. }
  180. }
  181. [DefaultValue (true)]
  182. [Category ("Behavior")]
  183. public bool EnablePartialRendering {
  184. get {
  185. return _enablePartialRendering;
  186. }
  187. set {
  188. if (_init)
  189. throw new InvalidOperationException ();
  190. _enablePartialRendering = value;
  191. }
  192. }
  193. [DefaultValue (false)]
  194. [Category ("Behavior")]
  195. public bool EnableScriptGlobalization {
  196. get {
  197. return _enableScriptGlobalization;
  198. }
  199. set {
  200. _enableScriptGlobalization = value;
  201. }
  202. }
  203. [Category ("Behavior")]
  204. [DefaultValue (false)]
  205. public bool EnableScriptLocalization {
  206. get {
  207. return _enableScriptLocalization;
  208. }
  209. set {
  210. _enableScriptLocalization = value;
  211. }
  212. }
  213. [Browsable (false)]
  214. public bool IsDebuggingEnabled {
  215. get {
  216. if (IsDeploymentRetail)
  217. return false;
  218. CompilationSection compilation = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  219. if (!compilation.Debug && (ScriptMode == ScriptMode.Auto || ScriptMode == ScriptMode.Inherit))
  220. return false;
  221. if (ScriptMode == ScriptMode.Release)
  222. return false;
  223. return true;
  224. }
  225. }
  226. bool IsDeploymentRetail {
  227. get {
  228. #if TARGET_J2EE
  229. return false;
  230. #else
  231. DeploymentSection deployment = (DeploymentSection) WebConfigurationManager.GetSection ("system.web/deployment");
  232. return deployment.Retail;
  233. #endif
  234. }
  235. }
  236. [Browsable (false)]
  237. public bool IsInAsyncPostBack {
  238. get {
  239. return _isInAsyncPostBack;
  240. }
  241. }
  242. internal bool IsInPartialRendering {
  243. get {
  244. return _isInPartialRendering;
  245. }
  246. set {
  247. _isInPartialRendering = value;
  248. }
  249. }
  250. [Category ("Behavior")]
  251. [DefaultValue (true)]
  252. public bool LoadScriptsBeforeUI {
  253. get {
  254. return _loadScriptsBeforeUI;
  255. }
  256. set {
  257. _loadScriptsBeforeUI = value;
  258. }
  259. }
  260. [PersistenceMode (PersistenceMode.InnerProperty)]
  261. [DefaultValue ("")]
  262. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  263. [Category ("Behavior")]
  264. [MergableProperty (false)]
  265. public ProfileServiceManager ProfileService {
  266. get {
  267. if (_profileService == null)
  268. _profileService = new ProfileServiceManager ();
  269. return _profileService;
  270. }
  271. }
  272. [Category ("Behavior")]
  273. #if TARGET_J2EE
  274. [MonoLimitation ("The 'Auto' value is the same as 'Debug'.")]
  275. #endif
  276. public ScriptMode ScriptMode {
  277. get {
  278. return _scriptMode;
  279. }
  280. set {
  281. if (value == ScriptMode.Inherit)
  282. value = ScriptMode.Auto;
  283. _scriptMode = value;
  284. }
  285. }
  286. [DefaultValue ("")]
  287. [Category ("Behavior")]
  288. public string ScriptPath {
  289. get {
  290. if (_scriptPath == null)
  291. return String.Empty;
  292. return _scriptPath;
  293. }
  294. set {
  295. _scriptPath = value;
  296. }
  297. }
  298. [PersistenceMode (PersistenceMode.InnerProperty)]
  299. [DefaultValue ("")]
  300. [Category ("Behavior")]
  301. [MergableProperty (false)]
  302. public ScriptReferenceCollection Scripts {
  303. get {
  304. if (_scripts == null)
  305. _scripts = new ScriptReferenceCollection ();
  306. return _scripts;
  307. }
  308. }
  309. [PersistenceMode (PersistenceMode.InnerProperty)]
  310. [DefaultValue ("")]
  311. [MergableProperty (false)]
  312. [Category ("Behavior")]
  313. public ServiceReferenceCollection Services {
  314. get {
  315. if (_services == null)
  316. _services = new ServiceReferenceCollection ();
  317. return _services;
  318. }
  319. }
  320. [DefaultValue (true)]
  321. [Browsable (false)]
  322. public bool SupportsPartialRendering {
  323. get {
  324. if (!_supportsPartialRendering.HasValue)
  325. _supportsPartialRendering = CheckSupportsPartialRendering ();
  326. return _supportsPartialRendering.Value;
  327. }
  328. set {
  329. if (_init)
  330. throw new InvalidOperationException ();
  331. if (!EnablePartialRendering && value)
  332. throw new InvalidOperationException ("The SupportsPartialRendering property cannot be set when EnablePartialRendering is false.");
  333. #if TARGET_J2EE
  334. if (!ServerSoftwareSupportsPartialRendering && value)
  335. throw new InvalidOperationException ("The server software does not supports partial rendering.");
  336. #endif
  337. _supportsPartialRendering = value;
  338. }
  339. }
  340. bool CheckSupportsPartialRendering () {
  341. if (!EnablePartialRendering)
  342. return false;
  343. #if TARGET_J2EE
  344. if (!ServerSoftwareSupportsPartialRendering)
  345. return false;
  346. #endif
  347. // TODO: consider browser capabilities
  348. return true;
  349. }
  350. #if TARGET_J2EE
  351. bool? _serverSoftwareSupportsPartialRendering;
  352. bool ServerSoftwareSupportsPartialRendering {
  353. get {
  354. if (!_serverSoftwareSupportsPartialRendering.HasValue)
  355. _serverSoftwareSupportsPartialRendering = CheckServerSoftwareSupportsPartialRendering ();
  356. return _serverSoftwareSupportsPartialRendering.Value;
  357. }
  358. }
  359. bool CheckServerSoftwareSupportsPartialRendering () {
  360. string serverSoftware = Context.Request.ServerVariables ["SERVER_SOFTWARE"];
  361. if (!String.IsNullOrEmpty (serverSoftware)) {
  362. if (serverSoftware.IndexOf ("WebSphere", StringComparison.OrdinalIgnoreCase) >= 0)
  363. return false;
  364. if (serverSoftware.IndexOf ("Jetspeed", StringComparison.OrdinalIgnoreCase) >= 0)
  365. return false;
  366. }
  367. return true;
  368. }
  369. #endif
  370. [EditorBrowsable (EditorBrowsableState.Never)]
  371. [Browsable (false)]
  372. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  373. public override bool Visible {
  374. get {
  375. return true;
  376. }
  377. set {
  378. throw new NotImplementedException ();
  379. }
  380. }
  381. [Category ("Action")]
  382. public event EventHandler<AsyncPostBackErrorEventArgs> AsyncPostBackError;
  383. [Category ("Action")]
  384. public event EventHandler<ScriptReferenceEventArgs> ResolveScriptReference;
  385. public static ScriptManager GetCurrent (Page page) {
  386. if (page == null)
  387. throw new ArgumentNullException("page");
  388. return (ScriptManager) page.Items [ScriptManagerKey];
  389. }
  390. static void SetCurrent (Page page, ScriptManager instance) {
  391. page.Items [ScriptManagerKey] = instance;
  392. }
  393. protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection) {
  394. _isInAsyncPostBack = true;
  395. string arg = postCollection [postDataKey];
  396. if (!String.IsNullOrEmpty (arg)) {
  397. string [] args = arg.Split ('|');
  398. _panelToRefreshID = args [0];
  399. _asyncPostBackSourceElementID = args [1];
  400. return true;
  401. }
  402. return false;
  403. }
  404. protected internal virtual void OnAsyncPostBackError (AsyncPostBackErrorEventArgs e) {
  405. if (AsyncPostBackError != null)
  406. AsyncPostBackError (this, e);
  407. }
  408. protected override void OnInit (EventArgs e) {
  409. base.OnInit (e);
  410. if (GetCurrent (Page) != null)
  411. throw new InvalidOperationException ("Only one instance of a ScriptManager can be added to the page.");
  412. SetCurrent (Page, this);
  413. Page.Error += new EventHandler (OnPageError);
  414. _init = true;
  415. }
  416. void OnPageError (object sender, EventArgs e) {
  417. if (IsInAsyncPostBack)
  418. OnAsyncPostBackError (new AsyncPostBackErrorEventArgs (Context.Error));
  419. }
  420. protected override void OnPreRender (EventArgs e) {
  421. base.OnPreRender (e);
  422. Page.PreRenderComplete += new EventHandler (OnPreRenderComplete);
  423. if (IsInAsyncPostBack) {
  424. Page.SetRenderMethodDelegate (RenderPageCallback);
  425. }
  426. else {
  427. if (EnableScriptGlobalization) {
  428. CultureInfo culture = Thread.CurrentThread.CurrentCulture;
  429. string script = String.Format ("var __cultureInfo = '{0}';", JavaScriptSerializer.DefaultSerializer.Serialize (new CultureInfoSerializer (culture)));
  430. RegisterClientScriptBlock (this, typeof (ScriptManager), "ScriptGlobalization", script, true);
  431. }
  432. // Register dispose script
  433. if (_disposeScripts != null && _disposeScripts.Count > 0) {
  434. StringBuilder sb = new StringBuilder ();
  435. sb.AppendLine ();
  436. for (int i = 0; i < _disposeScripts.Count; i++) {
  437. DisposeScriptEntry entry = _disposeScripts [i];
  438. if (IsMultiForm)
  439. sb.Append ("Sys.WebForms.PageRequestManager.getInstance($get(\"" + Page.Form.ClientID + "\"))._registerDisposeScript(\"");
  440. else
  441. sb.Append ("Sys.WebForms.PageRequestManager.getInstance()._registerDisposeScript(\"");
  442. sb.Append (entry.UpdatePanel.ClientID);
  443. sb.Append ("\", ");
  444. sb.Append (JavaScriptSerializer.DefaultSerializer.Serialize (entry.Script)); //JavaScriptSerializer.Serialize used escape script literal
  445. sb.AppendLine (");");
  446. }
  447. RegisterStartupScript (this, typeof (ExtenderControl), "disposeScripts;", sb.ToString (), true);
  448. }
  449. #if TARGET_DOTNET
  450. // to cause webform client script being included
  451. Page.ClientScript.GetPostBackEventReference (new PostBackOptions (this, null, null, false, false, false, true, true, null));
  452. #else
  453. Page.ClientScript.GetPostBackEventReference (this, null);
  454. #endif
  455. }
  456. }
  457. void OnPreRenderComplete (object sender, EventArgs e) {
  458. // Resolve Scripts
  459. ScriptReference ajaxScript = new ScriptReference ("MicrosoftAjax.js", String.Empty);
  460. ajaxScript.NotifyScriptLoaded = false;
  461. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxScript));
  462. ScriptReference ajaxWebFormsScript = new ScriptReference ("MicrosoftAjaxWebForms.js", String.Empty);
  463. ajaxWebFormsScript.NotifyScriptLoaded = false;
  464. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxWebFormsScript));
  465. ScriptReference ajaxExtensionScript = null;
  466. ScriptReference ajaxWebFormsExtensionScript = null;
  467. if (IsMultiForm) {
  468. ajaxExtensionScript = new ScriptReference ("MicrosoftAjaxExtension.js", String.Empty);
  469. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxExtensionScript));
  470. ajaxWebFormsExtensionScript = new ScriptReference ("MicrosoftAjaxWebFormsExtension.js", String.Empty);
  471. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxWebFormsExtensionScript));
  472. }
  473. foreach (ScriptReferenceEntry script in GetScriptReferences ()) {
  474. OnResolveScriptReference (new ScriptReferenceEventArgs (script.ScriptReference));
  475. if (!IsInAsyncPostBack || (script.Control != this && HasBeenRendered (script.Control))) {
  476. if (_scriptToRegister == null)
  477. _scriptToRegister = new List<ScriptReferenceEntry> ();
  478. _scriptToRegister.Add (script);
  479. }
  480. }
  481. if (!IsInAsyncPostBack) {
  482. // Register Ajax framework script.
  483. RegisterScriptReference (ajaxScript, true);
  484. if (IsMultiForm) {
  485. RegisterScriptReference (ajaxExtensionScript, true);
  486. RegisterClientScriptBlock (this, typeof (ScriptManager), "Sys.Application", "\nSys.Application._initialize(document.getElementById('" + Page.Form.ClientID + "'));\n", true);
  487. }
  488. StringBuilder sb = new StringBuilder ();
  489. sb.AppendLine ("if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');");
  490. ScriptingProfileServiceSection profileService = (ScriptingProfileServiceSection) WebConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/profileService");
  491. if (profileService.Enabled)
  492. sb.AppendLine ("Sys.Services._ProfileService.DefaultWebServicePath = '" + ResolveClientUrl ("~" + System.Web.Script.Services.ProfileService.DefaultWebServicePath) + "';");
  493. if (_profileService != null && !String.IsNullOrEmpty (_profileService.Path))
  494. sb.AppendLine ("Sys.Services.ProfileService.set_path('" + ResolveUrl (_profileService.Path) + "');");
  495. ScriptingAuthenticationServiceSection authenticationService = (ScriptingAuthenticationServiceSection) WebConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/authenticationService");
  496. if (authenticationService.Enabled)
  497. sb.AppendLine ("Sys.Services._AuthenticationService.DefaultWebServicePath = '" + ResolveClientUrl ("~/Authentication_JSON_AppService.axd") + "';");
  498. if (_authenticationService != null && !String.IsNullOrEmpty (_authenticationService.Path))
  499. sb.AppendLine ("Sys.Services.AuthenticationService.set_path('" + ResolveUrl (_authenticationService.Path) + "');");
  500. RegisterClientScriptBlock (this, typeof (ScriptManager), "Framework", sb.ToString (), true);
  501. RegisterScriptReference (ajaxWebFormsScript, true);
  502. if (IsMultiForm)
  503. RegisterScriptReference (ajaxWebFormsExtensionScript, true);
  504. }
  505. // Register Scripts
  506. if (_scriptToRegister != null)
  507. for (int i = 0; i < _scriptToRegister.Count; i++)
  508. RegisterScriptReference (_scriptToRegister [i].ScriptReference, _scriptToRegister [i].LoadScriptsBeforeUI);
  509. if (!IsInAsyncPostBack) {
  510. // Register services
  511. if (_services != null && _services.Count > 0) {
  512. for (int i = 0; i < _services.Count; i++) {
  513. RegisterServiceReference (_services [i]);
  514. }
  515. }
  516. if (EnablePageMethods) {
  517. LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (Page.GetType (), Page.Request.FilePath);
  518. RegisterClientScriptBlock (this, typeof (ScriptManager), "PageMethods", logicalTypeInfo.Proxy, true);
  519. }
  520. // Register startup script
  521. if (IsMultiForm)
  522. RegisterStartupScript (this, typeof (ExtenderControl), "Sys.Application.initialize();", "Sys.Application.getInstance($get(\"" + Page.Form.ClientID + "\")).initialize();\n", true);
  523. else
  524. RegisterStartupScript (this, typeof (ExtenderControl), "Sys.Application.initialize();", "Sys.Application.initialize();\n", true);
  525. }
  526. }
  527. #if TARGET_J2EE
  528. bool IsMultiForm {
  529. get {
  530. Mainsoft.Web.Configuration.PagesSection pageSection = (Mainsoft.Web.Configuration.PagesSection) WebConfigurationManager.GetSection ("mainsoft.web/pages");
  531. if (pageSection != null)
  532. return pageSection.MultiForm;
  533. return false;
  534. }
  535. }
  536. #else
  537. bool IsMultiForm {
  538. get { return false; }
  539. }
  540. #endif
  541. static bool HasBeenRendered (Control control) {
  542. if (control == null)
  543. return false;
  544. UpdatePanel parent = control.Parent as UpdatePanel;
  545. if (parent != null && parent.RequiresUpdate)
  546. return true;
  547. return HasBeenRendered (control.Parent);
  548. }
  549. IEnumerable<ScriptReferenceEntry> GetScriptReferences () {
  550. if (_scripts != null && _scripts.Count > 0) {
  551. for (int i = 0; i < _scripts.Count; i++) {
  552. yield return new ScriptReferenceEntry (this, _scripts [i], LoadScriptsBeforeUI);
  553. }
  554. }
  555. if (_registeredScriptControls != null && _registeredScriptControls.Count > 0) {
  556. for (int i = 0; i < _registeredScriptControls.Count; i++) {
  557. IEnumerable<ScriptReference> scripts = _registeredScriptControls [i].GetScriptReferences ();
  558. if (scripts != null)
  559. foreach (ScriptReference s in scripts)
  560. yield return new ScriptReferenceEntry ((Control) _registeredScriptControls [i], s, LoadScriptsBeforeUI);
  561. }
  562. }
  563. if (_registeredExtenderControls != null && _registeredExtenderControls.Count > 0) {
  564. foreach (IExtenderControl ex in _registeredExtenderControls.Keys) {
  565. IEnumerable<ScriptReference> scripts = ex.GetScriptReferences ();
  566. if (scripts != null)
  567. foreach (ScriptReference s in scripts)
  568. yield return new ScriptReferenceEntry ((Control) ex, s, LoadScriptsBeforeUI);
  569. }
  570. }
  571. }
  572. protected virtual void OnResolveScriptReference (ScriptReferenceEventArgs e) {
  573. if (ResolveScriptReference != null)
  574. ResolveScriptReference (this, e);
  575. }
  576. protected virtual void RaisePostDataChangedEvent () {
  577. UpdatePanel up = Page.FindControl (_panelToRefreshID) as UpdatePanel;
  578. if (up != null && up.ChildrenAsTriggers)
  579. up.Update ();
  580. }
  581. public static void RegisterArrayDeclaration (Control control, string arrayName, string arrayValue) {
  582. RegisterArrayDeclaration (control.Page, arrayName, arrayValue);
  583. }
  584. public static void RegisterArrayDeclaration (Page page, string arrayName, string arrayValue) {
  585. ScriptManager sm = GetCurrent (page);
  586. if (sm.IsInAsyncPostBack)
  587. sm.RegisterArrayDeclaration (arrayName, arrayValue);
  588. else
  589. page.ClientScript.RegisterArrayDeclaration (arrayName, arrayValue);
  590. }
  591. void RegisterArrayDeclaration (string arrayName, string arrayValue) {
  592. if (_arrayDeclarations == null)
  593. _arrayDeclarations = new List<ArrayDeclaration> ();
  594. _arrayDeclarations.Add (new ArrayDeclaration (arrayName, arrayValue));
  595. }
  596. public void RegisterAsyncPostBackControl (Control control) {
  597. if (control == null)
  598. return;
  599. if (_asyncPostBackControls == null)
  600. _asyncPostBackControls = new List<Control> ();
  601. if (_asyncPostBackControls.Contains (control))
  602. return;
  603. _asyncPostBackControls.Add (control);
  604. }
  605. public static void RegisterClientScriptBlock (Control control, Type type, string key, string script, bool addScriptTags) {
  606. RegisterClientScriptBlock (control.Page, type, key, script, addScriptTags);
  607. }
  608. public static void RegisterClientScriptBlock (Page page, Type type, string key, string script, bool addScriptTags) {
  609. ScriptManager sm = GetCurrent (page);
  610. if (sm.IsInAsyncPostBack)
  611. RegisterScript (ref sm._clientScriptBlocks, type, key, script, addScriptTags ? ScriptEntryType.ScriptContentNoTags : ScriptEntryType.ScriptContentWithTags);
  612. else
  613. page.ClientScript.RegisterClientScriptBlock (type, key, script, addScriptTags);
  614. }
  615. public static void RegisterClientScriptInclude (Control control, Type type, string key, string url) {
  616. RegisterClientScriptInclude (control.Page, type, key, url);
  617. }
  618. public static void RegisterClientScriptInclude (Page page, Type type, string key, string url) {
  619. ScriptManager sm = GetCurrent (page);
  620. if (sm.IsInAsyncPostBack)
  621. RegisterScript (ref sm._scriptIncludes, type, key, url, ScriptEntryType.ScriptPath);
  622. else
  623. page.ClientScript.RegisterClientScriptInclude (type, key, url);
  624. }
  625. public static void RegisterClientScriptResource (Control control, Type type, string resourceName) {
  626. RegisterClientScriptResource (control.Page, type, resourceName);
  627. }
  628. public static void RegisterClientScriptResource (Page page, Type type, string resourceName) {
  629. RegisterClientScriptInclude (page, type, "resource-" + resourceName, ScriptResourceHandler.GetResourceUrl (type.Assembly, resourceName, true));
  630. }
  631. void RegisterScriptReference (ScriptReference script, bool loadScriptsBeforeUI) {
  632. bool isDebugMode = IsDeploymentRetail ? false : (script.ScriptModeInternal == ScriptMode.Inherit ? IsDebuggingEnabled : (script.ScriptModeInternal == ScriptMode.Debug));
  633. string url;
  634. if (!String.IsNullOrEmpty (script.Path)) {
  635. url = GetScriptName (ResolveClientUrl (script.Path), isDebugMode, EnableScriptLocalization ? script.ResourceUICultures : null);
  636. }
  637. else if (!String.IsNullOrEmpty (script.Name)) {
  638. Assembly assembly;
  639. if (String.IsNullOrEmpty (script.Assembly))
  640. assembly = typeof (ScriptManager).Assembly;
  641. else
  642. assembly = Assembly.Load (script.Assembly);
  643. string name = GetScriptName (script.Name, isDebugMode, null);
  644. if (script.IgnoreScriptPath || String.IsNullOrEmpty (ScriptPath))
  645. url = ScriptResourceHandler.GetResourceUrl (assembly, name, script.NotifyScriptLoaded);
  646. else {
  647. AssemblyName an = assembly.GetName ();
  648. url = ResolveClientUrl (String.Concat (VirtualPathUtility.AppendTrailingSlash (ScriptPath), an.Name, '/', an.Version, '/', name));
  649. }
  650. }
  651. else {
  652. throw new InvalidOperationException ("Name and Path cannot both be empty.");
  653. }
  654. if (loadScriptsBeforeUI)
  655. RegisterClientScriptInclude (this, typeof (ScriptManager), url, url);
  656. else
  657. RegisterStartupScript (this, typeof (ScriptManager), url, String.Format ("<script src=\"{0}\" type=\"text/javascript\"></script>", url), false);
  658. }
  659. static string GetScriptName (string releaseName, bool isDebugMode, string [] supportedUICultures) {
  660. if (!isDebugMode && (supportedUICultures == null || supportedUICultures.Length == 0))
  661. return releaseName;
  662. if (releaseName.Length < 3 || !releaseName.EndsWith (".js", StringComparison.OrdinalIgnoreCase))
  663. throw new InvalidOperationException (String.Format ("'{0}' is not a valid script path. The path must end in '.js'.", releaseName));
  664. StringBuilder sb = new StringBuilder (releaseName);
  665. sb.Length -= 3;
  666. if (isDebugMode)
  667. sb.Append (".debug");
  668. string culture = Thread.CurrentThread.CurrentUICulture.Name;
  669. if (supportedUICultures != null && Array.IndexOf<string> (supportedUICultures, culture) >= 0)
  670. sb.AppendFormat (".{0}", culture);
  671. sb.Append (".js");
  672. return sb.ToString ();
  673. }
  674. void RegisterServiceReference (ServiceReference serviceReference) {
  675. if (serviceReference.InlineScript) {
  676. string url = ResolveUrl (serviceReference.Path);
  677. LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (WebServiceParser.GetCompiledType (url, Context), url);
  678. RegisterClientScriptBlock (this, typeof (ScriptManager), url, logicalTypeInfo.Proxy, true);
  679. }
  680. else {
  681. #if TARGET_J2EE
  682. string pathInfo = "/js.invoke";
  683. #else
  684. string pathInfo = "/js";
  685. #endif
  686. string url = String.Concat (ResolveClientUrl (serviceReference.Path), pathInfo);
  687. RegisterClientScriptInclude (this, typeof (ScriptManager), url, url);
  688. }
  689. }
  690. public void RegisterDataItem (Control control, string dataItem) {
  691. RegisterDataItem (control, dataItem, false);
  692. }
  693. public void RegisterDataItem (Control control, string dataItem, bool isJsonSerialized) {
  694. if (!IsInAsyncPostBack)
  695. throw new InvalidOperationException ("RegisterDataItem can only be called during an async postback.");
  696. if (control == null)
  697. throw new ArgumentNullException ("control");
  698. if (_dataItems == null)
  699. _dataItems = new Dictionary<Control, DataItemEntry> ();
  700. if (_dataItems.ContainsKey (control))
  701. throw new ArgumentException (String.Format ("'{0}' already has a data item registered.", control.ID), "control");
  702. _dataItems.Add (control, new DataItemEntry (dataItem, isJsonSerialized));
  703. }
  704. public void RegisterDispose (Control control, string disposeScript) {
  705. if (control == null)
  706. throw new ArgumentNullException ("control");
  707. if (disposeScript == null)
  708. throw new ArgumentNullException ("disposeScript");
  709. UpdatePanel updatePanel = GetUpdatePanel (control);
  710. if (updatePanel == null)
  711. return;
  712. if (_disposeScripts == null)
  713. _disposeScripts = new List<DisposeScriptEntry> ();
  714. _disposeScripts.Add (new DisposeScriptEntry (updatePanel, disposeScript));
  715. }
  716. static UpdatePanel GetUpdatePanel (Control control) {
  717. if (control == null)
  718. return null;
  719. UpdatePanel parent = control.Parent as UpdatePanel;
  720. if (parent != null)
  721. return parent;
  722. return GetUpdatePanel (control.Parent);
  723. }
  724. public static void RegisterExpandoAttribute (Control control, string controlId, string attributeName, string attributeValue, bool encode) {
  725. Page page = control.Page;
  726. ScriptManager sm = GetCurrent (page);
  727. if (sm.IsInAsyncPostBack)
  728. sm.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
  729. else
  730. page.ClientScript.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
  731. }
  732. private void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue, bool encode) {
  733. // seems MS do nothing.
  734. }
  735. public static void RegisterHiddenField (Control control, string hiddenFieldName, string hiddenFieldInitialValue) {
  736. RegisterHiddenField (control.Page, hiddenFieldName, hiddenFieldInitialValue);
  737. }
  738. public static void RegisterHiddenField (Page page, string hiddenFieldName, string hiddenFieldInitialValue) {
  739. ScriptManager sm = GetCurrent (page);
  740. if (sm.IsInAsyncPostBack)
  741. sm.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  742. else
  743. page.ClientScript.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  744. }
  745. void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue) {
  746. if (_hiddenFields == null)
  747. _hiddenFields = new Hashtable ();
  748. if (!_hiddenFields.ContainsKey (hiddenFieldName))
  749. _hiddenFields.Add (hiddenFieldName, hiddenFieldInitialValue);
  750. }
  751. public static void RegisterOnSubmitStatement (Control control, Type type, string key, string script) {
  752. RegisterOnSubmitStatement (control.Page, type, key, script);
  753. }
  754. public static void RegisterOnSubmitStatement (Page page, Type type, string key, string script) {
  755. ScriptManager sm = GetCurrent (page);
  756. if (sm.IsInAsyncPostBack)
  757. RegisterScript (ref sm._onSubmitStatements, type, key, script, ScriptEntryType.OnSubmit);
  758. else
  759. page.ClientScript.RegisterOnSubmitStatement (type, key, script);
  760. }
  761. public void RegisterPostBackControl (Control control) {
  762. if (control == null)
  763. return;
  764. if (_postBackControls == null)
  765. _postBackControls = new List<Control> ();
  766. if (_postBackControls.Contains (control))
  767. return;
  768. _postBackControls.Add (control);
  769. }
  770. internal void RegisterUpdatePanel (UpdatePanel updatePanel) {
  771. if (_updatePanels == null)
  772. _updatePanels = new List<UpdatePanel> ();
  773. if (_updatePanels.Contains (updatePanel))
  774. return;
  775. _updatePanels.Add (updatePanel);
  776. }
  777. public void RegisterScriptDescriptors (IExtenderControl extenderControl) {
  778. if (extenderControl == null)
  779. return;
  780. if (_registeredExtenderControls == null || !_registeredExtenderControls.ContainsKey (extenderControl))
  781. return;
  782. Control targetControl = _registeredExtenderControls [extenderControl];
  783. RegisterScriptDescriptors (extenderControl.GetScriptDescriptors (targetControl));
  784. }
  785. public void RegisterScriptDescriptors (IScriptControl scriptControl) {
  786. if (scriptControl == null)
  787. return;
  788. if (_registeredScriptControls == null || !_registeredScriptControls.Contains (scriptControl))
  789. return;
  790. RegisterScriptDescriptors (scriptControl.GetScriptDescriptors ());
  791. }
  792. void RegisterScriptDescriptors (IEnumerable<ScriptDescriptor> scriptDescriptors) {
  793. if (scriptDescriptors == null)
  794. return;
  795. if (IsInAsyncPostBack && !IsInPartialRendering)
  796. return;
  797. StringBuilder sb = new StringBuilder ();
  798. foreach (ScriptDescriptor scriptDescriptor in scriptDescriptors) {
  799. if (IsMultiForm) {
  800. scriptDescriptor.FormID = Page.Form.ClientID;
  801. sb.AppendLine ("Sys.Application.getInstance($get(\"" + Page.Form.ClientID + "\")).add_init(function() {");
  802. }
  803. else
  804. sb.AppendLine ("Sys.Application.add_init(function() {");
  805. sb.AppendLine (scriptDescriptor.GetScript ());
  806. sb.AppendLine ("});");
  807. }
  808. string script = sb.ToString ();
  809. RegisterStartupScript (this, typeof (ExtenderControl), script, script, true);
  810. }
  811. public static void RegisterStartupScript (Control control, Type type, string key, string script, bool addScriptTags) {
  812. RegisterStartupScript (control.Page, type, key, script, addScriptTags);
  813. }
  814. public static void RegisterStartupScript (Page page, Type type, string key, string script, bool addScriptTags) {
  815. ScriptManager sm = GetCurrent (page);
  816. if (sm.IsInAsyncPostBack)
  817. RegisterScript (ref sm._startupScriptBlocks, type, key, script, addScriptTags ? ScriptEntryType.ScriptContentNoTags : ScriptEntryType.ScriptContentWithTags);
  818. else
  819. page.ClientScript.RegisterStartupScript (type, key, script, addScriptTags);
  820. }
  821. public void RegisterScriptControl<TScriptControl> (TScriptControl scriptControl) where TScriptControl : Control, IScriptControl {
  822. if (scriptControl == null)
  823. throw new ArgumentNullException ("scriptControl");
  824. if (_registeredScriptControls == null)
  825. _registeredScriptControls = new List<IScriptControl> ();
  826. if (!_registeredScriptControls.Contains (scriptControl))
  827. _registeredScriptControls.Add (scriptControl);
  828. }
  829. public void RegisterExtenderControl<TExtenderControl> (TExtenderControl extenderControl, Control targetControl) where TExtenderControl : Control, IExtenderControl {
  830. if (extenderControl == null)
  831. throw new ArgumentNullException ("extenderControl");
  832. if (targetControl == null)
  833. throw new ArgumentNullException ("targetControl");
  834. if (_registeredExtenderControls == null)
  835. _registeredExtenderControls = new Dictionary<IExtenderControl, Control> ();
  836. if (!_registeredExtenderControls.ContainsKey (extenderControl))
  837. _registeredExtenderControls.Add (extenderControl, targetControl);
  838. }
  839. static void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, ScriptEntryType scriptEntryType) {
  840. ScriptEntry last = null;
  841. ScriptEntry entry = scriptList;
  842. while (entry != null) {
  843. if (entry.Type == type && entry.Key == key)
  844. return;
  845. last = entry;
  846. entry = entry.Next;
  847. }
  848. entry = new ScriptEntry (type, key, script, scriptEntryType);
  849. if (last != null)
  850. last.Next = entry;
  851. else
  852. scriptList = entry;
  853. }
  854. protected override void Render (HtmlTextWriter writer) {
  855. // MSDN: This method is used by control developers to extend the ScriptManager control.
  856. // Notes to Inheritors:
  857. // When overriding this method, call the base Render(HtmlTextWriter) method
  858. // so that PageRequestManager is rendered on the page.
  859. if (SupportsPartialRendering) {
  860. writer.WriteLine ("<script type=\"text/javascript\">");
  861. writer.WriteLine ("//<![CDATA[");
  862. writer.WriteLine ("Sys.WebForms.PageRequestManager._initialize('{0}', document.getElementById('{1}'));", UniqueID, Page.Form.ClientID);
  863. if (IsMultiForm)
  864. writer.WriteLine ("Sys.WebForms.PageRequestManager.getInstance($get(\"{0}\"))._updateControls([{1}], [{2}], [{3}], {4});", Page.Form.ClientID, FormatUpdatePanelIDs (_updatePanels, true), FormatListIDs (_asyncPostBackControls, true), FormatListIDs (_postBackControls, true), AsyncPostBackTimeout);
  865. else
  866. writer.WriteLine ("Sys.WebForms.PageRequestManager.getInstance()._updateControls([{0}], [{1}], [{2}], {3});", FormatUpdatePanelIDs (_updatePanels, true), FormatListIDs (_asyncPostBackControls, true), FormatListIDs (_postBackControls, true), AsyncPostBackTimeout);
  867. writer.WriteLine ("//]]");
  868. writer.WriteLine ("</script>");
  869. }
  870. base.Render (writer);
  871. }
  872. static string FormatUpdatePanelIDs (List<UpdatePanel> list, bool useSingleQuote) {
  873. if (list == null || list.Count == 0)
  874. return null;
  875. StringBuilder sb = new StringBuilder ();
  876. for (int i = 0; i < list.Count; i++) {
  877. sb.AppendFormat ("{0}{1}{2}{0},", useSingleQuote ? "'" : String.Empty, list [i].ChildrenAsTriggers ? "t" : "f", list [i].UniqueID);
  878. }
  879. if (sb.Length > 0)
  880. sb.Length--;
  881. return sb.ToString ();
  882. }
  883. static string FormatListIDs<T> (List<T> list, bool useSingleQuote) where T : Control {
  884. if (list == null || list.Count == 0)
  885. return null;
  886. StringBuilder sb = new StringBuilder ();
  887. for (int i = 0; i < list.Count; i++) {
  888. sb.AppendFormat ("{0}{1}{0},", useSingleQuote ? "'" : String.Empty, list [i].UniqueID);
  889. }
  890. if (sb.Length > 0)
  891. sb.Length--;
  892. return sb.ToString ();
  893. }
  894. public void SetFocus (Control control) {
  895. if (control == null)
  896. throw new ArgumentNullException ("control");
  897. if (IsInAsyncPostBack) {
  898. EnsureFocusClientScript ();
  899. _controlIDToFocus = control.ClientID;
  900. }
  901. else
  902. Page.SetFocus (control);
  903. }
  904. public void SetFocus (string clientID) {
  905. if (String.IsNullOrEmpty (clientID))
  906. throw new ArgumentNullException ("control");
  907. if (IsInAsyncPostBack) {
  908. EnsureFocusClientScript ();
  909. _controlIDToFocus = clientID;
  910. }
  911. else
  912. Page.SetFocus (clientID);
  913. }
  914. void EnsureFocusClientScript () {
  915. #if TARGET_DOTNET
  916. RegisterClientScriptResource (this, typeof (ClientScriptManager), "Focus.js");
  917. #endif
  918. }
  919. #region IPostBackDataHandler Members
  920. bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection) {
  921. return LoadPostData (postDataKey, postCollection);
  922. }
  923. void IPostBackDataHandler.RaisePostDataChangedEvent () {
  924. RaisePostDataChangedEvent ();
  925. }
  926. #endregion
  927. internal void WriteCallbackException (TextWriter output, Exception ex, bool writeMessage) {
  928. #if TARGET_DOTNET
  929. if (ex is HttpUnhandledException)
  930. ex = ex.InnerException;
  931. #endif
  932. HttpException httpEx = ex as HttpException;
  933. string message = AsyncPostBackErrorMessage;
  934. if (String.IsNullOrEmpty (message) && writeMessage)
  935. message = ex.Message;
  936. WriteCallbackOutput (output, error, httpEx == null ? "500" : httpEx.GetHttpCode ().ToString (), message);
  937. }
  938. static internal void WriteCallbackRedirect (TextWriter output, string redirectUrl) {
  939. WriteCallbackOutput (output, pageRedirect, null, redirectUrl);
  940. }
  941. internal void WriteCallbackPanel (TextWriter output, UpdatePanel panel, StringBuilder panelOutput) {
  942. if (_panelsToRefresh == null)
  943. _panelsToRefresh = new List<UpdatePanel> ();
  944. _panelsToRefresh.Add (panel);
  945. WriteCallbackOutput (output, updatePanel, panel.ClientID, panelOutput);
  946. }
  947. internal void RegisterChildUpdatePanel (UpdatePanel updatePanel) {
  948. if (_childUpdatePanels == null)
  949. _childUpdatePanels = new List<UpdatePanel> ();
  950. _childUpdatePanels.Add (updatePanel);
  951. }
  952. static void WriteCallbackOutput (TextWriter output, string type, string name, object value) {
  953. string str = value as string;
  954. StringBuilder sb = value as StringBuilder;
  955. int length = 0;
  956. if (str != null)
  957. length = str.Length;
  958. else if (sb != null)
  959. length = sb.Length;
  960. //output.Write ("{0}|{1}|{2}|{3}|", value == null ? 0 : value.Length, type, name, value);
  961. output.Write (length);
  962. output.Write ('|');
  963. output.Write (type);
  964. output.Write ('|');
  965. output.Write (name);
  966. output.Write ('|');
  967. for (int i = 0; i < length; i++)
  968. if (str != null)
  969. output.Write (str [i]);
  970. else
  971. output.Write (sb [i]);
  972. output.Write ('|');
  973. }
  974. void RenderPageCallback (HtmlTextWriter output, Control container) {
  975. Page page = (Page) container;
  976. page.Form.SetRenderMethodDelegate (RenderFormCallback);
  977. HtmlTextParser parser = new HtmlTextParser (output);
  978. page.Form.RenderControl (parser);
  979. WriteCallbackOutput (output, asyncPostBackControlIDs, null, FormatListIDs (_asyncPostBackControls, false));
  980. WriteCallbackOutput (output, postBackControlIDs, null, FormatListIDs (_postBackControls, false));
  981. WriteCallbackOutput (output, updatePanelIDs, null, FormatUpdatePanelIDs (_updatePanels, false));
  982. WriteCallbackOutput (output, childUpdatePanelIDs, null, FormatListIDs (_childUpdatePanels, false));
  983. WriteCallbackOutput (output, panelsToRefreshIDs, null, FormatListIDs (_panelsToRefresh, false));
  984. WriteCallbackOutput (output, asyncPostBackTimeout, null, AsyncPostBackTimeout.ToString ());
  985. if (!IsMultiForm)
  986. WriteCallbackOutput (output, pageTitle, null, Page.Title);
  987. if (_dataItems != null)
  988. foreach (Control control in _dataItems.Keys) {
  989. DataItemEntry entry = _dataItems [control];
  990. WriteCallbackOutput (output, entry.IsJsonSerialized ? dataItemJson : dataItem, control.ClientID, entry.DataItem);
  991. }
  992. WriteArrayDeclarations (output);
  993. WriteScriptBlocks (output, _clientScriptBlocks);
  994. WriteScriptBlocks (output, _scriptIncludes);
  995. WriteScriptBlocks (output, _startupScriptBlocks);
  996. WriteScriptBlocks (output, _onSubmitStatements);
  997. WriteHiddenFields (output);
  998. if (!String.IsNullOrEmpty (_controlIDToFocus))
  999. WriteCallbackOutput (output, focus, null, _controlIDToFocus);
  1000. if (_disposeScripts != null)
  1001. for (int i = 0; i < _disposeScripts.Count; i++) {
  1002. DisposeScriptEntry entry = _disposeScripts [i];
  1003. if ((_panelsToRefresh != null && _panelsToRefresh.IndexOf (entry.UpdatePanel) >= 0) || (_childUpdatePanels != null && _childUpdatePanels.IndexOf (entry.UpdatePanel) >= 0))
  1004. WriteCallbackOutput (output, scriptDispose, entry.UpdatePanel.ClientID, entry.Script);
  1005. }
  1006. }
  1007. void WriteArrayDeclarations (HtmlTextWriter writer) {
  1008. if (_arrayDeclarations != null) {
  1009. for (int i = 0; i < _arrayDeclarations.Count; i++) {
  1010. ArrayDeclaration array = _arrayDeclarations [i];
  1011. WriteCallbackOutput (writer, arrayDeclaration, array.ArrayName, array.ArrayValue);
  1012. }
  1013. }
  1014. }
  1015. void WriteScriptBlocks (HtmlTextWriter output, ScriptEntry scriptList) {
  1016. while (scriptList != null) {
  1017. switch (scriptList.ScriptEntryType) {
  1018. case ScriptEntryType.ScriptContentNoTags:
  1019. WriteCallbackOutput (output, scriptBlock, scriptContentNoTags, scriptList.Script);
  1020. break;
  1021. case ScriptEntryType.ScriptContentWithTags:
  1022. string script = SerializeScriptBlock (scriptList);
  1023. WriteCallbackOutput (output, scriptBlock, scriptContentWithTags, script);
  1024. break;
  1025. case ScriptEntryType.ScriptPath:
  1026. WriteCallbackOutput (output, scriptBlock, scriptPath, scriptList.Script);
  1027. break;
  1028. case ScriptEntryType.OnSubmit:
  1029. WriteCallbackOutput (output, onSubmit, null, scriptList.Script);
  1030. break;
  1031. }
  1032. scriptList = scriptList.Next;
  1033. }
  1034. }
  1035. void WriteHiddenFields (HtmlTextWriter output) {
  1036. if (_hiddenFields == null)
  1037. return;
  1038. foreach (string key in _hiddenFields.Keys) {
  1039. string value = _hiddenFields [key] as string;
  1040. WriteCallbackOutput (output, hiddenField, key, value);
  1041. }
  1042. }
  1043. static string SerializeScriptBlock (ScriptEntry scriptList) {
  1044. try {
  1045. XmlTextReader reader = new XmlTextReader (new StringReader (scriptList.Script));
  1046. while (reader.Read ()) {
  1047. switch (reader.NodeType) {
  1048. case XmlNodeType.Element:
  1049. if (String.Compare ("script", reader.Name, StringComparison.OrdinalIgnoreCase) == 0) {
  1050. Dictionary<string, string> dic = new Dictionary<string, string> ();
  1051. while (reader.MoveToNextAttribute ()) {
  1052. dic.Add (reader.Name, reader.Value);
  1053. }
  1054. reader.MoveToContent ();
  1055. dic.Add ("text", reader.ReadInnerXml ());
  1056. return JavaScriptSerializer.DefaultSerializer.Serialize (dic);
  1057. }
  1058. break;
  1059. default:
  1060. continue;
  1061. }
  1062. }
  1063. }
  1064. catch {
  1065. }
  1066. throw new InvalidOperationException (String.Format ("The script tag registered for type '{0}' and key '{1}' has invalid characters outside of the script tags: {2}. Only properly formatted script tags can be registered.", scriptList.Type, scriptList.Key, scriptList.Script));
  1067. }
  1068. void RenderFormCallback (HtmlTextWriter output, Control container) {
  1069. output = ((HtmlTextParser) output).ResponseOutput;
  1070. HtmlForm form = (HtmlForm) container;
  1071. HtmlTextWriter writer = new HtmlDropWriter (output);
  1072. if (form.HasControls ()) {
  1073. for (int i = 0; i < form.Controls.Count; i++) {
  1074. form.Controls [i].RenderControl (writer);
  1075. }
  1076. }
  1077. }
  1078. internal class AlternativeHtmlTextWriter : HtmlTextWriter
  1079. {
  1080. readonly HtmlTextWriter _responseOutput;
  1081. public HtmlTextWriter ResponseOutput {
  1082. get { return _responseOutput; }
  1083. }
  1084. public AlternativeHtmlTextWriter (TextWriter writer, HtmlTextWriter responseOutput)
  1085. : base (writer) {
  1086. _responseOutput = responseOutput;
  1087. }
  1088. }
  1089. sealed class HtmlTextParser : AlternativeHtmlTextWriter
  1090. {
  1091. bool _done;
  1092. public HtmlTextParser (HtmlTextWriter responseOutput)
  1093. : base (new TextParser (responseOutput), responseOutput) {
  1094. }
  1095. public override void WriteAttribute (string name, string value) {
  1096. if (!_done && String.Compare ("action", name, StringComparison.OrdinalIgnoreCase) == 0) {
  1097. _done = true;
  1098. ScriptManager.WriteCallbackOutput (ResponseOutput, formAction, null, value);
  1099. return;
  1100. }
  1101. base.WriteAttribute (name, value);
  1102. }
  1103. }
  1104. sealed class TextParser : TextWriter
  1105. {
  1106. int _state;
  1107. char _charState = (char) 255;
  1108. const char nullCharState = (char) 255;
  1109. StringBuilder _sb = new StringBuilder ();
  1110. Dictionary<string, string> _currentField;
  1111. string _currentAttribute;
  1112. readonly HtmlTextWriter _responseOutput;
  1113. public override Encoding Encoding {
  1114. get { return Encoding.UTF8; }
  1115. }
  1116. public TextParser (HtmlTextWriter responseOutput) {
  1117. _responseOutput = responseOutput;
  1118. }
  1119. public override void Write (char value) {
  1120. switch (_state) {
  1121. case 0:
  1122. ParseBeginTag (value);
  1123. break;
  1124. case 1:
  1125. ParseAttributeName (value);
  1126. break;
  1127. case 2:
  1128. ParseAttributeValue (value);
  1129. break;
  1130. }
  1131. }
  1132. private void ParseAttributeValue (char value) {
  1133. switch (value) {
  1134. case '>':
  1135. ResetState ();
  1136. break;
  1137. case '"':
  1138. _currentField.Add (_currentAttribute, _sb.ToString ());
  1139. _state = 1;
  1140. _sb.Length = 0;
  1141. ProbeWriteOutput ();
  1142. break;
  1143. default:
  1144. _sb.Append (value);
  1145. break;
  1146. }
  1147. }
  1148. private void ParseAttributeName (char value) {
  1149. switch (value) {
  1150. case '>':
  1151. ResetState ();
  1152. break;
  1153. case ' ':
  1154. case '=':
  1155. break;
  1156. case '"':
  1157. _currentAttribute = _sb.ToString ();
  1158. _state = 2;
  1159. _sb.Length = 0;
  1160. break;
  1161. default:
  1162. _sb.Append (value);
  1163. break;
  1164. }
  1165. }
  1166. void ParseBeginTag (char value) {
  1167. switch (_charState) {
  1168. case nullCharState:
  1169. if (value == '<')
  1170. _charState = value;
  1171. break;
  1172. case '<':
  1173. if (value == 'i')
  1174. _charState = value;
  1175. else
  1176. ResetState ();
  1177. break;
  1178. case 'i':
  1179. if (value == 'n')
  1180. _charState = value;
  1181. else
  1182. ResetState ();
  1183. break;
  1184. case 'n':
  1185. if (value == 'p')
  1186. _charState = value;
  1187. else
  1188. ResetState ();
  1189. break;
  1190. case 'p':
  1191. if (value == 'u')
  1192. _charState = value;
  1193. else
  1194. ResetState ();
  1195. break;
  1196. case 'u':
  1197. if (value == 't')
  1198. _charState = value;
  1199. else
  1200. ResetState ();
  1201. break;
  1202. case 't':
  1203. if (value == ' ') {
  1204. _state = 1;
  1205. _currentField = new Dictionary<string, string> ();
  1206. }
  1207. else
  1208. ResetState ();
  1209. break;
  1210. }
  1211. }
  1212. private void ResetState () {
  1213. _charState = nullCharState;
  1214. _state = 0;
  1215. _sb.Length = 0;
  1216. }
  1217. private void ProbeWriteOutput () {
  1218. if (!_currentField.ContainsKey ("name"))
  1219. return;
  1220. if (!_currentField.ContainsKey ("value"))
  1221. return;
  1222. string value = _currentField ["value"];
  1223. if (String.IsNullOrEmpty (value))
  1224. return;
  1225. ScriptManager.WriteCallbackOutput (_responseOutput, hiddenField, _currentField ["name"], HttpUtility.HtmlDecode (value));
  1226. }
  1227. }
  1228. sealed class HtmlDropWriter : AlternativeHtmlTextWriter
  1229. {
  1230. public HtmlDropWriter (HtmlTextWriter responseOutput)
  1231. : base (new DropWriter (), responseOutput) {
  1232. }
  1233. }
  1234. sealed class DropWriter : TextWriter
  1235. {
  1236. public override Encoding Encoding {
  1237. get { return Encoding.UTF8; }
  1238. }
  1239. }
  1240. sealed class ScriptEntry
  1241. {
  1242. readonly public Type Type;
  1243. readonly public string Key;
  1244. readonly public string Script;
  1245. readonly public ScriptEntryType ScriptEntryType;
  1246. public ScriptEntry Next;
  1247. public ScriptEntry (Type type, string key, string script, ScriptEntryType scriptEntryType) {
  1248. Key = key;
  1249. Type = type;
  1250. Script = script;
  1251. ScriptEntryType = scriptEntryType;
  1252. }
  1253. }
  1254. enum ScriptEntryType
  1255. {
  1256. ScriptContentNoTags,
  1257. ScriptContentWithTags,
  1258. ScriptPath,
  1259. OnSubmit
  1260. }
  1261. sealed class ArrayDeclaration
  1262. {
  1263. readonly public string ArrayName;
  1264. readonly public string ArrayValue;
  1265. public ArrayDeclaration (string arrayName, string arrayValue) {
  1266. ArrayName = arrayName;
  1267. ArrayValue = arrayValue;
  1268. }
  1269. }
  1270. sealed class CultureInfoSerializer : JavaScriptSerializer.LazyDictionary
  1271. {
  1272. readonly CultureInfo _ci;
  1273. public CultureInfoSerializer (CultureInfo ci) {
  1274. if (ci == null)
  1275. throw new ArgumentNullException ("ci");
  1276. _ci = ci;
  1277. }
  1278. protected override IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
  1279. yield return new KeyValuePair<string, object> ("name", _ci.Name);
  1280. yield return new KeyValuePair<string, object> ("numberFormat", _ci.NumberFormat);
  1281. yield return new KeyValuePair<string, object> ("dateTimeFormat", _ci.DateTimeFormat);
  1282. }
  1283. }
  1284. sealed class ScriptReferenceEntry
  1285. {
  1286. readonly Control _control;
  1287. readonly ScriptReference _scriptReference;
  1288. readonly bool _loadBeforeUI;
  1289. public Control Control { get { return _control; } }
  1290. public ScriptReference ScriptReference { get { return _scriptReference; } }
  1291. public bool LoadScriptsBeforeUI { get { return _loadBeforeUI; } }
  1292. public ScriptReferenceEntry (Control control, ScriptReference scriptReference, bool loadBeforeUI) {
  1293. _control = control;
  1294. _scriptReference = scriptReference;
  1295. _loadBeforeUI = loadBeforeUI;
  1296. }
  1297. }
  1298. sealed class DataItemEntry
  1299. {
  1300. readonly string _dataItem;
  1301. readonly bool _isJsonSerialized;
  1302. public string DataItem { get { return _dataItem; } }
  1303. public bool IsJsonSerialized { get { return _isJsonSerialized; } }
  1304. public DataItemEntry (string dataItem, bool isJsonSerialized) {
  1305. _dataItem = dataItem;
  1306. _isJsonSerialized = isJsonSerialized;
  1307. }
  1308. }
  1309. sealed class DisposeScriptEntry
  1310. {
  1311. readonly UpdatePanel _updatePanel;
  1312. readonly string _script;
  1313. public UpdatePanel UpdatePanel { get { return _updatePanel; } }
  1314. public string Script { get { return _script; } }
  1315. public DisposeScriptEntry (UpdatePanel updatePanel, string script) {
  1316. _updatePanel = updatePanel;
  1317. _script = script;
  1318. }
  1319. }
  1320. }
  1321. }