ScriptManager.cs 46 KB

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