ScriptManager.cs 44 KB

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