ScriptManager.cs 46 KB

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