ScriptManager.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047
  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. namespace System.Web.UI
  44. {
  45. [ParseChildrenAttribute (true)]
  46. [DefaultPropertyAttribute ("Scripts")]
  47. [DesignerAttribute ("System.Web.UI.Design.ScriptManagerDesigner, System.Web.Extensions.Design, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")]
  48. [NonVisualControlAttribute]
  49. [PersistChildrenAttribute (false)]
  50. [AspNetHostingPermissionAttribute (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  51. [AspNetHostingPermissionAttribute (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  52. public class ScriptManager : Control, IPostBackDataHandler
  53. {
  54. // the keywords are used in fomatting async response
  55. const string updatePanel = "updatePanel";
  56. const string hiddenField = "hiddenField";
  57. const string arrayDeclaration = "arrayDeclaration";
  58. const string scriptBlock = "scriptBlock";
  59. const string expando = "expando";
  60. const string onSubmit = "onSubmit";
  61. const string asyncPostBackControlIDs = "asyncPostBackControlIDs";
  62. const string postBackControlIDs = "postBackControlIDs";
  63. const string updatePanelIDs = "updatePanelIDs";
  64. const string asyncPostBackTimeout = "asyncPostBackTimeout";
  65. const string childUpdatePanelIDs = "childUpdatePanelIDs";
  66. const string panelsToRefreshIDs = "panelsToRefreshIDs";
  67. const string formAction = "formAction";
  68. const string dataItem = "dataItem";
  69. const string dataItemJson = "dataItemJson";
  70. const string scriptDispose = "scriptDispose";
  71. const string pageRedirect = "pageRedirect";
  72. const string error = "error";
  73. const string pageTitle = "pageTitle";
  74. const string focus = "focus";
  75. const string scriptContentNoTags = "ScriptContentNoTags";
  76. const string scriptContentWithTags = "ScriptContentWithTags";
  77. const string scriptPath = "ScriptPath";
  78. int _asyncPostBackTimeout = 90;
  79. List<Control> _asyncPostBackControls;
  80. List<Control> _postBackControls;
  81. List<UpdatePanel> _updatePanels;
  82. ScriptReferenceCollection _scripts;
  83. bool _isInAsyncPostBack;
  84. string _asyncPostBackSourceElementID;
  85. ScriptMode _scriptMode = ScriptMode.Auto;
  86. bool _enableScriptGlobalization;
  87. bool _enableScriptLocalization;
  88. string _scriptPath;
  89. ScriptEntry _clientScriptBlocks;
  90. ScriptEntry _startupScriptBlocks;
  91. ScriptEntry _scriptIncludes;
  92. ScriptEntry _onSubmitStatements;
  93. List<ArrayDeclaration> _arrayDeclarations;
  94. Hashtable _hiddenFields;
  95. [DefaultValue (true)]
  96. [Category ("Behavior")]
  97. public bool AllowCustomErrorsRedirect {
  98. get {
  99. throw new NotImplementedException ();
  100. }
  101. set {
  102. throw new NotImplementedException ();
  103. }
  104. }
  105. [Category ("Behavior")]
  106. [DefaultValue ("")]
  107. public string AsyncPostBackErrorMessage {
  108. get {
  109. throw new NotImplementedException ();
  110. }
  111. set {
  112. throw new NotImplementedException ();
  113. }
  114. }
  115. [Browsable (false)]
  116. public string AsyncPostBackSourceElementID {
  117. get {
  118. if(_asyncPostBackSourceElementID==null)
  119. return String.Empty;
  120. return _asyncPostBackSourceElementID;
  121. }
  122. }
  123. [DefaultValue (90)]
  124. [Category ("Behavior")]
  125. public int AsyncPostBackTimeout {
  126. get {
  127. return _asyncPostBackTimeout;
  128. }
  129. set {
  130. _asyncPostBackTimeout = value;
  131. }
  132. }
  133. [Category ("Behavior")]
  134. [MergableProperty (false)]
  135. [DefaultValue ("")]
  136. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  137. [PersistenceMode (PersistenceMode.InnerProperty)]
  138. public AuthenticationServiceManager AuthenticationService {
  139. get {
  140. throw new NotImplementedException ();
  141. }
  142. }
  143. [Category ("Behavior")]
  144. [DefaultValue (false)]
  145. public bool EnablePageMethods {
  146. get {
  147. throw new NotImplementedException ();
  148. }
  149. set {
  150. throw new NotImplementedException ();
  151. }
  152. }
  153. [DefaultValue (true)]
  154. [Category ("Behavior")]
  155. public bool EnablePartialRendering {
  156. get {
  157. throw new NotImplementedException ();
  158. }
  159. set {
  160. throw new NotImplementedException ();
  161. }
  162. }
  163. [DefaultValue (false)]
  164. [Category ("Behavior")]
  165. public bool EnableScriptGlobalization {
  166. get {
  167. return _enableScriptGlobalization;
  168. }
  169. set {
  170. _enableScriptGlobalization = value;
  171. }
  172. }
  173. [Category ("Behavior")]
  174. [DefaultValue (false)]
  175. public bool EnableScriptLocalization {
  176. get {
  177. return _enableScriptLocalization;
  178. }
  179. set {
  180. _enableScriptLocalization = value;
  181. }
  182. }
  183. [Browsable (false)]
  184. public bool IsDebuggingEnabled {
  185. get {
  186. if (IsDeploymentRetail)
  187. return false;
  188. CompilationSection compilation = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
  189. if (!compilation.Debug && (ScriptMode == ScriptMode.Auto || ScriptMode == ScriptMode.Inherit))
  190. return false;
  191. if (ScriptMode == ScriptMode.Release)
  192. return false;
  193. return true;
  194. }
  195. }
  196. bool IsDeploymentRetail {
  197. get {
  198. DeploymentSection deployment = (DeploymentSection) WebConfigurationManager.GetSection ("system.web/deployment");
  199. return deployment.Retail;
  200. }
  201. }
  202. [Browsable (false)]
  203. public bool IsInAsyncPostBack {
  204. get {
  205. return _isInAsyncPostBack;
  206. }
  207. }
  208. [Category ("Behavior")]
  209. [DefaultValue (true)]
  210. public bool LoadScriptsBeforeUI {
  211. get {
  212. throw new NotImplementedException ();
  213. }
  214. set {
  215. throw new NotImplementedException ();
  216. }
  217. }
  218. [PersistenceMode (PersistenceMode.InnerProperty)]
  219. [DefaultValue ("")]
  220. [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
  221. [Category ("Behavior")]
  222. [MergableProperty (false)]
  223. public ProfileServiceManager ProfileService {
  224. get {
  225. throw new NotImplementedException ();
  226. }
  227. }
  228. [Category ("Behavior")]
  229. public ScriptMode ScriptMode {
  230. get {
  231. return _scriptMode;
  232. }
  233. set {
  234. if (value == ScriptMode.Inherit)
  235. value = ScriptMode.Auto;
  236. _scriptMode = value;
  237. }
  238. }
  239. [DefaultValue ("")]
  240. [Category ("Behavior")]
  241. public string ScriptPath {
  242. get {
  243. if (_scriptPath == null)
  244. return String.Empty;
  245. return _scriptPath;
  246. }
  247. set {
  248. _scriptPath = value;
  249. }
  250. }
  251. [PersistenceMode (PersistenceMode.InnerProperty)]
  252. [DefaultValue ("")]
  253. [Category ("Behavior")]
  254. [MergableProperty (false)]
  255. public ScriptReferenceCollection Scripts {
  256. get {
  257. if (_scripts == null)
  258. _scripts = new ScriptReferenceCollection ();
  259. return _scripts;
  260. }
  261. }
  262. [PersistenceMode (PersistenceMode.InnerProperty)]
  263. [DefaultValue ("")]
  264. [MergableProperty (false)]
  265. [Category ("Behavior")]
  266. public ServiceReferenceCollection Services {
  267. get {
  268. throw new NotImplementedException ();
  269. }
  270. }
  271. [DefaultValue (true)]
  272. [Browsable (false)]
  273. public bool SupportsPartialRendering {
  274. get {
  275. throw new NotImplementedException ();
  276. }
  277. set {
  278. throw new NotImplementedException ();
  279. }
  280. }
  281. [EditorBrowsable (EditorBrowsableState.Never)]
  282. [Browsable (false)]
  283. [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
  284. public override bool Visible {
  285. get {
  286. return true;
  287. }
  288. set {
  289. throw new NotImplementedException ();
  290. }
  291. }
  292. [Category ("Action")]
  293. public event EventHandler<AsyncPostBackErrorEventArgs> AsyncPostBackError;
  294. [Category ("Action")]
  295. public event EventHandler<ScriptReferenceEventArgs> ResolveScriptReference;
  296. public static ScriptManager GetCurrent (Page page)
  297. {
  298. HttpContext ctx = HttpContext.Current;
  299. if (ctx == null)
  300. return null;
  301. return (ScriptManager) ctx.Items [page];
  302. }
  303. static void SetCurrent (Page page, ScriptManager instance) {
  304. HttpContext ctx = HttpContext.Current;
  305. ctx.Items [page] = instance;
  306. }
  307. protected virtual bool LoadPostData (string postDataKey, NameValueCollection postCollection)
  308. {
  309. _isInAsyncPostBack = true;
  310. string arg = postCollection [postDataKey];
  311. if (!String.IsNullOrEmpty (arg)) {
  312. string [] args = arg.Split ('|');
  313. Control c = Page.FindControl (args [0]);
  314. UpdatePanel up = c as UpdatePanel;
  315. if (up != null && up.ChildrenAsTriggers)
  316. up.Update ();
  317. _asyncPostBackSourceElementID = args[1];
  318. }
  319. return false;
  320. }
  321. protected internal virtual void OnAsyncPostBackError (AsyncPostBackErrorEventArgs e)
  322. {
  323. if (AsyncPostBackError != null)
  324. AsyncPostBackError (this, e);
  325. }
  326. protected override void OnInit (EventArgs e)
  327. {
  328. base.OnInit (e);
  329. if (GetCurrent (Page) != null)
  330. throw new InvalidOperationException ("Only one instance of a ScriptManager can be added to the page.");
  331. SetCurrent (Page, this);
  332. }
  333. protected override void OnPreRender (EventArgs e)
  334. {
  335. base.OnPreRender (e);
  336. if (IsInAsyncPostBack) {
  337. Page.SetRenderMethodDelegate (RenderPageCallback);
  338. }
  339. else {
  340. if (EnableScriptGlobalization) {
  341. CultureInfo culture = Thread.CurrentThread.CurrentCulture;
  342. string script = null; // TODO: Json serialization of culture
  343. RegisterClientScriptBlock (this, typeof (ScriptManager), "ScriptGlobalization", script, true);
  344. }
  345. // Register Scripts
  346. foreach (ScriptReference script in GetScriptReferences ()) {
  347. OnResolveScriptReference (new ScriptReferenceEventArgs (script));
  348. RegisterScriptReference (script);
  349. }
  350. // Register startup script
  351. RegisterStartupScript (this, typeof (ScriptManager), "Sys.Application.initialize();", "Sys.Application.initialize();", true);
  352. }
  353. }
  354. IEnumerable GetScriptReferences () {
  355. ScriptReference script;
  356. script = new ScriptReference ("MicrosoftAjax.js", String.Empty);
  357. script.NotifyScriptLoaded = false;
  358. yield return script;
  359. script = new ScriptReference ("MicrosoftAjaxWebForms.js", String.Empty);
  360. script.NotifyScriptLoaded = false;
  361. yield return script;
  362. if (_scripts != null && _scripts.Count > 0) {
  363. for (int i = 0; i < _scripts.Count; i++) {
  364. yield return _scripts [i];
  365. }
  366. }
  367. }
  368. protected virtual void OnResolveScriptReference (ScriptReferenceEventArgs e)
  369. {
  370. if (ResolveScriptReference != null)
  371. ResolveScriptReference (this, e);
  372. }
  373. protected virtual void RaisePostDataChangedEvent ()
  374. {
  375. throw new NotImplementedException ();
  376. }
  377. public static void RegisterArrayDeclaration (Control control, string arrayName, string arrayValue)
  378. {
  379. RegisterArrayDeclaration (control.Page, arrayName, arrayValue);
  380. }
  381. public static void RegisterArrayDeclaration (Page page, string arrayName, string arrayValue)
  382. {
  383. ScriptManager sm = GetCurrent (page);
  384. if (sm.IsInAsyncPostBack)
  385. sm.RegisterArrayDeclaration (arrayName, arrayValue);
  386. else
  387. page.ClientScript.RegisterArrayDeclaration (arrayName, arrayValue);
  388. }
  389. void RegisterArrayDeclaration (string arrayName, string arrayValue) {
  390. if (_arrayDeclarations == null)
  391. _arrayDeclarations = new List<ArrayDeclaration> ();
  392. _arrayDeclarations.Add(new ArrayDeclaration(arrayName, arrayValue));
  393. }
  394. public void RegisterAsyncPostBackControl (Control control)
  395. {
  396. if(control==null)
  397. return;
  398. if (_asyncPostBackControls == null)
  399. _asyncPostBackControls = new List<Control> ();
  400. if (_asyncPostBackControls.Contains (control))
  401. return;
  402. _asyncPostBackControls.Add (control);
  403. }
  404. public static void RegisterClientScriptBlock (Control control, Type type, string key, string script, bool addScriptTags)
  405. {
  406. RegisterClientScriptBlock (control.Page, type, key, script, addScriptTags);
  407. }
  408. public static void RegisterClientScriptBlock (Page page, Type type, string key, string script, bool addScriptTags)
  409. {
  410. ScriptManager sm = GetCurrent (page);
  411. if (sm.IsInAsyncPostBack)
  412. RegisterScript (ref sm._clientScriptBlocks, type, key, script, addScriptTags ? ScriptEntryType.ScriptContentNoTags : ScriptEntryType.ScriptContentWithTags);
  413. else
  414. page.ClientScript.RegisterClientScriptBlock (type, key, script, addScriptTags);
  415. }
  416. public static void RegisterClientScriptInclude (Control control, Type type, string key, string url)
  417. {
  418. RegisterClientScriptInclude (control.Page, type, key, url);
  419. }
  420. public static void RegisterClientScriptInclude (Page page, Type type, string key, string url)
  421. {
  422. ScriptManager sm = GetCurrent (page);
  423. if (sm.IsInAsyncPostBack)
  424. RegisterScript (ref sm._scriptIncludes, type, key, url, ScriptEntryType.ScriptPath);
  425. else
  426. page.ClientScript.RegisterClientScriptInclude (type, key, url);
  427. }
  428. public static void RegisterClientScriptResource (Control control, Type type, string resourceName)
  429. {
  430. RegisterClientScriptResource (control.Page, type, resourceName);
  431. }
  432. public static void RegisterClientScriptResource (Page page, Type type, string resourceName)
  433. {
  434. RegisterClientScriptInclude (page, type, "resource-" + resourceName, ScriptResourceHandler.GetResourceUrl (type, resourceName));
  435. }
  436. void RegisterScriptReference (ScriptReference script) {
  437. bool isDebugMode = IsDeploymentRetail ? false : (script.ScriptModeInternal == ScriptMode.Inherit ? IsDebuggingEnabled : (script.ScriptModeInternal == ScriptMode.Debug));
  438. string url;
  439. if (!String.IsNullOrEmpty (script.Path)) {
  440. url = GetScriptName (ResolveClientUrl (script.Path), isDebugMode, EnableScriptLocalization ? script.ResourceUICultures : null);
  441. }
  442. else if (!String.IsNullOrEmpty (script.Name)) {
  443. Assembly assembly;
  444. if (String.IsNullOrEmpty (script.Assembly))
  445. assembly = typeof (ScriptManager).Assembly;
  446. else
  447. assembly = Assembly.Load (script.Assembly);
  448. string name = GetScriptName (script.Name, isDebugMode, null);
  449. if (script.IgnoreScriptPath || String.IsNullOrEmpty (ScriptPath))
  450. url = ScriptResourceHandler.GetResourceUrl (assembly, name, script.NotifyScriptLoaded);
  451. else {
  452. AssemblyName an = assembly.GetName ();
  453. url = ResolveClientUrl (String.Concat (VirtualPathUtility.AppendTrailingSlash (ScriptPath), an.Name, '/', an.Version, '/', name));
  454. }
  455. }
  456. else {
  457. throw new InvalidOperationException ("Name and Path cannot both be empty.");
  458. }
  459. RegisterClientScriptInclude (this, typeof (ScriptManager), url, url);
  460. }
  461. static string GetScriptName (string releaseName, bool isDebugMode, string [] supportedUICultures) {
  462. if (!isDebugMode && (supportedUICultures == null || supportedUICultures.Length == 0))
  463. return releaseName;
  464. if (releaseName.Length < 3 || !releaseName.EndsWith (".js", StringComparison.OrdinalIgnoreCase))
  465. throw new InvalidOperationException (String.Format ("'{0}' is not a valid script path. The path must end in '.js'.", releaseName));
  466. StringBuilder sb = new StringBuilder (releaseName);
  467. sb.Length -= 3;
  468. if (isDebugMode)
  469. sb.Append (".debug");
  470. string culture=Thread.CurrentThread.CurrentUICulture.Name;
  471. if (supportedUICultures != null && Array.IndexOf<string> (supportedUICultures, culture) >= 0)
  472. sb.AppendFormat (".{0}", culture);
  473. sb.Append (".js");
  474. return sb.ToString ();
  475. }
  476. public void RegisterDataItem (Control control, string dataItem)
  477. {
  478. throw new NotImplementedException ();
  479. }
  480. public void RegisterDataItem (Control control, string dataItem, bool isJsonSerialized)
  481. {
  482. throw new NotImplementedException ();
  483. }
  484. public void RegisterDispose (Control control, string disposeScript)
  485. {
  486. throw new NotImplementedException ();
  487. }
  488. public static void RegisterExpandoAttribute (Control control, string controlId, string attributeName, string attributeValue, bool encode)
  489. {
  490. Page page = control.Page;
  491. ScriptManager sm = GetCurrent (page);
  492. if (sm.IsInAsyncPostBack)
  493. sm.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
  494. else
  495. page.ClientScript.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
  496. }
  497. private void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue, bool encode) {
  498. // seems MS do nothing.
  499. }
  500. public static void RegisterHiddenField (Control control, string hiddenFieldName, string hiddenFieldInitialValue)
  501. {
  502. RegisterHiddenField (control.Page, hiddenFieldName, hiddenFieldInitialValue);
  503. }
  504. public static void RegisterHiddenField (Page page, string hiddenFieldName, string hiddenFieldInitialValue)
  505. {
  506. ScriptManager sm = GetCurrent (page);
  507. if (sm.IsInAsyncPostBack)
  508. sm.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  509. else
  510. page.ClientScript.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  511. }
  512. void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue) {
  513. if (_hiddenFields == null)
  514. _hiddenFields = new Hashtable ();
  515. if (!_hiddenFields.ContainsKey (hiddenFieldName))
  516. _hiddenFields.Add (hiddenFieldName, hiddenFieldInitialValue);
  517. }
  518. public static void RegisterOnSubmitStatement (Control control, Type type, string key, string script)
  519. {
  520. RegisterOnSubmitStatement (control.Page, type, key, script);
  521. }
  522. public static void RegisterOnSubmitStatement (Page page, Type type, string key, string script)
  523. {
  524. ScriptManager sm = GetCurrent (page);
  525. if (sm.IsInAsyncPostBack)
  526. RegisterScript (ref sm._onSubmitStatements, type, key, script, ScriptEntryType.OnSubmit);
  527. else
  528. page.ClientScript.RegisterOnSubmitStatement (type, key, script);
  529. }
  530. public void RegisterPostBackControl (Control control)
  531. {
  532. if (control == null)
  533. return;
  534. if (_postBackControls == null)
  535. _postBackControls = new List<Control> ();
  536. if (_postBackControls.Contains (control))
  537. return;
  538. _postBackControls.Add (control);
  539. }
  540. internal void RegisterUpdatePanel (UpdatePanel updatePanel) {
  541. if (_updatePanels == null)
  542. _updatePanels = new List<UpdatePanel> ();
  543. if (_updatePanels.Contains (updatePanel))
  544. return;
  545. _updatePanels.Add (updatePanel);
  546. }
  547. public void RegisterScriptDescriptors (IExtenderControl extenderControl)
  548. {
  549. throw new NotImplementedException ();
  550. }
  551. public void RegisterScriptDescriptors (IScriptControl scriptControl)
  552. {
  553. throw new NotImplementedException ();
  554. }
  555. public static void RegisterStartupScript (Control control, Type type, string key, string script, bool addScriptTags)
  556. {
  557. RegisterStartupScript (control.Page, type, key, script, addScriptTags);
  558. }
  559. public static void RegisterStartupScript (Page page, Type type, string key, string script, bool addScriptTags)
  560. {
  561. ScriptManager sm = GetCurrent (page);
  562. if (sm.IsInAsyncPostBack)
  563. RegisterScript (ref sm._startupScriptBlocks, type, key, script, addScriptTags ? ScriptEntryType.ScriptContentNoTags : ScriptEntryType.ScriptContentWithTags);
  564. else
  565. page.ClientScript.RegisterStartupScript (type, key, script, addScriptTags);
  566. }
  567. static void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, ScriptEntryType scriptEntryType) {
  568. ScriptEntry last = null;
  569. ScriptEntry entry = scriptList;
  570. while (entry != null) {
  571. if (entry.Type == type && entry.Key == key)
  572. return;
  573. last = entry;
  574. entry = entry.Next;
  575. }
  576. entry = new ScriptEntry (type, key, script, scriptEntryType);
  577. if (last != null)
  578. last.Next = entry;
  579. else
  580. scriptList = entry;
  581. }
  582. protected override void Render (HtmlTextWriter writer)
  583. {
  584. // MSDN: This method is used by control developers to extend the ScriptManager control.
  585. // Notes to Inheritors:
  586. // When overriding this method, call the base Render(HtmlTextWriter) method
  587. // so that PageRequestManager is rendered on the page.
  588. writer.WriteLine ("<script type=\"text/javascript\">");
  589. writer.WriteLine ("//<![CDATA[");
  590. writer.WriteLine ("Sys.WebForms.PageRequestManager._initialize('{0}', document.getElementById('{1}'));", UniqueID, Page.Form.ClientID);
  591. writer.WriteLine ("Sys.WebForms.PageRequestManager.getInstance()._updateControls([{0}], [{1}], [{2}], {3});", FormatUpdatePanelIDs (_updatePanels, true), FormatListIDs (_asyncPostBackControls, true), FormatListIDs (_postBackControls, true), AsyncPostBackTimeout);
  592. writer.WriteLine ("//]]");
  593. writer.WriteLine ("</script>");
  594. base.Render (writer);
  595. }
  596. static string FormatUpdatePanelIDs (List<UpdatePanel> list, bool useSingleQuote) {
  597. if (list == null || list.Count == 0)
  598. return null;
  599. StringBuilder sb = new StringBuilder ();
  600. for (int i = 0; i < list.Count; i++) {
  601. sb.AppendFormat ("{0}{1}{2}{0},", useSingleQuote ? "'" : String.Empty, list [i].ChildrenAsTriggers ? "t" : "f", list [i].UniqueID);
  602. }
  603. if (sb.Length > 0)
  604. sb.Length--;
  605. return sb.ToString ();
  606. }
  607. static string FormatListIDs (List<Control> list, bool useSingleQuote)
  608. {
  609. if (list == null || list.Count == 0)
  610. return null;
  611. StringBuilder sb = new StringBuilder ();
  612. for (int i = 0; i < list.Count; i++) {
  613. sb.AppendFormat ("{0}{1}{0},", useSingleQuote ? "'" : String.Empty, list [i].UniqueID);
  614. }
  615. if (sb.Length > 0)
  616. sb.Length--;
  617. return sb.ToString ();
  618. }
  619. public void SetFocus (Control control)
  620. {
  621. throw new NotImplementedException ();
  622. }
  623. public void SetFocus (string clientID)
  624. {
  625. throw new NotImplementedException ();
  626. }
  627. #region IPostBackDataHandler Members
  628. bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection)
  629. {
  630. return LoadPostData (postDataKey, postCollection);
  631. }
  632. void IPostBackDataHandler.RaisePostDataChangedEvent ()
  633. {
  634. RaisePostDataChangedEvent ();
  635. }
  636. #endregion
  637. static internal void WriteCallbackException (TextWriter output, Exception ex) {
  638. HttpException httpEx = ex as HttpException;
  639. WriteCallbackOutput (output, error, httpEx == null ? "500" : httpEx.GetHttpCode ().ToString (), ex.GetBaseException ().Message);
  640. }
  641. static internal void WriteCallbackRedirect (TextWriter output, string redirectUrl) {
  642. WriteCallbackOutput (output, pageRedirect, null, redirectUrl);
  643. }
  644. static void WriteCallbackOutput (TextWriter output, string type, string name, string value) {
  645. output.Write ("{0}|{1}|{2}|{3}|", value == null ? 0 : value.Length, type, name, value);
  646. }
  647. void RenderPageCallback (HtmlTextWriter output, Control container) {
  648. Page page = (Page) container;
  649. page.Form.SetRenderMethodDelegate (RenderFormCallback);
  650. HtmlTextParser parser = new HtmlTextParser (output);
  651. page.Form.RenderControl (parser);
  652. parser.WriteOutput (output);
  653. WriteCallbackOutput (output, asyncPostBackControlIDs, null, FormatListIDs (_asyncPostBackControls, false));
  654. WriteCallbackOutput (output, postBackControlIDs, null, FormatListIDs (_postBackControls, false));
  655. WriteCallbackOutput (output, updatePanelIDs, null, FormatUpdatePanelIDs (_updatePanels, false));
  656. WriteCallbackOutput (output, asyncPostBackTimeout, null, AsyncPostBackTimeout.ToString ());
  657. WriteCallbackOutput (output, pageTitle, null, Page.Title);
  658. WriteArrayDeclarations (output);
  659. WriteScriptBlocks (output, _clientScriptBlocks);
  660. WriteScriptBlocks (output, _scriptIncludes);
  661. WriteScriptBlocks (output, _startupScriptBlocks);
  662. WriteScriptBlocks (output, _onSubmitStatements);
  663. WriteHiddenFields (output);
  664. }
  665. void WriteArrayDeclarations (HtmlTextWriter writer) {
  666. if (_arrayDeclarations != null) {
  667. for (int i = 0; i < _arrayDeclarations.Count; i++) {
  668. ArrayDeclaration array = _arrayDeclarations [i];
  669. WriteCallbackOutput (writer, arrayDeclaration, array.ArrayName, array.ArrayValue);
  670. }
  671. }
  672. }
  673. void WriteScriptBlocks (HtmlTextWriter output, ScriptEntry scriptList) {
  674. while (scriptList != null) {
  675. switch (scriptList.ScriptEntryType) {
  676. case ScriptEntryType.ScriptContentNoTags:
  677. WriteCallbackOutput (output, scriptBlock, scriptContentNoTags, scriptList.Script);
  678. break;
  679. case ScriptEntryType.ScriptContentWithTags:
  680. string script = SerializeScriptBlock (scriptList);
  681. WriteCallbackOutput (output, scriptBlock, scriptContentWithTags, script);
  682. break;
  683. case ScriptEntryType.ScriptPath:
  684. WriteCallbackOutput (output, scriptBlock, scriptPath, scriptList.Script);
  685. break;
  686. case ScriptEntryType.OnSubmit:
  687. WriteCallbackOutput (output, onSubmit, null, scriptList.Script);
  688. break;
  689. }
  690. scriptList = scriptList.Next;
  691. }
  692. }
  693. void WriteHiddenFields (HtmlTextWriter output) {
  694. if (_hiddenFields == null)
  695. return;
  696. foreach (string key in _hiddenFields.Keys) {
  697. string value = _hiddenFields [key] as string;
  698. WriteCallbackOutput (output, hiddenField, key, value);
  699. }
  700. }
  701. [MonoTODO()]
  702. static string SerializeScriptBlock (ScriptEntry scriptList) {
  703. 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));
  704. }
  705. void RenderFormCallback (HtmlTextWriter output, Control container) {
  706. output = ((HtmlTextParser) output).ResponseOutput;
  707. if (_updatePanels != null && _updatePanels.Count > 0) {
  708. StringBuilder sb = new StringBuilder ();
  709. HtmlTextWriter w = new HtmlTextWriter (new StringWriter (sb));
  710. for (int i = 0; i < _updatePanels.Count; i++) {
  711. UpdatePanel panel = _updatePanels [i];
  712. if (panel.Visible) {
  713. panel.RenderChildrenInternal (w);
  714. w.Flush ();
  715. if (panel.RequiresUpdate) {
  716. string panelOutput = sb.ToString ();
  717. WriteCallbackOutput (output, updatePanel, panel.ClientID, panelOutput);
  718. }
  719. sb.Length = 0;
  720. }
  721. }
  722. }
  723. HtmlForm form = (HtmlForm) container;
  724. HtmlTextWriter writer = new HtmlTextWriter (new DropWriter ());
  725. if (form.HasControls ()) {
  726. for (int i = 0; i < form.Controls.Count; i++) {
  727. form.Controls [i].RenderControl (writer);
  728. }
  729. }
  730. }
  731. sealed class HtmlTextParser : HtmlTextWriter
  732. {
  733. readonly HtmlTextWriter _responseOutput;
  734. public HtmlTextWriter ResponseOutput {
  735. get { return _responseOutput; }
  736. }
  737. public HtmlTextParser (HtmlTextWriter responseOutput)
  738. : base (new TextParser ()) {
  739. _responseOutput = responseOutput;
  740. }
  741. public void WriteOutput (HtmlTextWriter output) {
  742. ((TextParser) InnerWriter).WriteOutput (output);
  743. }
  744. }
  745. sealed class TextParser : TextWriter
  746. {
  747. int _state;
  748. char _charState = (char) 255;
  749. const char nullCharState = (char) 255;
  750. StringBuilder _sb = new StringBuilder ();
  751. List<Hashtable> _hiddenFields;
  752. Hashtable _currentField;
  753. string _currentAttribute;
  754. public override Encoding Encoding {
  755. get { return Encoding.UTF8; }
  756. }
  757. public override void Write (char value) {
  758. switch (_state) {
  759. case 0:
  760. ParseBeginTag (value);
  761. break;
  762. case 1:
  763. ParseAttributeName (value);
  764. break;
  765. case 2:
  766. ParseAttributeValue (value);
  767. break;
  768. }
  769. }
  770. private void ParseAttributeValue (char value) {
  771. switch (value) {
  772. case '>':
  773. ResetState ();
  774. break;
  775. case '"':
  776. _currentField [_currentAttribute] = _sb.ToString ();
  777. _state = 1;
  778. _sb.Length = 0;
  779. break;
  780. default:
  781. _sb.Append (value);
  782. break;
  783. }
  784. }
  785. private void ParseAttributeName (char value) {
  786. switch (value) {
  787. case '>':
  788. ResetState ();
  789. break;
  790. case ' ':
  791. case '=':
  792. break;
  793. case '"':
  794. _currentAttribute = _sb.ToString ();
  795. _state = 2;
  796. _sb.Length = 0;
  797. break;
  798. default:
  799. _sb.Append (value);
  800. break;
  801. }
  802. }
  803. void ParseBeginTag (char value) {
  804. switch (_charState) {
  805. case nullCharState:
  806. if (value == '<')
  807. _charState = value;
  808. break;
  809. case '<':
  810. if (value == 'i')
  811. _charState = value;
  812. else
  813. ResetState ();
  814. break;
  815. case 'i':
  816. if (value == 'n')
  817. _charState = value;
  818. else
  819. ResetState ();
  820. break;
  821. case 'n':
  822. if (value == 'p')
  823. _charState = value;
  824. else
  825. ResetState ();
  826. break;
  827. case 'p':
  828. if (value == 'u')
  829. _charState = value;
  830. else
  831. ResetState ();
  832. break;
  833. case 'u':
  834. if (value == 't')
  835. _charState = value;
  836. else
  837. ResetState ();
  838. break;
  839. case 't':
  840. if (value == ' ') {
  841. _state = 1;
  842. _currentField = new Hashtable ();
  843. if (_hiddenFields == null)
  844. _hiddenFields = new List<Hashtable> ();
  845. _hiddenFields.Add (_currentField);
  846. }
  847. else
  848. ResetState ();
  849. break;
  850. }
  851. }
  852. private void ResetState () {
  853. _charState = nullCharState;
  854. _state = 0;
  855. _sb.Length = 0;
  856. }
  857. public void WriteOutput (HtmlTextWriter output) {
  858. if (_hiddenFields == null)
  859. return;
  860. for (int i = 0; i < _hiddenFields.Count; i++) {
  861. Hashtable field = _hiddenFields [i];
  862. string value = (string) field ["value"];
  863. if (String.IsNullOrEmpty (value))
  864. continue;
  865. ScriptManager.WriteCallbackOutput (output, ScriptManager.hiddenField, (string) field ["name"], value);
  866. }
  867. }
  868. }
  869. sealed class DropWriter : TextWriter
  870. {
  871. public override Encoding Encoding {
  872. get { return Encoding.UTF8; }
  873. }
  874. }
  875. sealed class ScriptEntry
  876. {
  877. readonly public Type Type;
  878. readonly public string Key;
  879. readonly public string Script;
  880. readonly public ScriptEntryType ScriptEntryType;
  881. public ScriptEntry Next;
  882. public ScriptEntry (Type type, string key, string script, ScriptEntryType scriptEntryType) {
  883. Key = key;
  884. Type = type;
  885. Script = script;
  886. ScriptEntryType = scriptEntryType;
  887. }
  888. }
  889. enum ScriptEntryType
  890. {
  891. ScriptContentNoTags,
  892. ScriptContentWithTags,
  893. ScriptPath,
  894. OnSubmit
  895. }
  896. sealed class ArrayDeclaration
  897. {
  898. readonly public string ArrayName;
  899. readonly public string ArrayValue;
  900. public ArrayDeclaration (string arrayName, string arrayValue) {
  901. ArrayName = arrayName;
  902. ArrayValue = arrayValue;
  903. }
  904. }
  905. }
  906. }