PageRenderTime 58ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/mcs/class/System.Web.Extensions/System.Web.UI/ScriptManager.cs

https://bitbucket.org/danipen/mono
C# | 1857 lines | 1507 code | 270 blank | 80 comment | 387 complexity | 286448d76ece5f44ee00a26bdf45531e MD5 | raw file
Possible License(s): Unlicense, Apache-2.0, LGPL-2.0, MPL-2.0-no-copyleft-exception, CC-BY-SA-3.0, GPL-2.0

Large files files are truncated, but you can click here to view the full file

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

Large files files are truncated, but you can click here to view the full file