ScriptManager.cs 52 KB

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