ScriptManager.cs 54 KB

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