5 // Igor Zelmanovich <igorz@mainsoft.com>
6 // Marek Habersack <grendel@twistedcode.net>
8 // (C) 2007 Mainsoft, Inc. http://www.mainsoft.com
9 // (C) 2007-2010 Novell, Inc (http://novell.com/)
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:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
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.
33 using System.Collections.Generic;
35 using System.ComponentModel;
36 using System.Security.Permissions;
37 using System.Collections.Specialized;
38 using System.Collections;
39 using System.Web.Handlers;
40 using System.Reflection;
41 using System.Web.Configuration;
42 using System.Web.UI.HtmlControls;
44 using System.Globalization;
45 using System.Threading;
46 using System.Web.Script.Serialization;
47 using System.Web.Script.Services;
49 using System.Collections.ObjectModel;
50 using System.Web.Util;
52 namespace System.Web.UI
54 [ParseChildrenAttribute (true)]
55 [DefaultPropertyAttribute ("Scripts")]
56 [DesignerAttribute ("System.Web.UI.Design.ScriptManagerDesigner, System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
57 [NonVisualControlAttribute]
58 [PersistChildrenAttribute (false)]
59 [AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
60 [AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
61 public class ScriptManager : Control, IPostBackDataHandler, IScriptManager
63 // the keywords are used in fomatting async response
64 const string updatePanel = "updatePanel";
65 const string hiddenField = "hiddenField";
66 const string arrayDeclaration = "arrayDeclaration";
67 const string scriptBlock = "scriptBlock";
68 const string scriptStartupBlock = "scriptStartupBlock";
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";
89 static readonly object ScriptManagerKey = typeof (IScriptManager);
91 int _asyncPostBackTimeout = 90;
92 List<Control> _asyncPostBackControls;
93 List<Control> _postBackControls;
94 List<UpdatePanel> _childUpdatePanels;
95 List<UpdatePanel> _panelsToRefresh;
96 List<UpdatePanel> _updatePanels;
97 ScriptReferenceCollection _scripts;
98 CompositeScriptReference _compositeScript;
99 ServiceReferenceCollection _services;
100 bool _isInAsyncPostBack;
101 bool _isInPartialRendering;
102 string _asyncPostBackSourceElementID;
103 ScriptMode _scriptMode = ScriptMode.Auto;
104 bool _enableScriptGlobalization;
105 bool _enableScriptLocalization;
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;
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;
131 [DefaultValue (true)]
132 [Category ("Behavior")]
133 public bool AllowCustomErrorsRedirect {
135 return _allowCustomErrorsRedirect;
138 _allowCustomErrorsRedirect = value;
142 [Category ("Behavior")]
144 public string AsyncPostBackErrorMessage {
146 if (String.IsNullOrEmpty (_asyncPostBackErrorMessage))
148 return _asyncPostBackErrorMessage;
151 _asyncPostBackErrorMessage = value;
156 public string AsyncPostBackSourceElementID {
158 if (_asyncPostBackSourceElementID == null)
160 return _asyncPostBackSourceElementID;
165 [Category ("Behavior")]
166 public int AsyncPostBackTimeout {
168 return _asyncPostBackTimeout;
171 _asyncPostBackTimeout = value;
175 [Category ("Behavior")]
176 [MergableProperty (false)]
178 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
179 [PersistenceMode (PersistenceMode.InnerProperty)]
180 public AuthenticationServiceManager AuthenticationService {
182 if (_authenticationService == null)
183 _authenticationService = new AuthenticationServiceManager ();
184 return _authenticationService;
188 [Category ("Behavior")]
189 [DefaultValue (false)]
190 public bool EnablePageMethods {
192 return _enablePageMethods;
195 _enablePageMethods = value;
199 [DefaultValue (true)]
200 [Category ("Behavior")]
201 public bool EnablePartialRendering {
203 return _enablePartialRendering;
207 throw new InvalidOperationException ();
208 _enablePartialRendering = value;
212 [DefaultValue (false)]
213 [Category ("Behavior")]
214 public bool EnableScriptGlobalization {
216 return _enableScriptGlobalization;
219 _enableScriptGlobalization = value;
223 [Category ("Behavior")]
224 [DefaultValue (false)]
225 public bool EnableScriptLocalization {
227 return _enableScriptLocalization;
230 _enableScriptLocalization = value;
235 public bool IsDebuggingEnabled {
237 if (IsDeploymentRetail)
240 if (!RuntimeHelpers.DebuggingEnabled && (ScriptMode == ScriptMode.Auto || ScriptMode == ScriptMode.Inherit))
243 if (ScriptMode == ScriptMode.Release)
250 internal bool IsDeploymentRetail {
252 DeploymentSection deployment = (DeploymentSection) WebConfigurationManager.GetSection ("system.web/deployment");
253 return deployment.Retail;
258 public bool IsInAsyncPostBack {
260 return _isInAsyncPostBack;
264 internal bool IsInPartialRendering {
266 return _isInPartialRendering;
269 _isInPartialRendering = value;
273 [Category ("Behavior")]
274 [DefaultValue (true)]
275 public bool LoadScriptsBeforeUI {
277 return _loadScriptsBeforeUI;
280 _loadScriptsBeforeUI = value;
284 [PersistenceMode (PersistenceMode.InnerProperty)]
286 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
287 [Category ("Behavior")]
288 [MergableProperty (false)]
289 public ProfileServiceManager ProfileService {
291 if (_profileService == null)
292 _profileService = new ProfileServiceManager ();
293 return _profileService;
297 [Category ("Behavior")]
298 public ScriptMode ScriptMode {
303 if (value == ScriptMode.Inherit)
304 value = ScriptMode.Auto;
310 [Category ("Behavior")]
311 public string ScriptPath {
313 if (_scriptPath == null)
322 [PersistenceMode (PersistenceMode.InnerProperty)]
324 [Category ("Behavior")]
325 [MergableProperty (false)]
326 public ScriptReferenceCollection Scripts {
328 if (_scripts == null)
329 _scripts = new ScriptReferenceCollection ();
334 [PersistenceMode (PersistenceMode.InnerProperty)]
335 [Category ("Behavior")]
336 [DefaultValue (null)]
337 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
338 [MergableProperty (false)]
339 public CompositeScriptReference CompositeScript {
341 if (_compositeScript == null)
342 _compositeScript = new CompositeScriptReference ();
343 return _compositeScript;
346 [PersistenceMode (PersistenceMode.InnerProperty)]
348 [MergableProperty (false)]
349 [Category ("Behavior")]
350 public ServiceReferenceCollection Services {
352 if (_services == null)
353 _services = new ServiceReferenceCollection ();
359 [DefaultValue (true)]
361 public bool SupportsPartialRendering {
363 if (!_supportsPartialRendering.HasValue)
364 _supportsPartialRendering = CheckSupportsPartialRendering ();
365 return _supportsPartialRendering.Value;
369 throw new InvalidOperationException ();
370 if (!EnablePartialRendering && value)
371 throw new InvalidOperationException ("The SupportsPartialRendering property cannot be set when EnablePartialRendering is false.");
373 _supportsPartialRendering = value;
377 bool CheckSupportsPartialRendering () {
378 if (!EnablePartialRendering)
380 // TODO: consider browser capabilities
384 [EditorBrowsable (EditorBrowsableState.Never)]
386 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
387 public override bool Visible {
392 throw new NotImplementedException ();
396 [Category ("Action")]
397 public event EventHandler<AsyncPostBackErrorEventArgs> AsyncPostBackError;
399 [Category ("Action")]
400 public event EventHandler<ScriptReferenceEventArgs> ResolveScriptReference;
401 [Category ("Action")]
402 public event EventHandler<CompositeScriptReferenceEventArgs> ResolveCompositeScriptReference;
403 public static ScriptManager GetCurrent (Page page) {
405 throw new ArgumentNullException ("page");
406 return GetCurrentInternal (page);
409 internal static ScriptManager GetCurrentInternal (Page page)
414 return (ScriptManager) page.Items [ScriptManagerKey];
417 static void SetCurrent (Page page, ScriptManager instance) {
418 page.Items [ScriptManagerKey] = instance;
419 page.ClientScript.RegisterWebFormClientScript ();
422 UpdatePanel FindPanelWithId (string id)
424 if (_updatePanels == null)
426 foreach (UpdatePanel panel in _updatePanels) {
433 protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection) {
434 _isInAsyncPostBack = true;
435 string arg = postCollection [postDataKey];
436 if (!String.IsNullOrEmpty (arg)) {
437 string [] args = arg.Split ('|');
438 switch (args.Length) {
440 _asyncPostBackSourceElementID = args [0];
444 _panelToRefreshID = args [0];
445 _asyncPostBackSourceElementID = args [1];
448 default: // "impossible situation"
449 throw new InvalidOperationException ("Unexpected format of post data.");
457 protected internal virtual void OnAsyncPostBackError (AsyncPostBackErrorEventArgs e) {
458 if (AsyncPostBackError != null)
459 AsyncPostBackError (this, e);
462 protected internal override void OnInit (EventArgs e) {
465 if (GetCurrentInternal (Page) != null)
466 throw new InvalidOperationException ("Only one instance of a ScriptManager can be added to the page.");
468 SetCurrent (Page, this);
469 Page.Error += new EventHandler (OnPageError);
473 void OnPageError (object sender, EventArgs e) {
474 if (IsInAsyncPostBack)
475 OnAsyncPostBackError (new AsyncPostBackErrorEventArgs (Context.Error));
478 protected internal override void OnPreRender (EventArgs e) {
479 base.OnPreRender (e);
481 Page.PreRenderComplete += new EventHandler (OnPreRenderComplete);
483 if (IsInAsyncPostBack) {
484 Page.SetRenderMethodDelegate (RenderPageCallback);
487 if (EnableScriptGlobalization) {
488 CultureInfo culture = Thread.CurrentThread.CurrentCulture;
489 string script = String.Format ("var __cultureInfo = '{0}';", JavaScriptSerializer.DefaultSerializer.Serialize (new CultureInfoSerializer (culture)));
490 RegisterClientScriptBlock (this, typeof (ScriptManager), "ScriptGlobalization", script, true);
493 // Register dispose script
494 if (_disposeScripts != null && _disposeScripts.Count > 0) {
495 StringBuilder sb = new StringBuilder ();
497 for (int i = 0; i < _disposeScripts.Count; i++) {
498 RegisteredDisposeScript entry = _disposeScripts [i];
500 sb.Append ("Sys.WebForms.PageRequestManager.getInstance($get(\"" + Page.Form.ClientID + "\"))._registerDisposeScript(\"");
502 sb.Append ("Sys.WebForms.PageRequestManager.getInstance()._registerDisposeScript(\"");
503 sb.Append (entry.UpdatePanel.ClientID);
505 sb.Append (JavaScriptSerializer.DefaultSerializer.Serialize (entry.Script)); //JavaScriptSerializer.Serialize used escape script literal
506 sb.AppendLine (");");
508 RegisterStartupScript (this, typeof (ExtenderControl), "disposeScripts;", sb.ToString (), true);
512 // to cause webform client script being included
513 Page.ClientScript.GetPostBackEventReference (new PostBackOptions (this, null, null, false, false, false, true, true, null));
515 Page.ClientScript.GetPostBackEventReference (this, null);
520 ScriptReference CreateScriptReference (string path, string assembly, bool notifyScriptLoaded)
522 var ret = new ScriptReference (path, assembly);
523 if (!notifyScriptLoaded)
524 ret.NotifyScriptLoaded = false;
525 OnResolveScriptReference (new ScriptReferenceEventArgs (ret));
530 ScriptReference CreateScriptReference (string path, string assembly)
532 return CreateScriptReference (path, assembly, true);
535 void OnPreRenderComplete (object sender, EventArgs e)
538 ScriptReference ajaxScript = CreateScriptReference ("MicrosoftAjax.js", String.Empty, false);
539 ScriptReference ajaxWebFormsScript = CreateScriptReference ("MicrosoftAjaxWebForms.js", String.Empty, false);
540 ScriptReference ajaxExtensionScript = null;
541 ScriptReference ajaxWebFormsExtensionScript = null;
543 ajaxExtensionScript = CreateScriptReference ("MicrosoftAjaxExtension.js", String.Empty);
544 ajaxWebFormsExtensionScript = CreateScriptReference ("MicrosoftAjaxWebFormsExtension.js", String.Empty);
547 foreach (ScriptReferenceEntry script in GetScriptReferences ()) {
548 OnResolveScriptReference (new ScriptReferenceEventArgs (script.ScriptReference));
549 if (_scriptToRegister == null)
550 _scriptToRegister = new List<ScriptReferenceEntry> ();
551 _scriptToRegister.Add (script);
554 if (!IsInAsyncPostBack) {
555 // Register Ajax framework script.
556 RegisterScriptReference (this, ajaxScript, true);
558 RegisterScriptReference (this, ajaxExtensionScript, true);
559 RegisterClientScriptBlock (this, typeof (ScriptManager), "Sys.Application", "\nSys.Application._initialize(document.getElementById('" + Page.Form.ClientID + "'));\n", true);
562 StringBuilder sb = new StringBuilder ();
563 sb.AppendLine ("if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');");
565 ScriptingProfileServiceSection profileService = (ScriptingProfileServiceSection) WebConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/profileService");
566 if (profileService != null && profileService.Enabled)
567 sb.AppendLine ("Sys.Services._ProfileService.DefaultWebServicePath = '" + ResolveClientUrl ("~" + System.Web.Script.Services.ProfileService.DefaultWebServicePath) + "';");
568 string profileServicePath = GetProfileServicePath ();
569 if (!String.IsNullOrEmpty (profileServicePath))
570 sb.AppendLine ("Sys.Services.ProfileService.set_path('" + profileServicePath + "');");
572 ScriptingAuthenticationServiceSection authenticationService = (ScriptingAuthenticationServiceSection) WebConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/authenticationService");
573 if (authenticationService != null && authenticationService.Enabled) {
574 sb.AppendLine ("Sys.Services._AuthenticationService.DefaultWebServicePath = '" + ResolveClientUrl ("~/Authentication_JSON_AppService.axd") + "';");
575 if (Page.User.Identity.IsAuthenticated)
576 sb.AppendLine ("Sys.Services.AuthenticationService._setAuthenticated(true);");
578 string authenticationServicePath = GetAuthenticationServicePath ();
579 if (!String.IsNullOrEmpty (authenticationServicePath))
580 sb.AppendLine ("Sys.Services.AuthenticationService.set_path('" + authenticationServicePath + "');");
582 RegisterClientScriptBlock (this, typeof (ScriptManager), "Framework", sb.ToString (), true);
584 RegisterScriptReference (this, ajaxWebFormsScript, true);
587 RegisterScriptReference (this, ajaxWebFormsExtensionScript, true);
589 if (_compositeScript != null && _compositeScript.HaveScripts ()) {
590 OnResolveCompositeScriptReference (new CompositeScriptReferenceEventArgs (_compositeScript));
591 RegisterScriptReference (this, _compositeScript, true);
594 if (_scriptToRegister != null)
595 for (int i = 0; i < _scriptToRegister.Count; i++)
596 RegisterScriptReference (_scriptToRegister [i].Control, _scriptToRegister [i].ScriptReference, _scriptToRegister [i].LoadScriptsBeforeUI);
598 if (!IsInAsyncPostBack) {
600 if (_services != null && _services.Count > 0) {
601 for (int i = 0; i < _services.Count; i++) {
602 RegisterServiceReference (this, _services [i]);
606 if (_proxies != null && _proxies.Count > 0) {
607 for (int i = 0; i < _proxies.Count; i++) {
608 ScriptManagerProxy proxy = _proxies [i];
609 for (int j = 0; j < proxy.Services.Count; j++) {
610 RegisterServiceReference (proxy, proxy.Services [j]);
615 if (EnablePageMethods) {
616 LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (Page.GetType (), Page.Request.FilePath);
617 RegisterClientScriptBlock (this, typeof (ScriptManager), "PageMethods", logicalTypeInfo.Proxy, true);
620 // Register startup script
622 RegisterStartupScript (this, typeof (ExtenderControl), "Sys.Application.initialize();", "Sys.Application.getInstance($get(\"" + Page.Form.ClientID + "\")).initialize();\n", true);
624 RegisterStartupScript (this, typeof (ExtenderControl), "Sys.Application.initialize();", "Sys.Application.initialize();\n", true);
628 string GetProfileServicePath () {
629 if (_profileService != null && !String.IsNullOrEmpty (_profileService.Path))
630 return ResolveClientUrl (_profileService.Path);
632 if (_proxies != null && _proxies.Count > 0)
633 for (int i = 0; i < _proxies.Count; i++)
634 if (!String.IsNullOrEmpty (_proxies [i].ProfileService.Path))
635 return _proxies [i].ResolveClientUrl (_proxies [i].ProfileService.Path);
639 string GetAuthenticationServicePath () {
640 if (_authenticationService != null && !String.IsNullOrEmpty (_authenticationService.Path))
641 return ResolveClientUrl (_authenticationService.Path);
643 if (_proxies != null && _proxies.Count > 0)
644 for (int i = 0; i < _proxies.Count; i++)
645 if (!String.IsNullOrEmpty (_proxies [i].AuthenticationService.Path))
646 return _proxies [i].ResolveClientUrl (_proxies [i].AuthenticationService.Path);
650 public ReadOnlyCollection<RegisteredArrayDeclaration> GetRegisteredArrayDeclarations () {
651 if (_arrayDeclarations == null)
652 _arrayDeclarations = new List<RegisteredArrayDeclaration> ();
653 return new ReadOnlyCollection<RegisteredArrayDeclaration> (_arrayDeclarations);
656 public ReadOnlyCollection<RegisteredScript> GetRegisteredClientScriptBlocks () {
657 if (_clientScriptBlocks == null)
658 _clientScriptBlocks = new List<RegisteredScript> ();
659 return new ReadOnlyCollection<RegisteredScript> (_clientScriptBlocks);
662 public ReadOnlyCollection<RegisteredDisposeScript> GetRegisteredDisposeScripts () {
663 if (_disposeScripts == null)
664 _disposeScripts = new List<RegisteredDisposeScript> ();
665 return new ReadOnlyCollection<RegisteredDisposeScript> (_disposeScripts);
668 public ReadOnlyCollection<RegisteredExpandoAttribute> GetRegisteredExpandoAttributes () {
669 if (_expandoAttributes == null)
670 _expandoAttributes = new List<RegisteredExpandoAttribute> ();
671 return new ReadOnlyCollection<RegisteredExpandoAttribute> (_expandoAttributes);
674 public ReadOnlyCollection<RegisteredHiddenField> GetRegisteredHiddenFields () {
675 if (_hiddenFields == null)
676 _hiddenFields = new List<RegisteredHiddenField> ();
677 return new ReadOnlyCollection<RegisteredHiddenField> (_hiddenFields);
680 public ReadOnlyCollection<RegisteredScript> GetRegisteredOnSubmitStatements () {
681 if (_onSubmitStatements == null)
682 _onSubmitStatements = new List<RegisteredScript> ();
683 return new ReadOnlyCollection<RegisteredScript> (_onSubmitStatements);
686 public ReadOnlyCollection<RegisteredScript> GetRegisteredStartupScripts () {
687 if (_startupScriptBlocks == null)
688 _startupScriptBlocks = new List<RegisteredScript> ();
689 return new ReadOnlyCollection<RegisteredScript> (_startupScriptBlocks);
693 get { return false; }
696 bool PanelRequiresUpdate (UpdatePanel panel)
698 if (panel == null || _panelsToRefresh == null || _panelsToRefresh.Count == 0)
701 return _panelsToRefresh.Contains (panel);
704 bool HasBeenRendered (Control control)
709 UpdatePanel panel = control as UpdatePanel;
710 if (PanelRequiresUpdate (panel))
713 return HasBeenRendered (control.Parent);
716 IEnumerable<ScriptReferenceEntry> GetScriptReferences () {
717 if (_scripts != null && _scripts.Count > 0) {
718 for (int i = 0; i < _scripts.Count; i++) {
719 yield return new ScriptReferenceEntry (this, _scripts [i], LoadScriptsBeforeUI);
723 if (_proxies != null && _proxies.Count > 0) {
724 for (int i = 0; i < _proxies.Count; i++) {
725 ScriptManagerProxy proxy = _proxies [i];
726 for (int j = 0; j < proxy.Scripts.Count; j++)
727 yield return new ScriptReferenceEntry (proxy, proxy.Scripts [j], LoadScriptsBeforeUI);
731 if (_registeredScriptControls != null && _registeredScriptControls.Count > 0) {
732 for (int i = 0; i < _registeredScriptControls.Count; i++) {
733 IEnumerable<ScriptReference> scripts = _registeredScriptControls [i].GetScriptReferences ();
735 foreach (ScriptReference s in scripts)
736 yield return new ScriptReferenceEntry ((Control) _registeredScriptControls [i], s, LoadScriptsBeforeUI);
740 if (_registeredExtenderControls != null && _registeredExtenderControls.Count > 0) {
741 foreach (IExtenderControl ex in _registeredExtenderControls.Keys) {
742 IEnumerable<ScriptReference> scripts = ex.GetScriptReferences ();
744 foreach (ScriptReference s in scripts)
745 yield return new ScriptReferenceEntry ((Control) ex, s, LoadScriptsBeforeUI);
749 protected virtual void OnResolveCompositeScriptReference (CompositeScriptReferenceEventArgs e)
751 EventHandler <CompositeScriptReferenceEventArgs> evt = ResolveCompositeScriptReference;
755 protected virtual void OnResolveScriptReference (ScriptReferenceEventArgs e) {
756 if (ResolveScriptReference != null)
757 ResolveScriptReference (this, e);
760 protected virtual void RaisePostDataChangedEvent ()
765 public static void RegisterArrayDeclaration (Page page, string arrayName, string arrayValue) {
766 RegisterArrayDeclaration ((Control) page, arrayName, arrayValue);
769 public static void RegisterArrayDeclaration (Control control, string arrayName, string arrayValue) {
770 Page page = control.Page;
771 ScriptManager sm = GetCurrentInternal (page);
776 if (sm._arrayDeclarations == null)
777 sm._arrayDeclarations = new List<RegisteredArrayDeclaration> ();
779 sm._arrayDeclarations.Add (new RegisteredArrayDeclaration (control, arrayName, arrayValue));
781 if (!sm.IsInAsyncPostBack)
782 page.ClientScript.RegisterArrayDeclaration (arrayName, arrayValue);
785 public void RegisterAsyncPostBackControl (Control control) {
789 if (_asyncPostBackControls == null)
790 _asyncPostBackControls = new List<Control> ();
792 if (_asyncPostBackControls.Contains (control))
795 _asyncPostBackControls.Add (control);
798 public static void RegisterClientScriptBlock (Page page, Type type, string key, string script, bool addScriptTags) {
799 RegisterClientScriptBlock ((Control) page, type, key, script, addScriptTags);
802 public static void RegisterClientScriptBlock (Control control, Type type, string key, string script, bool addScriptTags) {
803 Page page = control.Page;
804 ScriptManager sm = GetCurrentInternal (page);
809 RegisterScript (ref sm._clientScriptBlocks, control, type, key, script, null, addScriptTags, RegisteredScriptType.ClientScriptBlock);
811 if (!sm.IsInAsyncPostBack)
812 page.ClientScript.RegisterClientScriptBlock (type, key, script, addScriptTags);
815 public static void RegisterClientScriptInclude (Page page, Type type, string key, string url) {
816 RegisterClientScriptInclude ((Control) page, type, key, url);
819 public static void RegisterClientScriptInclude (Control control, Type type, string key, string url) {
820 Page page = control.Page;
821 ScriptManager sm = GetCurrentInternal (page);
826 RegisterScript (ref sm._clientScriptBlocks, control, type, key, null, url, false, RegisteredScriptType.ClientScriptInclude);
828 if (!sm.IsInAsyncPostBack)
829 page.ClientScript.RegisterClientScriptInclude (type, key, url);
832 public static void RegisterClientScriptResource (Page page, Type type, string resourceName) {
833 RegisterClientScriptResource ((Control) page, type, resourceName);
836 public static void RegisterClientScriptResource (Control control, Type type, string resourceName) {
837 RegisterClientScriptInclude (control, type, resourceName, ScriptResourceHandler.GetResourceUrl (type.Assembly, resourceName, true));
840 void RegisterScriptReference (Control control, ScriptReferenceBase script, bool loadScriptsBeforeUI)
842 string scriptPath = script.Path;
843 string url = String.IsNullOrEmpty (scriptPath) ? script.GetUrl (this, false) : scriptPath;
844 if (control != this && !String.IsNullOrEmpty (scriptPath))
845 url = control.ResolveClientUrl (scriptPath);
847 if (String.IsNullOrEmpty (url))
850 if (loadScriptsBeforeUI)
851 RegisterClientScriptInclude (control, typeof (ScriptManager), url, url);
853 RegisterStartupScript (control, typeof (ScriptManager), url, String.Format ("<script src=\"{0}\" type=\"text/javascript\"></script>", url), false);
856 void RegisterServiceReference (Control control, ServiceReference serviceReference)
858 if (serviceReference.InlineScript) {
859 string url = control.ResolveUrl (serviceReference.Path);
860 Type type = WebServiceParser.GetCompiledType (url, Context);
862 object[] attributes = type.GetCustomAttributes (typeof (ScriptServiceAttribute), true);
863 if (attributes.Length == 0)
864 throw new InvalidOperationException ("Only Web services with a [ScriptService] attribute on the class definition can be called from script.");
867 LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (type, url);
868 RegisterClientScriptBlock (control, typeof (ScriptManager), url, logicalTypeInfo.Proxy, true);
871 string pathInfo = "/js";
872 if (IsDebuggingEnabled)
874 string url = String.Concat (control.ResolveClientUrl (serviceReference.Path), pathInfo);
875 RegisterClientScriptInclude (control, typeof (ScriptManager), url, url);
879 public void RegisterDataItem (Control control, string dataItem) {
880 RegisterDataItem (control, dataItem, false);
883 public void RegisterDataItem (Control control, string dataItem, bool isJsonSerialized) {
884 if (!IsInAsyncPostBack)
885 throw new InvalidOperationException ("RegisterDataItem can only be called during an async postback.");
887 throw new ArgumentNullException ("control");
889 if (_dataItems == null)
890 _dataItems = new Dictionary<Control, DataItemEntry> ();
892 if (_dataItems.ContainsKey (control))
893 throw new ArgumentException (String.Format ("'{0}' already has a data item registered.", control.ID), "control");
895 _dataItems.Add (control, new DataItemEntry (dataItem, isJsonSerialized));
898 public void RegisterDispose (Control control, string disposeScript) {
900 throw new ArgumentNullException ("control");
901 if (disposeScript == null)
902 throw new ArgumentNullException ("disposeScript");
904 UpdatePanel updatePanel = GetUpdatePanel (control);
905 if (updatePanel == null)
908 if (_disposeScripts == null)
909 _disposeScripts = new List<RegisteredDisposeScript> ();
910 _disposeScripts.Add (new RegisteredDisposeScript (control, disposeScript, updatePanel));
913 static UpdatePanel GetUpdatePanel (Control control) {
917 UpdatePanel parent = control.Parent as UpdatePanel;
921 return GetUpdatePanel (control.Parent);
924 public static void RegisterExpandoAttribute (Control control, string controlId, string attributeName, string attributeValue, bool encode) {
925 Page page = control.Page;
926 ScriptManager sm = GetCurrentInternal (page);
931 if (sm._expandoAttributes == null)
932 sm._expandoAttributes = new List<RegisteredExpandoAttribute> ();
934 sm._expandoAttributes.Add (new RegisteredExpandoAttribute (control, controlId, attributeName, attributeValue, encode));
936 if (!sm.IsInAsyncPostBack)
937 page.ClientScript.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
940 public static void RegisterHiddenField (Page page, string hiddenFieldName, string hiddenFieldInitialValue) {
941 RegisterHiddenField ((Control) page, hiddenFieldName, hiddenFieldInitialValue);
944 public static void RegisterHiddenField (Control control, string hiddenFieldName, string hiddenFieldInitialValue) {
945 Page page = control.Page;
946 ScriptManager sm = GetCurrentInternal (page);
951 if (sm._hiddenFields == null)
952 sm._hiddenFields = new List<RegisteredHiddenField> ();
954 sm._hiddenFields.Add (new RegisteredHiddenField (control, hiddenFieldName, hiddenFieldInitialValue));
956 if (!sm.IsInAsyncPostBack)
957 page.ClientScript.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
960 public static void RegisterOnSubmitStatement (Page page, Type type, string key, string script) {
961 RegisterOnSubmitStatement ((Control) page, type, key, script);
964 public static void RegisterOnSubmitStatement (Control control, Type type, string key, string script) {
965 Page page = control.Page;
966 ScriptManager sm = GetCurrentInternal (page);
971 RegisterScript (ref sm._onSubmitStatements, control, type, key, script, null, false, RegisteredScriptType.OnSubmitStatement);
973 if (!sm.IsInAsyncPostBack)
974 page.ClientScript.RegisterOnSubmitStatement (type, key, script);
977 public void RegisterPostBackControl (Control control) {
981 if (_postBackControls == null)
982 _postBackControls = new List<Control> ();
984 if (_postBackControls.Contains (control))
987 _postBackControls.Add (control);
990 internal void RegisterUpdatePanel (UpdatePanel updatePanel) {
991 if (_updatePanels == null)
992 _updatePanels = new List<UpdatePanel> ();
994 if (_updatePanels.Contains (updatePanel))
997 _updatePanels.Add (updatePanel);
1000 public void RegisterScriptDescriptors (IExtenderControl extenderControl) {
1001 if (extenderControl == null)
1004 if (_registeredExtenderControls == null || !_registeredExtenderControls.ContainsKey (extenderControl))
1007 Control targetControl = _registeredExtenderControls [extenderControl];
1008 RegisterScriptDescriptors ((Control) extenderControl, extenderControl.GetScriptDescriptors (targetControl));
1011 public void RegisterScriptDescriptors (IScriptControl scriptControl) {
1012 if (scriptControl == null)
1015 if (_registeredScriptControls == null || !_registeredScriptControls.Contains (scriptControl))
1018 RegisterScriptDescriptors ((Control) scriptControl, scriptControl.GetScriptDescriptors ());
1021 void RegisterScriptDescriptors (Control control, IEnumerable<ScriptDescriptor> scriptDescriptors)
1023 if (scriptDescriptors == null)
1026 StringBuilder sb = new StringBuilder ();
1027 foreach (ScriptDescriptor scriptDescriptor in scriptDescriptors) {
1029 scriptDescriptor.FormID = Page.Form.ClientID;
1030 sb.AppendLine ("Sys.Application.getInstance($get(\"" + Page.Form.ClientID + "\")).add_init(function() {");
1033 sb.AppendLine ("Sys.Application.add_init(function() {");
1035 sb.AppendLine (scriptDescriptor.GetScript ());
1036 sb.AppendLine ("});");
1038 string script = sb.ToString ();
1039 RegisterStartupScript (control, typeof (ScriptDescriptor), script, script, true);
1042 public static void RegisterStartupScript (Page page, Type type, string key, string script, bool addScriptTags) {
1043 RegisterStartupScript ((Control) page, type, key, script, addScriptTags);
1046 public static void RegisterStartupScript (Control control, Type type, string key, string script, bool addScriptTags) {
1047 Page page = control.Page;
1048 ScriptManager sm = GetCurrentInternal (page);
1053 RegisterScript (ref sm._startupScriptBlocks, control, type, key, script, null, addScriptTags, RegisteredScriptType.ClientStartupScript);
1055 if (!sm.IsInAsyncPostBack)
1056 page.ClientScript.RegisterStartupScript (type, key, script, addScriptTags);
1059 public void RegisterScriptControl<TScriptControl> (TScriptControl scriptControl) where TScriptControl : Control, IScriptControl {
1060 if (scriptControl == null)
1061 throw new ArgumentNullException ("scriptControl");
1063 if (_registeredScriptControls == null)
1064 _registeredScriptControls = new List<IScriptControl> ();
1066 if (!_registeredScriptControls.Contains (scriptControl))
1067 _registeredScriptControls.Add (scriptControl);
1070 public void RegisterExtenderControl<TExtenderControl> (TExtenderControl extenderControl, Control targetControl) where TExtenderControl : Control, IExtenderControl {
1071 if (extenderControl == null)
1072 throw new ArgumentNullException ("extenderControl");
1073 if (targetControl == null)
1074 throw new ArgumentNullException ("targetControl");
1076 if (_registeredExtenderControls == null)
1077 _registeredExtenderControls = new Dictionary<IExtenderControl, Control> ();
1079 if (!_registeredExtenderControls.ContainsKey (extenderControl))
1080 _registeredExtenderControls.Add (extenderControl, targetControl);
1083 static void RegisterScript (ref List<RegisteredScript> scriptList, Control control, Type type, string key, string script, string url, bool addScriptTag, RegisteredScriptType scriptType) {
1084 if (scriptList == null)
1085 scriptList = new List<RegisteredScript> ();
1087 scriptList.Add (new RegisteredScript (control, type, key, script, url, addScriptTag, scriptType));
1090 protected internal override void Render (HtmlTextWriter writer) {
1091 // MSDN: This method is used by control developers to extend the ScriptManager control.
1092 // Notes to Inheritors:
1093 // When overriding this method, call the base Render(HtmlTextWriter) method
1094 // so that PageRequestManager is rendered on the page.
1095 if (SupportsPartialRendering) {
1096 writer.WriteLine ("<script type=\"text/javascript\">");
1097 writer.WriteLine ("//<![CDATA[");
1098 writer.WriteLine ("Sys.WebForms.PageRequestManager._initialize('{0}', document.getElementById('{1}'));", UniqueID, Page.Form.ClientID);
1100 writer.WriteLine ("Sys.WebForms.PageRequestManager.getInstance($get(\"{0}\"))._updateControls([{1}], [{2}], [{3}], {4});",
1102 FormatUpdatePanelIDs (_updatePanels, true),
1103 FormatListIDs (_asyncPostBackControls, true, false),
1104 FormatListIDs (_postBackControls, true, false),
1105 AsyncPostBackTimeout);
1107 writer.WriteLine ("Sys.WebForms.PageRequestManager.getInstance()._updateControls([{0}], [{1}], [{2}], {3});",
1108 FormatUpdatePanelIDs (_updatePanels, true),
1109 FormatListIDs (_asyncPostBackControls, true, false),
1110 FormatListIDs (_postBackControls, true, false),
1111 AsyncPostBackTimeout);
1112 writer.WriteLine ("//]]");
1113 writer.WriteLine ("</script>");
1115 base.Render (writer);
1118 static string FormatUpdatePanelIDs (List<UpdatePanel> list, bool useSingleQuote) {
1119 return FormatUpdatePanelIDs (list, useSingleQuote, false);
1122 static string FormatUpdatePanelIDs (List<UpdatePanel> list, bool useSingleQuote, bool useUntaggedName) {
1123 if (list == null || list.Count == 0)
1126 string quote = useSingleQuote ? "'" : String.Empty;
1128 StringBuilder sb = new StringBuilder ();
1129 foreach (UpdatePanel panel in list) {
1133 id = panel.UniqueID;
1134 sb.AppendFormat ("{0}{1}{2}{0},", quote, panel.ChildrenAsTriggers ? "t" : "f", id);
1135 if (useUntaggedName)
1136 sb.AppendFormat ("{0}{1}{0},", quote, id);
1142 return sb.ToString ();
1145 static string FormatListIDs<T> (List<T> list, bool useSingleQuote, bool skipInvisible) where T : Control
1147 if (list == null || list.Count == 0)
1150 StringBuilder sb = new StringBuilder ();
1151 for (int i = 0; i < list.Count; i++) {
1152 if (skipInvisible && !list [i].Visible)
1155 sb.AppendFormat ("{0}{1}{0},", useSingleQuote ? "'" : String.Empty, list [i].UniqueID);
1160 return sb.ToString ();
1163 public void SetFocus (Control control) {
1164 if (control == null)
1165 throw new ArgumentNullException ("control");
1167 if (IsInAsyncPostBack) {
1168 EnsureFocusClientScript ();
1169 _controlIDToFocus = control.ClientID;
1172 Page.SetFocus (control);
1175 public void SetFocus (string clientID) {
1176 if (String.IsNullOrEmpty (clientID))
1177 throw new ArgumentNullException ("control");
1179 if (IsInAsyncPostBack) {
1180 EnsureFocusClientScript ();
1181 _controlIDToFocus = clientID;
1184 Page.SetFocus (clientID);
1187 void EnsureFocusClientScript () {
1189 RegisterClientScriptResource (this, typeof (ClientScriptManager), "Focus.js");
1193 #region IPostBackDataHandler Members
1195 bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection) {
1196 return LoadPostData (postDataKey, postCollection);
1199 void IPostBackDataHandler.RaisePostDataChangedEvent () {
1200 RaisePostDataChangedEvent ();
1205 internal static void WriteCallbackException (ScriptManager current, TextWriter output, Exception ex, bool writeMessage)
1208 if (ex is HttpUnhandledException)
1209 ex = ex.InnerException;
1211 HttpException httpEx = ex as HttpException;
1212 string message = current != null ? current.AsyncPostBackErrorMessage : null;
1213 if (String.IsNullOrEmpty (message) && writeMessage) {
1214 if ((current != null && current.IsDebuggingEnabled) || (current == null && RuntimeHelpers.DebuggingEnabled))
1215 message = ex.ToString ();
1217 message = ex.Message;
1220 WriteCallbackOutput (output, error, httpEx == null ? "500" : httpEx.GetHttpCode ().ToString (), message);
1223 static internal void WriteCallbackRedirect (TextWriter output, string redirectUrl) {
1224 WriteCallbackOutput (output, pageRedirect, null, redirectUrl);
1227 void RegisterPanelForRefresh (UpdatePanel panel)
1229 if (_panelsToRefresh == null)
1230 _panelsToRefresh = new List<UpdatePanel> ();
1231 else if (_panelsToRefresh.Contains (panel))
1234 _panelsToRefresh.Add (panel);
1235 RegisterUpdatePanel (panel);
1238 internal void WriteCallbackPanel (TextWriter output, UpdatePanel panel, StringBuilder panelOutput)
1240 WriteCallbackOutput (output, updatePanel, panel.ClientID, panelOutput);
1243 internal void RegisterChildUpdatePanel (UpdatePanel updatePanel) {
1244 if (_childUpdatePanels == null)
1245 _childUpdatePanels = new List<UpdatePanel> ();
1246 _childUpdatePanels.Add (updatePanel);
1249 static void WriteCallbackOutput (TextWriter output, string type, string name, object value) {
1250 string str = value as string;
1251 StringBuilder sb = str == null ? value as StringBuilder : null;
1254 length = str.Length;
1255 else if (sb != null)
1258 //output.Write ("{0}|{1}|{2}|{3}|", value == null ? 0 : value.Length, type, name, value);
1259 output.Write (length);
1261 output.Write (type);
1263 output.Write (name);
1265 for (int i = 0; i < length; i++)
1267 output.Write (str [i]);
1269 output.Write (sb [i]);
1273 void RenderPageCallback (HtmlTextWriter output, Control container)
1275 Page page = (Page) container;
1277 // MSDN: http://msdn.microsoft.com/en-us/library/system.web.ui.updatepanel.aspx
1279 // Refreshing UpdatePanel Content
1281 // When partial-page rendering is enabled, a control can perform a postback
1282 // that updates the whole page or an asynchronous postback that updates the
1283 // content of one or more UpdatePanel controls. Whether a control causes an
1284 // asynchronous postback and updates an UpdatePanel control depends on the
1287 // * If the UpdateMode property of the UpdatePanel control is set to Always,
1288 // the UpdatePanel control's content is updated on every postback that
1289 // originates from the page. This includes asynchronous postbacks from
1290 // controls that are inside other UpdatePanel controls and postbacks from
1291 // controls that are not inside UpdatePanel controls.
1293 // * If the UpdateMode property is set to Conditional, the UpdatePanel
1294 // control's content is updated in the following circumstances:
1296 // o When you call the Update method of the UpdatePanel control
1298 // o When the UpdatePanel control is nested inside another UpdatePanel
1299 // control, and the parent panel is updated.
1300 // o When a postback is caused by a control that is defined as a
1301 // trigger by using the Triggers property of the UpdatePanel
1302 // control. In this scenario, the control explicitly triggers an
1303 // update of the panel content. The control can be either inside or
1304 // outside the UpdatePanel control that the trigger is associated
1306 // o When the ChildrenAsTriggers property is set to true and a child
1307 // control of the UpdatePanel control causes a postback. Child
1308 // controls of nested UpdatePanel controls do not cause an update to
1309 // the outer UpdatePanel control unless they are explicitly defined
1312 if (_updatePanels != null && _updatePanels.Count > 0) {
1314 foreach (UpdatePanel panel in _updatePanels) {
1315 if (panel.RequiresUpdate || (!String.IsNullOrEmpty (_panelToRefreshID) && String.Compare (_panelToRefreshID, panel.UniqueID, StringComparison.Ordinal) == 0))
1318 needsUpdate = false;
1320 panel.SetInPartialRendering (needsUpdate);
1322 RegisterPanelForRefresh (panel);
1326 page.Form.SetRenderMethodDelegate (RenderFormCallback);
1327 HtmlTextParser parser = new HtmlTextParser (output);
1328 page.Form.RenderControl (parser);
1330 Dictionary <string, string> pageHiddenFields = parser.HiddenFields;
1331 if (pageHiddenFields != null)
1332 foreach (KeyValuePair <string, string> kvp in pageHiddenFields)
1333 WriteCallbackOutput (output, hiddenField, kvp.Key, kvp.Value);
1335 WriteCallbackOutput (output, asyncPostBackControlIDs, null, FormatListIDs (_asyncPostBackControls, false, false));
1336 WriteCallbackOutput (output, postBackControlIDs, null, FormatListIDs (_postBackControls, false, false));
1337 WriteCallbackOutput (output, updatePanelIDs, null, FormatUpdatePanelIDs (_updatePanels, false, true));
1338 WriteCallbackOutput (output, childUpdatePanelIDs, null, FormatListIDs (_childUpdatePanels, false, true));
1339 WriteCallbackOutput (output, panelsToRefreshIDs, null, FormatListIDs (_panelsToRefresh, false, true));
1340 WriteCallbackOutput (output, asyncPostBackTimeout, null, AsyncPostBackTimeout.ToString ());
1342 WriteCallbackOutput (output, pageTitle, null, Page.Title);
1344 if (_dataItems != null)
1345 foreach (Control control in _dataItems.Keys) {
1346 DataItemEntry entry = _dataItems [control];
1347 WriteCallbackOutput (output, entry.IsJsonSerialized ? dataItemJson : dataItem, control.ClientID, entry.DataItem);
1350 WriteArrayDeclarations (output);
1351 WriteExpandoAttributes (output);
1352 WriteScriptBlocks (output, _clientScriptBlocks);
1353 WriteScriptBlocks (output, _startupScriptBlocks);
1354 WriteScriptBlocks (output, _onSubmitStatements);
1355 WriteHiddenFields (output);
1357 if (!String.IsNullOrEmpty (_controlIDToFocus))
1358 WriteCallbackOutput (output, focus, null, _controlIDToFocus);
1360 if (_disposeScripts != null)
1361 for (int i = 0; i < _disposeScripts.Count; i++) {
1362 RegisteredDisposeScript entry = _disposeScripts [i];
1363 if ((_panelsToRefresh != null && _panelsToRefresh.IndexOf (entry.UpdatePanel) >= 0) || (_childUpdatePanels != null && _childUpdatePanels.IndexOf (entry.UpdatePanel) >= 0))
1364 WriteCallbackOutput (output, scriptDispose, entry.UpdatePanel.ClientID, entry.Script);
1368 private void WriteExpandoAttributes (HtmlTextWriter writer) {
1369 if (_expandoAttributes != null) {
1370 for (int i = 0; i < _expandoAttributes.Count; i++) {
1371 RegisteredExpandoAttribute attr = _expandoAttributes [i];
1372 if (HasBeenRendered (attr.Control)) {
1375 StringWriter sw = new StringWriter ();
1376 Newtonsoft.Json.JavaScriptUtils.WriteEscapedJavaScriptString (attr.Value, sw);
1377 value = sw.ToString ();
1380 value = "\"" + attr.Value + "\"";
1381 WriteCallbackOutput (writer, expando, "document.getElementById('" + attr.ControlId + "')['" + attr.Name + "']", value);
1387 void WriteArrayDeclarations (HtmlTextWriter writer) {
1388 if (_arrayDeclarations != null) {
1389 for (int i = 0; i < _arrayDeclarations.Count; i++) {
1390 RegisteredArrayDeclaration array = _arrayDeclarations [i];
1391 if (Page == array.Control || HasBeenRendered (array.Control))
1392 WriteCallbackOutput (writer, arrayDeclaration, array.Name, array.Value);
1397 void WriteScriptBlocks (HtmlTextWriter output, List<RegisteredScript> scriptList) {
1398 if (scriptList == null)
1400 var registeredScripts = new Dictionary <string, RegisteredScript> ();
1404 for (int i = 0; i < scriptList.Count; i++) {
1405 RegisteredScript scriptEntry = scriptList [i];
1406 if (registeredScripts.ContainsKey (scriptEntry.Key))
1409 control = scriptEntry.Control;
1410 if (page == control || HasBeenRendered (control)) {
1411 registeredScripts.Add (scriptEntry.Key, scriptEntry);
1412 switch (scriptEntry.ScriptType) {
1413 case RegisteredScriptType.ClientScriptBlock:
1414 if (scriptEntry.AddScriptTags)
1415 WriteCallbackOutput (output, scriptBlock, scriptContentNoTags, scriptEntry.Script);
1417 WriteCallbackOutput (output, scriptBlock, scriptContentWithTags, SerializeScriptBlock (scriptEntry));
1419 case RegisteredScriptType.ClientStartupScript:
1420 if (scriptEntry.AddScriptTags)
1421 WriteCallbackOutput (output, scriptStartupBlock, scriptContentNoTags, scriptEntry.Script);
1423 WriteCallbackOutput (output, scriptStartupBlock, scriptContentWithTags, SerializeScriptBlock (scriptEntry));
1425 case RegisteredScriptType.ClientScriptInclude:
1426 WriteCallbackOutput (output, scriptBlock, scriptPath, scriptEntry.Url);
1428 case RegisteredScriptType.OnSubmitStatement:
1429 WriteCallbackOutput (output, onSubmit, null, scriptEntry.Script);
1436 void WriteHiddenFields (HtmlTextWriter output) {
1437 if (_hiddenFields == null)
1439 Hashtable registeredFields = new Hashtable ();
1440 for (int i = 0; i < _hiddenFields.Count; i++) {
1441 RegisteredHiddenField field = _hiddenFields [i];
1442 if (registeredFields.ContainsKey (field.Name))
1444 if (Page == field.Control || HasBeenRendered (field.Control)) {
1445 registeredFields.Add (field.Name, field);
1446 WriteCallbackOutput (output, hiddenField, field.Name, field.InitialValue);
1451 static string SerializeScriptBlock (RegisteredScript scriptEntry) {
1453 XmlTextReader reader = new XmlTextReader (new StringReader (scriptEntry.Script));
1454 while (reader.Read ()) {
1455 switch (reader.NodeType) {
1456 case XmlNodeType.Element:
1457 if (String.Compare ("script", reader.Name, StringComparison.OrdinalIgnoreCase) == 0) {
1458 Dictionary<string, string> dic = new Dictionary<string, string> ();
1459 while (reader.MoveToNextAttribute ()) {
1460 dic.Add (reader.Name, reader.Value);
1462 reader.MoveToContent ();
1463 dic.Add ("text", reader.ReadInnerXml ());
1464 return JavaScriptSerializer.DefaultSerializer.Serialize (dic);
1474 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.", scriptEntry.Type, scriptEntry.Key, scriptEntry.Script));
1477 void RenderFormCallback (HtmlTextWriter output, Control container)
1479 output = ((HtmlTextParser) output).ResponseOutput;
1480 HtmlForm form = (HtmlForm) container;
1481 HtmlTextWriter writer = new HtmlDropWriter (output);
1483 if (form.HasControls ()) {
1484 foreach (Control control in form.Controls)
1485 control.RenderControl (writer);
1489 internal class AlternativeHtmlTextWriter : HtmlTextWriter
1491 readonly HtmlTextWriter _responseOutput;
1493 public HtmlTextWriter ResponseOutput {
1494 get { return _responseOutput; }
1497 public AlternativeHtmlTextWriter (TextWriter writer, HtmlTextWriter responseOutput)
1499 _responseOutput = responseOutput;
1503 sealed class HtmlTextParser : AlternativeHtmlTextWriter
1507 public Dictionary <string, string> _hiddenFields;
1509 public Dictionary <string, string> HiddenFields {
1510 get { return _hiddenFields; }
1513 public HtmlTextParser (HtmlTextWriter responseOutput)
1514 : this (new TextParser (responseOutput), responseOutput) {
1517 HtmlTextParser (TextParser parser, HtmlTextWriter responseOutput)
1518 : base (parser, responseOutput)
1520 parser.HiddenFieldParsed += new TextParser.TextParserHiddenFieldParsedEventHandler (OnHiddenFieldParsed);
1523 void OnHiddenFieldParsed (TextParser sender, TextParserHiddenFieldParsedEventArgs args)
1525 if (_hiddenFields == null)
1526 _hiddenFields = new Dictionary <string, string> ();
1527 _hiddenFields [args.Name] = args.Value;
1530 public override void WriteAttribute (string name, string value) {
1531 if (!_done && String.Compare ("action", name, StringComparison.OrdinalIgnoreCase) == 0) {
1533 ScriptManager.WriteCallbackOutput (ResponseOutput, formAction, null, value);
1536 base.WriteAttribute (name, value);
1540 sealed class TextParserHiddenFieldParsedEventArgs : EventArgs
1542 public string Name {
1547 public string Value {
1552 public TextParserHiddenFieldParsedEventArgs (string name, string value)
1559 sealed class TextParser : TextWriter
1561 public delegate void TextParserHiddenFieldParsedEventHandler (TextParser sender, TextParserHiddenFieldParsedEventArgs args);
1564 char _charState = (char) 255;
1565 const char nullCharState = (char) 255;
1566 StringBuilder _sb = new StringBuilder ();
1567 Dictionary<string, string> _currentField;
1568 string _currentAttribute;
1569 readonly HtmlTextWriter _responseOutput;
1570 TextParserHiddenFieldParsedEventHandler _hiddenFieldParsedHandler;
1572 public event TextParserHiddenFieldParsedEventHandler HiddenFieldParsed {
1573 add { _hiddenFieldParsedHandler = value; }
1574 remove { _hiddenFieldParsedHandler = null; }
1577 public override Encoding Encoding {
1578 get { return Encoding.UTF8; }
1581 public TextParser (HtmlTextWriter responseOutput) {
1582 _responseOutput = responseOutput;
1585 public override void Write (char value) {
1588 ParseBeginTag (value);
1591 ParseAttributeName (value);
1594 ParseAttributeValue (value);
1599 private void ParseAttributeValue (char value) {
1605 _currentField.Add (_currentAttribute, _sb.ToString ());
1608 ProbeWriteOutput ();
1616 private void ParseAttributeName (char value) {
1625 _currentAttribute = _sb.ToString ();
1635 void ParseBeginTag (char value) {
1636 switch (_charState) {
1674 _currentField = new Dictionary<string, string> ();
1682 private void ResetState () {
1683 _charState = nullCharState;
1688 private void ProbeWriteOutput () {
1689 if (!_currentField.ContainsKey ("name"))
1691 if (!_currentField.ContainsKey ("value"))
1694 string value = _currentField ["value"];
1698 if (_hiddenFieldParsedHandler != null)
1699 _hiddenFieldParsedHandler (this, new TextParserHiddenFieldParsedEventArgs (_currentField ["name"], HttpUtility.HtmlDecode (value)));
1701 ScriptManager.WriteCallbackOutput (_responseOutput, hiddenField, _currentField ["name"], HttpUtility.HtmlDecode (value));
1705 sealed class HtmlDropWriter : AlternativeHtmlTextWriter
1707 public HtmlDropWriter (HtmlTextWriter responseOutput)
1708 : base (new DropWriter (), responseOutput) {
1712 sealed class DropWriter : TextWriter
1714 public override Encoding Encoding {
1715 get { return Encoding.UTF8; }
1719 sealed class CultureInfoSerializer
1721 readonly CultureInfo _ci;
1722 public CultureInfoSerializer (CultureInfo ci) {
1724 throw new ArgumentNullException ("ci");
1728 public string name {
1729 get { return _ci.Name; }
1732 public NumberFormatInfo numberFormat {
1733 get { return _ci.NumberFormat; }
1736 public DateTimeFormatInfo dateTimeFormat {
1737 get { return _ci.DateTimeFormat; }
1741 sealed class ScriptReferenceEntry
1743 readonly Control _control;
1744 readonly ScriptReference _scriptReference;
1745 readonly bool _loadBeforeUI;
1747 public Control Control { get { return _control; } }
1748 public ScriptReference ScriptReference { get { return _scriptReference; } }
1749 public bool LoadScriptsBeforeUI { get { return _loadBeforeUI; } }
1751 public ScriptReferenceEntry (Control control, ScriptReference scriptReference, bool loadBeforeUI) {
1753 _scriptReference = scriptReference;
1754 _loadBeforeUI = loadBeforeUI;
1758 sealed class DataItemEntry
1760 readonly string _dataItem;
1761 readonly bool _isJsonSerialized;
1763 public string DataItem { get { return _dataItem; } }
1764 public bool IsJsonSerialized { get { return _isJsonSerialized; } }
1766 public DataItemEntry (string dataItem, bool isJsonSerialized) {
1767 _dataItem = dataItem;
1768 _isJsonSerialized = isJsonSerialized;
1772 internal void RegisterProxy (ScriptManagerProxy scriptManagerProxy) {
1773 if (_proxies == null)
1774 _proxies = new List<ScriptManagerProxy> ();
1776 _proxies.Add (scriptManagerProxy);
1779 #region IScriptManager Members
1781 void IScriptManager.RegisterOnSubmitStatementExternal (Control control, Type type, string key, string script) {
1782 RegisterOnSubmitStatement (control, type, key, script);
1785 void IScriptManager.RegisterExpandoAttributeExternal (Control control, string controlId, string attributeName, string attributeValue, bool encode) {
1786 RegisterExpandoAttribute (control, controlId, attributeName, attributeValue, encode);
1789 void IScriptManager.RegisterHiddenFieldExternal (Control control, string hiddenFieldName, string hiddenFieldInitialValue) {
1790 RegisterHiddenField (control, hiddenFieldName, hiddenFieldInitialValue);
1793 void IScriptManager.RegisterStartupScriptExternal (Control control, Type type, string key, string script, bool addScriptTags) {
1794 RegisterStartupScript (control, type, key, script, addScriptTags);
1797 void IScriptManager.RegisterArrayDeclarationExternal (Control control, string arrayName, string arrayValue) {
1798 RegisterArrayDeclaration (control, arrayName, arrayValue);
1801 void IScriptManager.RegisterClientScriptBlockExternal (Control control, Type type, string key, string script, bool addScriptTags) {
1802 RegisterClientScriptBlock (control, type, key, script, addScriptTags);
1805 void IScriptManager.RegisterClientScriptIncludeExternal (Control control, Type type, string key, string url) {
1806 RegisterClientScriptInclude (control, type, key, url);
1809 void IScriptManager.RegisterClientScriptResourceExternal (Control control, Type type, string resourceName) {
1810 RegisterClientScriptResource (control, type, resourceName);