ScriptManager.cs 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444
  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. #if !TARGET_J2EE
  219. CompilationSection compilation = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  220. if (!compilation.Debug && (ScriptMode == ScriptMode.Auto || ScriptMode == ScriptMode.Inherit))
  221. return false;
  222. #endif
  223. if (ScriptMode == ScriptMode.Release)
  224. return false;
  225. return true;
  226. }
  227. }
  228. bool IsDeploymentRetail {
  229. get {
  230. #if TARGET_J2EE
  231. return false;
  232. #else
  233. DeploymentSection deployment = (DeploymentSection) WebConfigurationManager.GetSection ("system.web/deployment");
  234. return deployment.Retail;
  235. #endif
  236. }
  237. }
  238. [Browsable (false)]
  239. public bool IsInAsyncPostBack {
  240. get {
  241. return _isInAsyncPostBack;
  242. }
  243. }
  244. internal bool IsInPartialRendering {
  245. get {
  246. return _isInPartialRendering;
  247. }
  248. set {
  249. _isInPartialRendering = value;
  250. }
  251. }
  252. [Category ("Behavior")]
  253. [DefaultValue (true)]
  254. public bool LoadScriptsBeforeUI {
  255. get {
  256. return _loadScriptsBeforeUI;
  257. }
  258. set {
  259. _loadScriptsBeforeUI = value;
  260. }
  261. }
  262. [PersistenceMode (PersistenceMode.InnerProperty)]
  263. [DefaultValue ("")]
  264. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  265. [Category ("Behavior")]
  266. [MergableProperty (false)]
  267. public ProfileServiceManager ProfileService {
  268. get {
  269. if (_profileService == null)
  270. _profileService = new ProfileServiceManager ();
  271. return _profileService;
  272. }
  273. }
  274. [Category ("Behavior")]
  275. #if TARGET_J2EE
  276. [MonoLimitation ("The 'Auto' value is the same as 'Debug'.")]
  277. #endif
  278. public ScriptMode ScriptMode {
  279. get {
  280. return _scriptMode;
  281. }
  282. set {
  283. if (value == ScriptMode.Inherit)
  284. value = ScriptMode.Auto;
  285. _scriptMode = value;
  286. }
  287. }
  288. [DefaultValue ("")]
  289. [Category ("Behavior")]
  290. public string ScriptPath {
  291. get {
  292. if (_scriptPath == null)
  293. return String.Empty;
  294. return _scriptPath;
  295. }
  296. set {
  297. _scriptPath = value;
  298. }
  299. }
  300. [PersistenceMode (PersistenceMode.InnerProperty)]
  301. [DefaultValue ("")]
  302. [Category ("Behavior")]
  303. [MergableProperty (false)]
  304. public ScriptReferenceCollection Scripts {
  305. get {
  306. if (_scripts == null)
  307. _scripts = new ScriptReferenceCollection ();
  308. return _scripts;
  309. }
  310. }
  311. [PersistenceMode (PersistenceMode.InnerProperty)]
  312. [DefaultValue ("")]
  313. [MergableProperty (false)]
  314. [Category ("Behavior")]
  315. public ServiceReferenceCollection Services {
  316. get {
  317. if (_services == null)
  318. _services = new ServiceReferenceCollection ();
  319. return _services;
  320. }
  321. }
  322. [DefaultValue (true)]
  323. [Browsable (false)]
  324. public bool SupportsPartialRendering {
  325. get {
  326. if (!_supportsPartialRendering.HasValue)
  327. _supportsPartialRendering = CheckSupportsPartialRendering ();
  328. return _supportsPartialRendering.Value;
  329. }
  330. set {
  331. if (_init)
  332. throw new InvalidOperationException ();
  333. if (!EnablePartialRendering && value)
  334. throw new InvalidOperationException ("The SupportsPartialRendering property cannot be set when EnablePartialRendering is false.");
  335. _supportsPartialRendering = value;
  336. }
  337. }
  338. bool CheckSupportsPartialRendering () {
  339. if (!EnablePartialRendering)
  340. return false;
  341. // TODO: consider browser capabilities
  342. return true;
  343. }
  344. [EditorBrowsable (EditorBrowsableState.Never)]
  345. [Browsable (false)]
  346. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  347. public override bool Visible {
  348. get {
  349. return true;
  350. }
  351. set {
  352. throw new NotImplementedException ();
  353. }
  354. }
  355. [Category ("Action")]
  356. public event EventHandler<AsyncPostBackErrorEventArgs> AsyncPostBackError;
  357. [Category ("Action")]
  358. public event EventHandler<ScriptReferenceEventArgs> ResolveScriptReference;
  359. public static ScriptManager GetCurrent (Page page) {
  360. if (page == null)
  361. throw new ArgumentNullException("page");
  362. return (ScriptManager) page.Items [ScriptManagerKey];
  363. }
  364. static void SetCurrent (Page page, ScriptManager instance) {
  365. page.Items [ScriptManagerKey] = instance;
  366. }
  367. protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection) {
  368. _isInAsyncPostBack = true;
  369. string arg = postCollection [postDataKey];
  370. if (!String.IsNullOrEmpty (arg)) {
  371. string [] args = arg.Split ('|');
  372. _panelToRefreshID = args [0];
  373. _asyncPostBackSourceElementID = args [1];
  374. return true;
  375. }
  376. return false;
  377. }
  378. protected internal virtual void OnAsyncPostBackError (AsyncPostBackErrorEventArgs e) {
  379. if (AsyncPostBackError != null)
  380. AsyncPostBackError (this, e);
  381. }
  382. protected override void OnInit (EventArgs e) {
  383. base.OnInit (e);
  384. if (GetCurrent (Page) != null)
  385. throw new InvalidOperationException ("Only one instance of a ScriptManager can be added to the page.");
  386. SetCurrent (Page, this);
  387. Page.Error += new EventHandler (OnPageError);
  388. _init = true;
  389. }
  390. void OnPageError (object sender, EventArgs e) {
  391. if (IsInAsyncPostBack)
  392. OnAsyncPostBackError (new AsyncPostBackErrorEventArgs (Context.Error));
  393. }
  394. protected override void OnPreRender (EventArgs e) {
  395. base.OnPreRender (e);
  396. Page.PreRenderComplete += new EventHandler (OnPreRenderComplete);
  397. if (IsInAsyncPostBack) {
  398. Page.SetRenderMethodDelegate (RenderPageCallback);
  399. }
  400. else {
  401. if (EnableScriptGlobalization) {
  402. CultureInfo culture = Thread.CurrentThread.CurrentCulture;
  403. string script = String.Format ("var __cultureInfo = '{0}';", JavaScriptSerializer.DefaultSerializer.Serialize (new CultureInfoSerializer (culture)));
  404. RegisterClientScriptBlock (this, typeof (ScriptManager), "ScriptGlobalization", script, true);
  405. }
  406. // Register dispose script
  407. if (_disposeScripts != null && _disposeScripts.Count > 0) {
  408. StringBuilder sb = new StringBuilder ();
  409. sb.AppendLine ();
  410. for (int i = 0; i < _disposeScripts.Count; i++) {
  411. DisposeScriptEntry entry = _disposeScripts [i];
  412. sb.Append ("Sys.WebForms.PageRequestManager.getInstance()._registerDisposeScript(\"");
  413. sb.Append (entry.UpdatePanel.ClientID);
  414. sb.Append ("\", ");
  415. sb.Append (JavaScriptSerializer.DefaultSerializer.Serialize (entry.Script)); //JavaScriptSerializer.Serialize used escape script literal
  416. sb.AppendLine (");");
  417. }
  418. RegisterStartupScript (this, typeof (ExtenderControl), "disposeScripts;", sb.ToString (), true);
  419. }
  420. #if TARGET_DOTNET
  421. // to cause webform client script being included
  422. Page.ClientScript.GetPostBackEventReference (new PostBackOptions (this, null, null, false, false, false, true, true, null));
  423. #else
  424. Page.ClientScript.GetPostBackEventReference (this, null);
  425. #endif
  426. }
  427. }
  428. void OnPreRenderComplete (object sender, EventArgs e) {
  429. // Resolve Scripts
  430. ScriptReference ajaxScript = new ScriptReference ("MicrosoftAjax.js", String.Empty);
  431. ajaxScript.NotifyScriptLoaded = false;
  432. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxScript));
  433. ScriptReference ajaxWebFormsScript = new ScriptReference ("MicrosoftAjaxWebForms.js", String.Empty);
  434. ajaxWebFormsScript.NotifyScriptLoaded = false;
  435. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxWebFormsScript));
  436. foreach (ScriptReferenceEntry script in GetScriptReferences ()) {
  437. OnResolveScriptReference (new ScriptReferenceEventArgs (script.ScriptReference));
  438. if (!IsInAsyncPostBack || (script.Control != this && HasBeenRendered (script.Control))) {
  439. if (_scriptToRegister == null)
  440. _scriptToRegister = new List<ScriptReferenceEntry> ();
  441. _scriptToRegister.Add (script);
  442. }
  443. }
  444. // Register Ajax framework script.
  445. RegisterScriptReference (ajaxScript, true);
  446. if (!IsInAsyncPostBack) {
  447. StringBuilder sb = new StringBuilder ();
  448. sb.AppendLine ("if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');");
  449. ScriptingProfileServiceSection profileService = (ScriptingProfileServiceSection) WebConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/profileService");
  450. if (profileService.Enabled)
  451. sb.AppendLine ("Sys.Services._ProfileService.DefaultWebServicePath = '" + ResolveClientUrl ("~/Profile_JSON_AppService.axd") + "';");
  452. if (_profileService != null && !String.IsNullOrEmpty (_profileService.Path))
  453. sb.AppendLine ("Sys.Services.ProfileService.set_path('" + ResolveUrl (_profileService.Path) + "');");
  454. ScriptingAuthenticationServiceSection authenticationService = (ScriptingAuthenticationServiceSection) WebConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/authenticationService");
  455. if (authenticationService.Enabled)
  456. sb.AppendLine ("Sys.Services._AuthenticationService.DefaultWebServicePath = '" + ResolveClientUrl ("~/Authentication_JSON_AppService.axd") + "';");
  457. if (_authenticationService != null && !String.IsNullOrEmpty (_authenticationService.Path))
  458. sb.AppendLine ("Sys.Services.AuthenticationService.set_path('" + ResolveUrl (_authenticationService.Path) + "');");
  459. RegisterClientScriptBlock (this, typeof (ScriptManager), "Framework", sb.ToString (), true);
  460. }
  461. RegisterScriptReference (ajaxWebFormsScript, true);
  462. // Register Scripts
  463. if (_scriptToRegister != null)
  464. for (int i = 0; i < _scriptToRegister.Count; i++)
  465. RegisterScriptReference (_scriptToRegister [i].ScriptReference, _scriptToRegister [i].LoadScriptsBeforeUI);
  466. if (!IsInAsyncPostBack) {
  467. // Register services
  468. if (_services != null && _services.Count > 0) {
  469. for (int i = 0; i < _services.Count; i++) {
  470. RegisterServiceReference (_services [i]);
  471. }
  472. }
  473. if (EnablePageMethods) {
  474. LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (Page.GetType (), Page.Request.FilePath);
  475. RegisterClientScriptBlock (this, typeof (ScriptManager), "PageMethods", logicalTypeInfo.Proxy, true);
  476. }
  477. // Register startup script
  478. RegisterStartupScript (this, typeof (ExtenderControl), "Sys.Application.initialize();", "Sys.Application.initialize();\n", true);
  479. }
  480. }
  481. static bool HasBeenRendered (Control control) {
  482. if (control == null)
  483. return false;
  484. UpdatePanel parent = control.Parent as UpdatePanel;
  485. if (parent != null && parent.RequiresUpdate)
  486. return true;
  487. return HasBeenRendered (control.Parent);
  488. }
  489. IEnumerable<ScriptReferenceEntry> GetScriptReferences () {
  490. if (_scripts != null && _scripts.Count > 0) {
  491. for (int i = 0; i < _scripts.Count; i++) {
  492. yield return new ScriptReferenceEntry (this, _scripts [i], LoadScriptsBeforeUI);
  493. }
  494. }
  495. if (_registeredScriptControls != null && _registeredScriptControls.Count > 0) {
  496. for (int i = 0; i < _registeredScriptControls.Count; i++) {
  497. IEnumerable<ScriptReference> scripts = _registeredScriptControls [i].GetScriptReferences ();
  498. if (scripts != null)
  499. foreach (ScriptReference s in scripts)
  500. yield return new ScriptReferenceEntry ((Control) _registeredScriptControls [i], s, LoadScriptsBeforeUI);
  501. }
  502. }
  503. if (_registeredExtenderControls != null && _registeredExtenderControls.Count > 0) {
  504. foreach (IExtenderControl ex in _registeredExtenderControls.Keys) {
  505. IEnumerable<ScriptReference> scripts = ex.GetScriptReferences ();
  506. if (scripts != null)
  507. foreach (ScriptReference s in scripts)
  508. yield return new ScriptReferenceEntry ((Control) ex, s, LoadScriptsBeforeUI);
  509. }
  510. }
  511. }
  512. protected virtual void OnResolveScriptReference (ScriptReferenceEventArgs e) {
  513. if (ResolveScriptReference != null)
  514. ResolveScriptReference (this, e);
  515. }
  516. protected virtual void RaisePostDataChangedEvent () {
  517. UpdatePanel up = Page.FindControl (_panelToRefreshID) as UpdatePanel;
  518. if (up != null && up.ChildrenAsTriggers)
  519. up.Update ();
  520. }
  521. public static void RegisterArrayDeclaration (Control control, string arrayName, string arrayValue) {
  522. RegisterArrayDeclaration (control.Page, arrayName, arrayValue);
  523. }
  524. public static void RegisterArrayDeclaration (Page page, string arrayName, string arrayValue) {
  525. ScriptManager sm = GetCurrent (page);
  526. if (sm.IsInAsyncPostBack)
  527. sm.RegisterArrayDeclaration (arrayName, arrayValue);
  528. else
  529. page.ClientScript.RegisterArrayDeclaration (arrayName, arrayValue);
  530. }
  531. void RegisterArrayDeclaration (string arrayName, string arrayValue) {
  532. if (_arrayDeclarations == null)
  533. _arrayDeclarations = new List<ArrayDeclaration> ();
  534. _arrayDeclarations.Add (new ArrayDeclaration (arrayName, arrayValue));
  535. }
  536. public void RegisterAsyncPostBackControl (Control control) {
  537. if (control == null)
  538. return;
  539. if (_asyncPostBackControls == null)
  540. _asyncPostBackControls = new List<Control> ();
  541. if (_asyncPostBackControls.Contains (control))
  542. return;
  543. _asyncPostBackControls.Add (control);
  544. }
  545. public static void RegisterClientScriptBlock (Control control, Type type, string key, string script, bool addScriptTags) {
  546. RegisterClientScriptBlock (control.Page, type, key, script, addScriptTags);
  547. }
  548. public static void RegisterClientScriptBlock (Page page, Type type, string key, string script, bool addScriptTags) {
  549. ScriptManager sm = GetCurrent (page);
  550. if (sm.IsInAsyncPostBack)
  551. RegisterScript (ref sm._clientScriptBlocks, type, key, script, addScriptTags ? ScriptEntryType.ScriptContentNoTags : ScriptEntryType.ScriptContentWithTags);
  552. else
  553. page.ClientScript.RegisterClientScriptBlock (type, key, script, addScriptTags);
  554. }
  555. public static void RegisterClientScriptInclude (Control control, Type type, string key, string url) {
  556. RegisterClientScriptInclude (control.Page, type, key, url);
  557. }
  558. public static void RegisterClientScriptInclude (Page page, Type type, string key, string url) {
  559. ScriptManager sm = GetCurrent (page);
  560. if (sm.IsInAsyncPostBack)
  561. RegisterScript (ref sm._scriptIncludes, type, key, url, ScriptEntryType.ScriptPath);
  562. else
  563. page.ClientScript.RegisterClientScriptInclude (type, key, url);
  564. }
  565. public static void RegisterClientScriptResource (Control control, Type type, string resourceName) {
  566. RegisterClientScriptResource (control.Page, type, resourceName);
  567. }
  568. public static void RegisterClientScriptResource (Page page, Type type, string resourceName) {
  569. RegisterClientScriptInclude (page, type, "resource-" + resourceName, ScriptResourceHandler.GetResourceUrl (type.Assembly, resourceName, true));
  570. }
  571. void RegisterScriptReference (ScriptReference script, bool loadScriptsBeforeUI) {
  572. bool isDebugMode = IsDeploymentRetail ? false : (script.ScriptModeInternal == ScriptMode.Inherit ? IsDebuggingEnabled : (script.ScriptModeInternal == ScriptMode.Debug));
  573. string url;
  574. if (!String.IsNullOrEmpty (script.Path)) {
  575. url = GetScriptName (ResolveClientUrl (script.Path), isDebugMode, EnableScriptLocalization ? script.ResourceUICultures : null);
  576. }
  577. else if (!String.IsNullOrEmpty (script.Name)) {
  578. Assembly assembly;
  579. if (String.IsNullOrEmpty (script.Assembly))
  580. assembly = typeof (ScriptManager).Assembly;
  581. else
  582. assembly = Assembly.Load (script.Assembly);
  583. string name = GetScriptName (script.Name, isDebugMode, null);
  584. if (script.IgnoreScriptPath || String.IsNullOrEmpty (ScriptPath))
  585. url = ScriptResourceHandler.GetResourceUrl (assembly, name, script.NotifyScriptLoaded);
  586. else {
  587. AssemblyName an = assembly.GetName ();
  588. url = ResolveClientUrl (String.Concat (VirtualPathUtility.AppendTrailingSlash (ScriptPath), an.Name, '/', an.Version, '/', name));
  589. }
  590. }
  591. else {
  592. throw new InvalidOperationException ("Name and Path cannot both be empty.");
  593. }
  594. if (loadScriptsBeforeUI)
  595. RegisterClientScriptInclude (this, typeof (ScriptManager), url, url);
  596. else
  597. RegisterStartupScript (this, typeof (ScriptManager), url, String.Format ("<script src=\"{0}\" type=\"text/javascript\"></script>", url), false);
  598. }
  599. static string GetScriptName (string releaseName, bool isDebugMode, string [] supportedUICultures) {
  600. if (!isDebugMode && (supportedUICultures == null || supportedUICultures.Length == 0))
  601. return releaseName;
  602. if (releaseName.Length < 3 || !releaseName.EndsWith (".js", StringComparison.OrdinalIgnoreCase))
  603. throw new InvalidOperationException (String.Format ("'{0}' is not a valid script path. The path must end in '.js'.", releaseName));
  604. StringBuilder sb = new StringBuilder (releaseName);
  605. sb.Length -= 3;
  606. if (isDebugMode)
  607. sb.Append (".debug");
  608. string culture = Thread.CurrentThread.CurrentUICulture.Name;
  609. if (supportedUICultures != null && Array.IndexOf<string> (supportedUICultures, culture) >= 0)
  610. sb.AppendFormat (".{0}", culture);
  611. sb.Append (".js");
  612. return sb.ToString ();
  613. }
  614. void RegisterServiceReference (ServiceReference serviceReference) {
  615. if (serviceReference.InlineScript) {
  616. string url = ResolveUrl (serviceReference.Path);
  617. LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (WebServiceParser.GetCompiledType (url, Context), url);
  618. RegisterClientScriptBlock (this, typeof (ScriptManager), url, logicalTypeInfo.Proxy, true);
  619. }
  620. else {
  621. #if TARGET_J2EE
  622. string pathInfo = "/js.invoke";
  623. #else
  624. string pathInfo = "/js";
  625. #endif
  626. string url = String.Concat (ResolveClientUrl (serviceReference.Path), pathInfo);
  627. RegisterClientScriptInclude (this, typeof (ScriptManager), url, url);
  628. }
  629. }
  630. public void RegisterDataItem (Control control, string dataItem) {
  631. RegisterDataItem (control, dataItem, false);
  632. }
  633. public void RegisterDataItem (Control control, string dataItem, bool isJsonSerialized) {
  634. if (!IsInAsyncPostBack)
  635. throw new InvalidOperationException ("RegisterDataItem can only be called during an async postback.");
  636. if (control == null)
  637. throw new ArgumentNullException ("control");
  638. if (_dataItems == null)
  639. _dataItems = new Dictionary<Control, DataItemEntry> ();
  640. if (_dataItems.ContainsKey (control))
  641. throw new ArgumentException (String.Format ("'{0}' already has a data item registered.", control.ID), "control");
  642. _dataItems.Add (control, new DataItemEntry (dataItem, isJsonSerialized));
  643. }
  644. public void RegisterDispose (Control control, string disposeScript) {
  645. if (control == null)
  646. throw new ArgumentNullException ("control");
  647. if (disposeScript == null)
  648. throw new ArgumentNullException ("disposeScript");
  649. UpdatePanel updatePanel = GetUpdatePanel (control);
  650. if (updatePanel == null)
  651. return;
  652. if (_disposeScripts == null)
  653. _disposeScripts = new List<DisposeScriptEntry> ();
  654. _disposeScripts.Add (new DisposeScriptEntry (updatePanel, disposeScript));
  655. }
  656. static UpdatePanel GetUpdatePanel (Control control) {
  657. if (control == null)
  658. return null;
  659. UpdatePanel parent = control.Parent as UpdatePanel;
  660. if (parent != null)
  661. return parent;
  662. return GetUpdatePanel (control.Parent);
  663. }
  664. public static void RegisterExpandoAttribute (Control control, string controlId, string attributeName, string attributeValue, bool encode) {
  665. Page page = control.Page;
  666. ScriptManager sm = GetCurrent (page);
  667. if (sm.IsInAsyncPostBack)
  668. sm.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
  669. else
  670. page.ClientScript.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
  671. }
  672. private void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue, bool encode) {
  673. // seems MS do nothing.
  674. }
  675. public static void RegisterHiddenField (Control control, string hiddenFieldName, string hiddenFieldInitialValue) {
  676. RegisterHiddenField (control.Page, hiddenFieldName, hiddenFieldInitialValue);
  677. }
  678. public static void RegisterHiddenField (Page page, string hiddenFieldName, string hiddenFieldInitialValue) {
  679. ScriptManager sm = GetCurrent (page);
  680. if (sm.IsInAsyncPostBack)
  681. sm.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  682. else
  683. page.ClientScript.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  684. }
  685. void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue) {
  686. if (_hiddenFields == null)
  687. _hiddenFields = new Hashtable ();
  688. if (!_hiddenFields.ContainsKey (hiddenFieldName))
  689. _hiddenFields.Add (hiddenFieldName, hiddenFieldInitialValue);
  690. }
  691. public static void RegisterOnSubmitStatement (Control control, Type type, string key, string script) {
  692. RegisterOnSubmitStatement (control.Page, type, key, script);
  693. }
  694. public static void RegisterOnSubmitStatement (Page page, Type type, string key, string script) {
  695. ScriptManager sm = GetCurrent (page);
  696. if (sm.IsInAsyncPostBack)
  697. RegisterScript (ref sm._onSubmitStatements, type, key, script, ScriptEntryType.OnSubmit);
  698. else
  699. page.ClientScript.RegisterOnSubmitStatement (type, key, script);
  700. }
  701. public void RegisterPostBackControl (Control control) {
  702. if (control == null)
  703. return;
  704. if (_postBackControls == null)
  705. _postBackControls = new List<Control> ();
  706. if (_postBackControls.Contains (control))
  707. return;
  708. _postBackControls.Add (control);
  709. }
  710. internal void RegisterUpdatePanel (UpdatePanel updatePanel) {
  711. if (_updatePanels == null)
  712. _updatePanels = new List<UpdatePanel> ();
  713. if (_updatePanels.Contains (updatePanel))
  714. return;
  715. _updatePanels.Add (updatePanel);
  716. }
  717. public void RegisterScriptDescriptors (IExtenderControl extenderControl) {
  718. if (extenderControl == null)
  719. return;
  720. if (_registeredExtenderControls == null || !_registeredExtenderControls.ContainsKey (extenderControl))
  721. return;
  722. Control targetControl = _registeredExtenderControls [extenderControl];
  723. RegisterScriptDescriptors (extenderControl.GetScriptDescriptors (targetControl));
  724. }
  725. public void RegisterScriptDescriptors (IScriptControl scriptControl) {
  726. if (scriptControl == null)
  727. return;
  728. if (_registeredScriptControls == null || !_registeredScriptControls.Contains (scriptControl))
  729. return;
  730. RegisterScriptDescriptors (scriptControl.GetScriptDescriptors ());
  731. }
  732. void RegisterScriptDescriptors (IEnumerable<ScriptDescriptor> scriptDescriptors) {
  733. if (scriptDescriptors == null)
  734. return;
  735. if (IsInAsyncPostBack && !IsInPartialRendering)
  736. return;
  737. StringBuilder sb = new StringBuilder ();
  738. foreach (ScriptDescriptor scriptDescriptor in scriptDescriptors) {
  739. sb.AppendLine ("Sys.Application.add_init(function() {");
  740. sb.AppendLine (scriptDescriptor.GetScript ());
  741. sb.AppendLine ("});");
  742. }
  743. string script = sb.ToString ();
  744. RegisterStartupScript (this, typeof (ExtenderControl), script, script, true);
  745. }
  746. public static void RegisterStartupScript (Control control, Type type, string key, string script, bool addScriptTags) {
  747. RegisterStartupScript (control.Page, type, key, script, addScriptTags);
  748. }
  749. public static void RegisterStartupScript (Page page, Type type, string key, string script, bool addScriptTags) {
  750. ScriptManager sm = GetCurrent (page);
  751. if (sm.IsInAsyncPostBack)
  752. RegisterScript (ref sm._startupScriptBlocks, type, key, script, addScriptTags ? ScriptEntryType.ScriptContentNoTags : ScriptEntryType.ScriptContentWithTags);
  753. else
  754. page.ClientScript.RegisterStartupScript (type, key, script, addScriptTags);
  755. }
  756. public void RegisterScriptControl<TScriptControl> (TScriptControl scriptControl) where TScriptControl : Control, IScriptControl {
  757. if (scriptControl == null)
  758. throw new ArgumentNullException ("scriptControl");
  759. if (_registeredScriptControls == null)
  760. _registeredScriptControls = new List<IScriptControl> ();
  761. if (!_registeredScriptControls.Contains (scriptControl))
  762. _registeredScriptControls.Add (scriptControl);
  763. }
  764. public void RegisterExtenderControl<TExtenderControl> (TExtenderControl extenderControl, Control targetControl) where TExtenderControl : Control, IExtenderControl {
  765. if (extenderControl == null)
  766. throw new ArgumentNullException ("extenderControl");
  767. if (targetControl == null)
  768. throw new ArgumentNullException ("targetControl");
  769. if (_registeredExtenderControls == null)
  770. _registeredExtenderControls = new Dictionary<IExtenderControl, Control> ();
  771. if (!_registeredExtenderControls.ContainsKey (extenderControl))
  772. _registeredExtenderControls.Add (extenderControl, targetControl);
  773. }
  774. static void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, ScriptEntryType scriptEntryType) {
  775. ScriptEntry last = null;
  776. ScriptEntry entry = scriptList;
  777. while (entry != null) {
  778. if (entry.Type == type && entry.Key == key)
  779. return;
  780. last = entry;
  781. entry = entry.Next;
  782. }
  783. entry = new ScriptEntry (type, key, script, scriptEntryType);
  784. if (last != null)
  785. last.Next = entry;
  786. else
  787. scriptList = entry;
  788. }
  789. protected override void Render (HtmlTextWriter writer) {
  790. // MSDN: This method is used by control developers to extend the ScriptManager control.
  791. // Notes to Inheritors:
  792. // When overriding this method, call the base Render(HtmlTextWriter) method
  793. // so that PageRequestManager is rendered on the page.
  794. if (SupportsPartialRendering) {
  795. writer.WriteLine ("<script type=\"text/javascript\">");
  796. writer.WriteLine ("//<![CDATA[");
  797. writer.WriteLine ("Sys.WebForms.PageRequestManager._initialize('{0}', document.getElementById('{1}'));", UniqueID, Page.Form.ClientID);
  798. writer.WriteLine ("Sys.WebForms.PageRequestManager.getInstance()._updateControls([{0}], [{1}], [{2}], {3});", FormatUpdatePanelIDs (_updatePanels, true), FormatListIDs (_asyncPostBackControls, true), FormatListIDs (_postBackControls, true), AsyncPostBackTimeout);
  799. writer.WriteLine ("//]]");
  800. writer.WriteLine ("</script>");
  801. }
  802. base.Render (writer);
  803. }
  804. static string FormatUpdatePanelIDs (List<UpdatePanel> list, bool useSingleQuote) {
  805. if (list == null || list.Count == 0)
  806. return null;
  807. StringBuilder sb = new StringBuilder ();
  808. for (int i = 0; i < list.Count; i++) {
  809. sb.AppendFormat ("{0}{1}{2}{0},", useSingleQuote ? "'" : String.Empty, list [i].ChildrenAsTriggers ? "t" : "f", list [i].UniqueID);
  810. }
  811. if (sb.Length > 0)
  812. sb.Length--;
  813. return sb.ToString ();
  814. }
  815. static string FormatListIDs<T> (List<T> list, bool useSingleQuote) where T : Control {
  816. if (list == null || list.Count == 0)
  817. return null;
  818. StringBuilder sb = new StringBuilder ();
  819. for (int i = 0; i < list.Count; i++) {
  820. sb.AppendFormat ("{0}{1}{0},", useSingleQuote ? "'" : String.Empty, list [i].UniqueID);
  821. }
  822. if (sb.Length > 0)
  823. sb.Length--;
  824. return sb.ToString ();
  825. }
  826. public void SetFocus (Control control) {
  827. if (control == null)
  828. throw new ArgumentNullException ("control");
  829. if (IsInAsyncPostBack) {
  830. EnsureFocusClientScript ();
  831. _controlIDToFocus = control.ClientID;
  832. }
  833. else
  834. Page.SetFocus (control);
  835. }
  836. public void SetFocus (string clientID) {
  837. if (String.IsNullOrEmpty (clientID))
  838. throw new ArgumentNullException ("control");
  839. if (IsInAsyncPostBack) {
  840. EnsureFocusClientScript ();
  841. _controlIDToFocus = clientID;
  842. }
  843. else
  844. Page.SetFocus (clientID);
  845. }
  846. void EnsureFocusClientScript () {
  847. #if TARGET_DOTNET
  848. RegisterClientScriptResource (this, typeof (ClientScriptManager), "Focus.js");
  849. #endif
  850. }
  851. #region IPostBackDataHandler Members
  852. bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection) {
  853. return LoadPostData (postDataKey, postCollection);
  854. }
  855. void IPostBackDataHandler.RaisePostDataChangedEvent () {
  856. RaisePostDataChangedEvent ();
  857. }
  858. #endregion
  859. internal void WriteCallbackException (TextWriter output, Exception ex, bool writeMessage) {
  860. #if TARGET_DOTNET
  861. if (ex is HttpUnhandledException)
  862. ex = ex.InnerException;
  863. #endif
  864. HttpException httpEx = ex as HttpException;
  865. string message = AsyncPostBackErrorMessage;
  866. if (String.IsNullOrEmpty (message) && writeMessage)
  867. message = ex.Message;
  868. WriteCallbackOutput (output, error, httpEx == null ? "500" : httpEx.GetHttpCode ().ToString (), message);
  869. }
  870. static internal void WriteCallbackRedirect (TextWriter output, string redirectUrl) {
  871. WriteCallbackOutput (output, pageRedirect, null, redirectUrl);
  872. }
  873. internal void WriteCallbackPanel (TextWriter output, UpdatePanel panel, StringBuilder panelOutput) {
  874. if (_panelsToRefresh == null)
  875. _panelsToRefresh = new List<UpdatePanel> ();
  876. _panelsToRefresh.Add (panel);
  877. WriteCallbackOutput (output, updatePanel, panel.ClientID, panelOutput);
  878. }
  879. internal void RegisterChildUpdatePanel (UpdatePanel updatePanel) {
  880. if (_childUpdatePanels == null)
  881. _childUpdatePanels = new List<UpdatePanel> ();
  882. _childUpdatePanels.Add (updatePanel);
  883. }
  884. static void WriteCallbackOutput (TextWriter output, string type, string name, object value) {
  885. string str = value as string;
  886. StringBuilder sb = value as StringBuilder;
  887. int length = 0;
  888. if (str != null)
  889. length = str.Length;
  890. else if (sb != null)
  891. length = sb.Length;
  892. //output.Write ("{0}|{1}|{2}|{3}|", value == null ? 0 : value.Length, type, name, value);
  893. output.Write (length);
  894. output.Write ('|');
  895. output.Write (type);
  896. output.Write ('|');
  897. output.Write (name);
  898. output.Write ('|');
  899. for (int i = 0; i < length; i++)
  900. if (str != null)
  901. output.Write (str [i]);
  902. else
  903. output.Write (sb [i]);
  904. output.Write ('|');
  905. }
  906. void RenderPageCallback (HtmlTextWriter output, Control container) {
  907. Page page = (Page) container;
  908. page.Form.SetRenderMethodDelegate (RenderFormCallback);
  909. HtmlTextParser parser = new HtmlTextParser (output);
  910. page.Form.RenderControl (parser);
  911. WriteCallbackOutput (output, asyncPostBackControlIDs, null, FormatListIDs (_asyncPostBackControls, false));
  912. WriteCallbackOutput (output, postBackControlIDs, null, FormatListIDs (_postBackControls, false));
  913. WriteCallbackOutput (output, updatePanelIDs, null, FormatUpdatePanelIDs (_updatePanels, false));
  914. WriteCallbackOutput (output, childUpdatePanelIDs, null, FormatListIDs (_childUpdatePanels, false));
  915. WriteCallbackOutput (output, panelsToRefreshIDs, null, FormatListIDs (_panelsToRefresh, false));
  916. WriteCallbackOutput (output, asyncPostBackTimeout, null, AsyncPostBackTimeout.ToString ());
  917. WriteCallbackOutput (output, pageTitle, null, Page.Title);
  918. if (_dataItems != null)
  919. foreach (Control control in _dataItems.Keys) {
  920. DataItemEntry entry = _dataItems [control];
  921. WriteCallbackOutput (output, entry.IsJsonSerialized ? dataItemJson : dataItem, control.ClientID, entry.DataItem);
  922. }
  923. WriteArrayDeclarations (output);
  924. WriteScriptBlocks (output, _clientScriptBlocks);
  925. WriteScriptBlocks (output, _scriptIncludes);
  926. WriteScriptBlocks (output, _startupScriptBlocks);
  927. WriteScriptBlocks (output, _onSubmitStatements);
  928. WriteHiddenFields (output);
  929. if (!String.IsNullOrEmpty (_controlIDToFocus))
  930. WriteCallbackOutput (output, focus, null, _controlIDToFocus);
  931. if (_disposeScripts != null)
  932. for (int i = 0; i < _disposeScripts.Count; i++) {
  933. DisposeScriptEntry entry = _disposeScripts [i];
  934. if ((_panelsToRefresh != null && _panelsToRefresh.IndexOf (entry.UpdatePanel) >= 0) || (_childUpdatePanels != null && _childUpdatePanels.IndexOf (entry.UpdatePanel) >= 0))
  935. WriteCallbackOutput (output, scriptDispose, entry.UpdatePanel.ClientID, entry.Script);
  936. }
  937. }
  938. void WriteArrayDeclarations (HtmlTextWriter writer) {
  939. if (_arrayDeclarations != null) {
  940. for (int i = 0; i < _arrayDeclarations.Count; i++) {
  941. ArrayDeclaration array = _arrayDeclarations [i];
  942. WriteCallbackOutput (writer, arrayDeclaration, array.ArrayName, array.ArrayValue);
  943. }
  944. }
  945. }
  946. void WriteScriptBlocks (HtmlTextWriter output, ScriptEntry scriptList) {
  947. while (scriptList != null) {
  948. switch (scriptList.ScriptEntryType) {
  949. case ScriptEntryType.ScriptContentNoTags:
  950. WriteCallbackOutput (output, scriptBlock, scriptContentNoTags, scriptList.Script);
  951. break;
  952. case ScriptEntryType.ScriptContentWithTags:
  953. string script = SerializeScriptBlock (scriptList);
  954. WriteCallbackOutput (output, scriptBlock, scriptContentWithTags, script);
  955. break;
  956. case ScriptEntryType.ScriptPath:
  957. WriteCallbackOutput (output, scriptBlock, scriptPath, scriptList.Script);
  958. break;
  959. case ScriptEntryType.OnSubmit:
  960. WriteCallbackOutput (output, onSubmit, null, scriptList.Script);
  961. break;
  962. }
  963. scriptList = scriptList.Next;
  964. }
  965. }
  966. void WriteHiddenFields (HtmlTextWriter output) {
  967. if (_hiddenFields == null)
  968. return;
  969. foreach (string key in _hiddenFields.Keys) {
  970. string value = _hiddenFields [key] as string;
  971. WriteCallbackOutput (output, hiddenField, key, value);
  972. }
  973. }
  974. static string SerializeScriptBlock (ScriptEntry scriptList) {
  975. try {
  976. XmlTextReader reader = new XmlTextReader (new StringReader (scriptList.Script));
  977. while (reader.Read ()) {
  978. switch (reader.NodeType) {
  979. case XmlNodeType.Element:
  980. if (String.Compare ("script", reader.Name, StringComparison.OrdinalIgnoreCase) == 0) {
  981. Dictionary<string, string> dic = new Dictionary<string, string> ();
  982. while (reader.MoveToNextAttribute ()) {
  983. dic.Add (reader.Name, reader.Value);
  984. }
  985. reader.MoveToContent ();
  986. dic.Add ("text", reader.ReadInnerXml ());
  987. return JavaScriptSerializer.DefaultSerializer.Serialize (dic);
  988. }
  989. break;
  990. default:
  991. continue;
  992. }
  993. }
  994. }
  995. catch {
  996. }
  997. 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));
  998. }
  999. void RenderFormCallback (HtmlTextWriter output, Control container) {
  1000. output = ((HtmlTextParser) output).ResponseOutput;
  1001. HtmlForm form = (HtmlForm) container;
  1002. HtmlTextWriter writer = new HtmlDropWriter (output);
  1003. if (form.HasControls ()) {
  1004. for (int i = 0; i < form.Controls.Count; i++) {
  1005. form.Controls [i].RenderControl (writer);
  1006. }
  1007. }
  1008. }
  1009. internal class AlternativeHtmlTextWriter : HtmlTextWriter
  1010. {
  1011. readonly HtmlTextWriter _responseOutput;
  1012. public HtmlTextWriter ResponseOutput {
  1013. get { return _responseOutput; }
  1014. }
  1015. public AlternativeHtmlTextWriter (TextWriter writer, HtmlTextWriter responseOutput)
  1016. : base (writer) {
  1017. _responseOutput = responseOutput;
  1018. }
  1019. }
  1020. sealed class HtmlTextParser : AlternativeHtmlTextWriter
  1021. {
  1022. public HtmlTextParser (HtmlTextWriter responseOutput)
  1023. : base (new TextParser (responseOutput), responseOutput) {
  1024. }
  1025. }
  1026. sealed class TextParser : TextWriter
  1027. {
  1028. int _state;
  1029. char _charState = (char) 255;
  1030. const char nullCharState = (char) 255;
  1031. StringBuilder _sb = new StringBuilder ();
  1032. Dictionary<string, string> _currentField;
  1033. string _currentAttribute;
  1034. readonly HtmlTextWriter _responseOutput;
  1035. public override Encoding Encoding {
  1036. get { return Encoding.UTF8; }
  1037. }
  1038. public TextParser (HtmlTextWriter responseOutput) {
  1039. _responseOutput = responseOutput;
  1040. }
  1041. public override void Write (char value) {
  1042. switch (_state) {
  1043. case 0:
  1044. ParseBeginTag (value);
  1045. break;
  1046. case 1:
  1047. ParseAttributeName (value);
  1048. break;
  1049. case 2:
  1050. ParseAttributeValue (value);
  1051. break;
  1052. }
  1053. }
  1054. private void ParseAttributeValue (char value) {
  1055. switch (value) {
  1056. case '>':
  1057. ResetState ();
  1058. break;
  1059. case '"':
  1060. _currentField.Add (_currentAttribute, _sb.ToString ());
  1061. _state = 1;
  1062. _sb.Length = 0;
  1063. ProbeWriteOutput ();
  1064. break;
  1065. default:
  1066. _sb.Append (value);
  1067. break;
  1068. }
  1069. }
  1070. private void ParseAttributeName (char value) {
  1071. switch (value) {
  1072. case '>':
  1073. ResetState ();
  1074. break;
  1075. case ' ':
  1076. case '=':
  1077. break;
  1078. case '"':
  1079. _currentAttribute = _sb.ToString ();
  1080. _state = 2;
  1081. _sb.Length = 0;
  1082. break;
  1083. default:
  1084. _sb.Append (value);
  1085. break;
  1086. }
  1087. }
  1088. void ParseBeginTag (char value) {
  1089. switch (_charState) {
  1090. case nullCharState:
  1091. if (value == '<')
  1092. _charState = value;
  1093. break;
  1094. case '<':
  1095. if (value == 'i')
  1096. _charState = value;
  1097. else
  1098. ResetState ();
  1099. break;
  1100. case 'i':
  1101. if (value == 'n')
  1102. _charState = value;
  1103. else
  1104. ResetState ();
  1105. break;
  1106. case 'n':
  1107. if (value == 'p')
  1108. _charState = value;
  1109. else
  1110. ResetState ();
  1111. break;
  1112. case 'p':
  1113. if (value == 'u')
  1114. _charState = value;
  1115. else
  1116. ResetState ();
  1117. break;
  1118. case 'u':
  1119. if (value == 't')
  1120. _charState = value;
  1121. else
  1122. ResetState ();
  1123. break;
  1124. case 't':
  1125. if (value == ' ') {
  1126. _state = 1;
  1127. _currentField = new Dictionary<string, string> ();
  1128. }
  1129. else
  1130. ResetState ();
  1131. break;
  1132. }
  1133. }
  1134. private void ResetState () {
  1135. _charState = nullCharState;
  1136. _state = 0;
  1137. _sb.Length = 0;
  1138. }
  1139. private void ProbeWriteOutput () {
  1140. if (!_currentField.ContainsKey ("name"))
  1141. return;
  1142. if (!_currentField.ContainsKey ("value"))
  1143. return;
  1144. string value = _currentField ["value"];
  1145. if (String.IsNullOrEmpty (value))
  1146. return;
  1147. ScriptManager.WriteCallbackOutput (_responseOutput, ScriptManager.hiddenField, _currentField ["name"], value);
  1148. }
  1149. }
  1150. sealed class HtmlDropWriter : AlternativeHtmlTextWriter
  1151. {
  1152. public HtmlDropWriter (HtmlTextWriter responseOutput)
  1153. : base (new DropWriter (), responseOutput) {
  1154. }
  1155. }
  1156. sealed class DropWriter : TextWriter
  1157. {
  1158. public override Encoding Encoding {
  1159. get { return Encoding.UTF8; }
  1160. }
  1161. }
  1162. sealed class ScriptEntry
  1163. {
  1164. readonly public Type Type;
  1165. readonly public string Key;
  1166. readonly public string Script;
  1167. readonly public ScriptEntryType ScriptEntryType;
  1168. public ScriptEntry Next;
  1169. public ScriptEntry (Type type, string key, string script, ScriptEntryType scriptEntryType) {
  1170. Key = key;
  1171. Type = type;
  1172. Script = script;
  1173. ScriptEntryType = scriptEntryType;
  1174. }
  1175. }
  1176. enum ScriptEntryType
  1177. {
  1178. ScriptContentNoTags,
  1179. ScriptContentWithTags,
  1180. ScriptPath,
  1181. OnSubmit
  1182. }
  1183. sealed class ArrayDeclaration
  1184. {
  1185. readonly public string ArrayName;
  1186. readonly public string ArrayValue;
  1187. public ArrayDeclaration (string arrayName, string arrayValue) {
  1188. ArrayName = arrayName;
  1189. ArrayValue = arrayValue;
  1190. }
  1191. }
  1192. sealed class CultureInfoSerializer : JavaScriptSerializer.LazyDictionary
  1193. {
  1194. readonly CultureInfo _ci;
  1195. public CultureInfoSerializer (CultureInfo ci) {
  1196. if (ci == null)
  1197. throw new ArgumentNullException ("ci");
  1198. _ci = ci;
  1199. }
  1200. protected override IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
  1201. yield return new KeyValuePair<string, object> ("name", _ci.Name);
  1202. yield return new KeyValuePair<string, object> ("numberFormat", _ci.NumberFormat);
  1203. yield return new KeyValuePair<string, object> ("dateTimeFormat", _ci.DateTimeFormat);
  1204. }
  1205. }
  1206. sealed class ScriptReferenceEntry
  1207. {
  1208. readonly Control _control;
  1209. readonly ScriptReference _scriptReference;
  1210. readonly bool _loadBeforeUI;
  1211. public Control Control { get { return _control; } }
  1212. public ScriptReference ScriptReference { get { return _scriptReference; } }
  1213. public bool LoadScriptsBeforeUI { get { return _loadBeforeUI; } }
  1214. public ScriptReferenceEntry (Control control, ScriptReference scriptReference, bool loadBeforeUI) {
  1215. _control = control;
  1216. _scriptReference = scriptReference;
  1217. _loadBeforeUI = loadBeforeUI;
  1218. }
  1219. }
  1220. sealed class DataItemEntry
  1221. {
  1222. readonly string _dataItem;
  1223. readonly bool _isJsonSerialized;
  1224. public string DataItem { get { return _dataItem; } }
  1225. public bool IsJsonSerialized { get { return _isJsonSerialized; } }
  1226. public DataItemEntry (string dataItem, bool isJsonSerialized) {
  1227. _dataItem = dataItem;
  1228. _isJsonSerialized = isJsonSerialized;
  1229. }
  1230. }
  1231. sealed class DisposeScriptEntry
  1232. {
  1233. readonly UpdatePanel _updatePanel;
  1234. readonly string _script;
  1235. public UpdatePanel UpdatePanel { get { return _updatePanel; } }
  1236. public string Script { get { return _script; } }
  1237. public DisposeScriptEntry (UpdatePanel updatePanel, string script) {
  1238. _updatePanel = updatePanel;
  1239. _script = script;
  1240. }
  1241. }
  1242. }
  1243. }