ScriptManager.cs 52 KB

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