2
0

ScriptManager.cs 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491
  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. if (IsMultiForm)
  413. sb.Append ("Sys.WebForms.PageRequestManager.getInstance($get(\"" + Page.Form.ClientID + "\"))._registerDisposeScript(\"");
  414. else
  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. ScriptReference ajaxScript = new ScriptReference ("MicrosoftAjax.js", String.Empty);
  434. ajaxScript.NotifyScriptLoaded = false;
  435. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxScript));
  436. ScriptReference ajaxWebFormsScript = new ScriptReference ("MicrosoftAjaxWebForms.js", String.Empty);
  437. ajaxWebFormsScript.NotifyScriptLoaded = false;
  438. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxWebFormsScript));
  439. ScriptReference ajaxExtensionScript = null;
  440. ScriptReference ajaxWebFormsExtensionScript = null;
  441. if (IsMultiForm) {
  442. ajaxExtensionScript = new ScriptReference ("MicrosoftAjaxExtension.js", String.Empty);
  443. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxExtensionScript));
  444. ajaxWebFormsExtensionScript = new ScriptReference ("MicrosoftAjaxWebFormsExtension.js", String.Empty);
  445. OnResolveScriptReference (new ScriptReferenceEventArgs (ajaxWebFormsExtensionScript));
  446. }
  447. foreach (ScriptReferenceEntry script in GetScriptReferences ()) {
  448. OnResolveScriptReference (new ScriptReferenceEventArgs (script.ScriptReference));
  449. if (!IsInAsyncPostBack || (script.Control != this && HasBeenRendered (script.Control))) {
  450. if (_scriptToRegister == null)
  451. _scriptToRegister = new List<ScriptReferenceEntry> ();
  452. _scriptToRegister.Add (script);
  453. }
  454. }
  455. if (!IsInAsyncPostBack) {
  456. // Register Ajax framework script.
  457. RegisterScriptReference (ajaxScript, true);
  458. if (IsMultiForm) {
  459. RegisterScriptReference (ajaxExtensionScript, true);
  460. RegisterClientScriptBlock (this, typeof (ScriptManager), "Sys.Application", "\nSys.Application._initialize(document.getElementById('" + Page.Form.ClientID + "'));\n", true);
  461. }
  462. StringBuilder sb = new StringBuilder ();
  463. sb.AppendLine ("if (typeof(Sys) === 'undefined') throw new Error('ASP.NET Ajax client-side framework failed to load.');");
  464. ScriptingProfileServiceSection profileService = (ScriptingProfileServiceSection) WebConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/profileService");
  465. if (profileService.Enabled)
  466. sb.AppendLine ("Sys.Services._ProfileService.DefaultWebServicePath = '" + ResolveClientUrl ("~" + System.Web.Script.Services.ProfileService.DefaultWebServicePath) + "';");
  467. if (_profileService != null && !String.IsNullOrEmpty (_profileService.Path))
  468. sb.AppendLine ("Sys.Services.ProfileService.set_path('" + ResolveUrl (_profileService.Path) + "');");
  469. ScriptingAuthenticationServiceSection authenticationService = (ScriptingAuthenticationServiceSection) WebConfigurationManager.GetSection ("system.web.extensions/scripting/webServices/authenticationService");
  470. if (authenticationService.Enabled)
  471. sb.AppendLine ("Sys.Services._AuthenticationService.DefaultWebServicePath = '" + ResolveClientUrl ("~/Authentication_JSON_AppService.axd") + "';");
  472. if (_authenticationService != null && !String.IsNullOrEmpty (_authenticationService.Path))
  473. sb.AppendLine ("Sys.Services.AuthenticationService.set_path('" + ResolveUrl (_authenticationService.Path) + "');");
  474. RegisterClientScriptBlock (this, typeof (ScriptManager), "Framework", sb.ToString (), true);
  475. RegisterScriptReference (ajaxWebFormsScript, true);
  476. if (IsMultiForm)
  477. RegisterScriptReference (ajaxWebFormsExtensionScript, true);
  478. }
  479. // Register Scripts
  480. if (_scriptToRegister != null)
  481. for (int i = 0; i < _scriptToRegister.Count; i++)
  482. RegisterScriptReference (_scriptToRegister [i].ScriptReference, _scriptToRegister [i].LoadScriptsBeforeUI);
  483. if (!IsInAsyncPostBack) {
  484. // Register services
  485. if (_services != null && _services.Count > 0) {
  486. for (int i = 0; i < _services.Count; i++) {
  487. RegisterServiceReference (_services [i]);
  488. }
  489. }
  490. if (EnablePageMethods) {
  491. LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (Page.GetType (), Page.Request.FilePath);
  492. RegisterClientScriptBlock (this, typeof (ScriptManager), "PageMethods", logicalTypeInfo.Proxy, true);
  493. }
  494. // Register startup script
  495. if (IsMultiForm)
  496. RegisterStartupScript (this, typeof (ExtenderControl), "Sys.Application.initialize();", "Sys.Application.getInstance($get(\"" + Page.Form.ClientID + "\")).initialize();\n", true);
  497. else
  498. RegisterStartupScript (this, typeof (ExtenderControl), "Sys.Application.initialize();", "Sys.Application.initialize();\n", true);
  499. }
  500. }
  501. #if TARGET_J2EE
  502. bool IsMultiForm {
  503. get {
  504. Mainsoft.Web.Configuration.PagesSection pageSection = (Mainsoft.Web.Configuration.PagesSection) WebConfigurationManager.GetSection ("mainsoft.web/pages");
  505. if (pageSection != null)
  506. return pageSection.MultiForm;
  507. return false;
  508. }
  509. }
  510. #else
  511. bool IsMultiForm {
  512. get { return false; }
  513. }
  514. #endif
  515. static bool HasBeenRendered (Control control) {
  516. if (control == null)
  517. return false;
  518. UpdatePanel parent = control.Parent as UpdatePanel;
  519. if (parent != null && parent.RequiresUpdate)
  520. return true;
  521. return HasBeenRendered (control.Parent);
  522. }
  523. IEnumerable<ScriptReferenceEntry> GetScriptReferences () {
  524. if (_scripts != null && _scripts.Count > 0) {
  525. for (int i = 0; i < _scripts.Count; i++) {
  526. yield return new ScriptReferenceEntry (this, _scripts [i], LoadScriptsBeforeUI);
  527. }
  528. }
  529. if (_registeredScriptControls != null && _registeredScriptControls.Count > 0) {
  530. for (int i = 0; i < _registeredScriptControls.Count; i++) {
  531. IEnumerable<ScriptReference> scripts = _registeredScriptControls [i].GetScriptReferences ();
  532. if (scripts != null)
  533. foreach (ScriptReference s in scripts)
  534. yield return new ScriptReferenceEntry ((Control) _registeredScriptControls [i], s, LoadScriptsBeforeUI);
  535. }
  536. }
  537. if (_registeredExtenderControls != null && _registeredExtenderControls.Count > 0) {
  538. foreach (IExtenderControl ex in _registeredExtenderControls.Keys) {
  539. IEnumerable<ScriptReference> scripts = ex.GetScriptReferences ();
  540. if (scripts != null)
  541. foreach (ScriptReference s in scripts)
  542. yield return new ScriptReferenceEntry ((Control) ex, s, LoadScriptsBeforeUI);
  543. }
  544. }
  545. }
  546. protected virtual void OnResolveScriptReference (ScriptReferenceEventArgs e) {
  547. if (ResolveScriptReference != null)
  548. ResolveScriptReference (this, e);
  549. }
  550. protected virtual void RaisePostDataChangedEvent () {
  551. UpdatePanel up = Page.FindControl (_panelToRefreshID) as UpdatePanel;
  552. if (up != null && up.ChildrenAsTriggers)
  553. up.Update ();
  554. }
  555. public static void RegisterArrayDeclaration (Control control, string arrayName, string arrayValue) {
  556. RegisterArrayDeclaration (control.Page, arrayName, arrayValue);
  557. }
  558. public static void RegisterArrayDeclaration (Page page, string arrayName, string arrayValue) {
  559. ScriptManager sm = GetCurrent (page);
  560. if (sm.IsInAsyncPostBack)
  561. sm.RegisterArrayDeclaration (arrayName, arrayValue);
  562. else
  563. page.ClientScript.RegisterArrayDeclaration (arrayName, arrayValue);
  564. }
  565. void RegisterArrayDeclaration (string arrayName, string arrayValue) {
  566. if (_arrayDeclarations == null)
  567. _arrayDeclarations = new List<ArrayDeclaration> ();
  568. _arrayDeclarations.Add (new ArrayDeclaration (arrayName, arrayValue));
  569. }
  570. public void RegisterAsyncPostBackControl (Control control) {
  571. if (control == null)
  572. return;
  573. if (_asyncPostBackControls == null)
  574. _asyncPostBackControls = new List<Control> ();
  575. if (_asyncPostBackControls.Contains (control))
  576. return;
  577. _asyncPostBackControls.Add (control);
  578. }
  579. public static void RegisterClientScriptBlock (Control control, Type type, string key, string script, bool addScriptTags) {
  580. RegisterClientScriptBlock (control.Page, type, key, script, addScriptTags);
  581. }
  582. public static void RegisterClientScriptBlock (Page page, Type type, string key, string script, bool addScriptTags) {
  583. ScriptManager sm = GetCurrent (page);
  584. if (sm.IsInAsyncPostBack)
  585. RegisterScript (ref sm._clientScriptBlocks, type, key, script, addScriptTags ? ScriptEntryType.ScriptContentNoTags : ScriptEntryType.ScriptContentWithTags);
  586. else
  587. page.ClientScript.RegisterClientScriptBlock (type, key, script, addScriptTags);
  588. }
  589. public static void RegisterClientScriptInclude (Control control, Type type, string key, string url) {
  590. RegisterClientScriptInclude (control.Page, type, key, url);
  591. }
  592. public static void RegisterClientScriptInclude (Page page, Type type, string key, string url) {
  593. ScriptManager sm = GetCurrent (page);
  594. if (sm.IsInAsyncPostBack)
  595. RegisterScript (ref sm._scriptIncludes, type, key, url, ScriptEntryType.ScriptPath);
  596. else
  597. page.ClientScript.RegisterClientScriptInclude (type, key, url);
  598. }
  599. public static void RegisterClientScriptResource (Control control, Type type, string resourceName) {
  600. RegisterClientScriptResource (control.Page, type, resourceName);
  601. }
  602. public static void RegisterClientScriptResource (Page page, Type type, string resourceName) {
  603. RegisterClientScriptInclude (page, type, "resource-" + resourceName, ScriptResourceHandler.GetResourceUrl (type.Assembly, resourceName, true));
  604. }
  605. void RegisterScriptReference (ScriptReference script, bool loadScriptsBeforeUI) {
  606. bool isDebugMode = IsDeploymentRetail ? false : (script.ScriptModeInternal == ScriptMode.Inherit ? IsDebuggingEnabled : (script.ScriptModeInternal == ScriptMode.Debug));
  607. string url;
  608. if (!String.IsNullOrEmpty (script.Path)) {
  609. url = GetScriptName (ResolveClientUrl (script.Path), isDebugMode, EnableScriptLocalization ? script.ResourceUICultures : null);
  610. }
  611. else if (!String.IsNullOrEmpty (script.Name)) {
  612. Assembly assembly;
  613. if (String.IsNullOrEmpty (script.Assembly))
  614. assembly = typeof (ScriptManager).Assembly;
  615. else
  616. assembly = Assembly.Load (script.Assembly);
  617. string name = GetScriptName (script.Name, isDebugMode, null);
  618. if (script.IgnoreScriptPath || String.IsNullOrEmpty (ScriptPath))
  619. url = ScriptResourceHandler.GetResourceUrl (assembly, name, script.NotifyScriptLoaded);
  620. else {
  621. AssemblyName an = assembly.GetName ();
  622. url = ResolveClientUrl (String.Concat (VirtualPathUtility.AppendTrailingSlash (ScriptPath), an.Name, '/', an.Version, '/', name));
  623. }
  624. }
  625. else {
  626. throw new InvalidOperationException ("Name and Path cannot both be empty.");
  627. }
  628. if (loadScriptsBeforeUI)
  629. RegisterClientScriptInclude (this, typeof (ScriptManager), url, url);
  630. else
  631. RegisterStartupScript (this, typeof (ScriptManager), url, String.Format ("<script src=\"{0}\" type=\"text/javascript\"></script>", url), false);
  632. }
  633. static string GetScriptName (string releaseName, bool isDebugMode, string [] supportedUICultures) {
  634. if (!isDebugMode && (supportedUICultures == null || supportedUICultures.Length == 0))
  635. return releaseName;
  636. if (releaseName.Length < 3 || !releaseName.EndsWith (".js", StringComparison.OrdinalIgnoreCase))
  637. throw new InvalidOperationException (String.Format ("'{0}' is not a valid script path. The path must end in '.js'.", releaseName));
  638. StringBuilder sb = new StringBuilder (releaseName);
  639. sb.Length -= 3;
  640. if (isDebugMode)
  641. sb.Append (".debug");
  642. string culture = Thread.CurrentThread.CurrentUICulture.Name;
  643. if (supportedUICultures != null && Array.IndexOf<string> (supportedUICultures, culture) >= 0)
  644. sb.AppendFormat (".{0}", culture);
  645. sb.Append (".js");
  646. return sb.ToString ();
  647. }
  648. void RegisterServiceReference (ServiceReference serviceReference) {
  649. if (serviceReference.InlineScript) {
  650. string url = ResolveUrl (serviceReference.Path);
  651. LogicalTypeInfo logicalTypeInfo = LogicalTypeInfo.GetLogicalTypeInfo (WebServiceParser.GetCompiledType (url, Context), url);
  652. RegisterClientScriptBlock (this, typeof (ScriptManager), url, logicalTypeInfo.Proxy, true);
  653. }
  654. else {
  655. #if TARGET_J2EE
  656. string pathInfo = "/js.invoke";
  657. #else
  658. string pathInfo = "/js";
  659. #endif
  660. string url = String.Concat (ResolveClientUrl (serviceReference.Path), pathInfo);
  661. RegisterClientScriptInclude (this, typeof (ScriptManager), url, url);
  662. }
  663. }
  664. public void RegisterDataItem (Control control, string dataItem) {
  665. RegisterDataItem (control, dataItem, false);
  666. }
  667. public void RegisterDataItem (Control control, string dataItem, bool isJsonSerialized) {
  668. if (!IsInAsyncPostBack)
  669. throw new InvalidOperationException ("RegisterDataItem can only be called during an async postback.");
  670. if (control == null)
  671. throw new ArgumentNullException ("control");
  672. if (_dataItems == null)
  673. _dataItems = new Dictionary<Control, DataItemEntry> ();
  674. if (_dataItems.ContainsKey (control))
  675. throw new ArgumentException (String.Format ("'{0}' already has a data item registered.", control.ID), "control");
  676. _dataItems.Add (control, new DataItemEntry (dataItem, isJsonSerialized));
  677. }
  678. public void RegisterDispose (Control control, string disposeScript) {
  679. if (control == null)
  680. throw new ArgumentNullException ("control");
  681. if (disposeScript == null)
  682. throw new ArgumentNullException ("disposeScript");
  683. UpdatePanel updatePanel = GetUpdatePanel (control);
  684. if (updatePanel == null)
  685. return;
  686. if (_disposeScripts == null)
  687. _disposeScripts = new List<DisposeScriptEntry> ();
  688. _disposeScripts.Add (new DisposeScriptEntry (updatePanel, disposeScript));
  689. }
  690. static UpdatePanel GetUpdatePanel (Control control) {
  691. if (control == null)
  692. return null;
  693. UpdatePanel parent = control.Parent as UpdatePanel;
  694. if (parent != null)
  695. return parent;
  696. return GetUpdatePanel (control.Parent);
  697. }
  698. public static void RegisterExpandoAttribute (Control control, string controlId, string attributeName, string attributeValue, bool encode) {
  699. Page page = control.Page;
  700. ScriptManager sm = GetCurrent (page);
  701. if (sm.IsInAsyncPostBack)
  702. sm.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
  703. else
  704. page.ClientScript.RegisterExpandoAttribute (controlId, attributeName, attributeValue, encode);
  705. }
  706. private void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue, bool encode) {
  707. // seems MS do nothing.
  708. }
  709. public static void RegisterHiddenField (Control control, string hiddenFieldName, string hiddenFieldInitialValue) {
  710. RegisterHiddenField (control.Page, hiddenFieldName, hiddenFieldInitialValue);
  711. }
  712. public static void RegisterHiddenField (Page page, string hiddenFieldName, string hiddenFieldInitialValue) {
  713. ScriptManager sm = GetCurrent (page);
  714. if (sm.IsInAsyncPostBack)
  715. sm.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  716. else
  717. page.ClientScript.RegisterHiddenField (hiddenFieldName, hiddenFieldInitialValue);
  718. }
  719. void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue) {
  720. if (_hiddenFields == null)
  721. _hiddenFields = new Hashtable ();
  722. if (!_hiddenFields.ContainsKey (hiddenFieldName))
  723. _hiddenFields.Add (hiddenFieldName, hiddenFieldInitialValue);
  724. }
  725. public static void RegisterOnSubmitStatement (Control control, Type type, string key, string script) {
  726. RegisterOnSubmitStatement (control.Page, type, key, script);
  727. }
  728. public static void RegisterOnSubmitStatement (Page page, Type type, string key, string script) {
  729. ScriptManager sm = GetCurrent (page);
  730. if (sm.IsInAsyncPostBack)
  731. RegisterScript (ref sm._onSubmitStatements, type, key, script, ScriptEntryType.OnSubmit);
  732. else
  733. page.ClientScript.RegisterOnSubmitStatement (type, key, script);
  734. }
  735. public void RegisterPostBackControl (Control control) {
  736. if (control == null)
  737. return;
  738. if (_postBackControls == null)
  739. _postBackControls = new List<Control> ();
  740. if (_postBackControls.Contains (control))
  741. return;
  742. _postBackControls.Add (control);
  743. }
  744. internal void RegisterUpdatePanel (UpdatePanel updatePanel) {
  745. if (_updatePanels == null)
  746. _updatePanels = new List<UpdatePanel> ();
  747. if (_updatePanels.Contains (updatePanel))
  748. return;
  749. _updatePanels.Add (updatePanel);
  750. }
  751. public void RegisterScriptDescriptors (IExtenderControl extenderControl) {
  752. if (extenderControl == null)
  753. return;
  754. if (_registeredExtenderControls == null || !_registeredExtenderControls.ContainsKey (extenderControl))
  755. return;
  756. Control targetControl = _registeredExtenderControls [extenderControl];
  757. RegisterScriptDescriptors (extenderControl.GetScriptDescriptors (targetControl));
  758. }
  759. public void RegisterScriptDescriptors (IScriptControl scriptControl) {
  760. if (scriptControl == null)
  761. return;
  762. if (_registeredScriptControls == null || !_registeredScriptControls.Contains (scriptControl))
  763. return;
  764. RegisterScriptDescriptors (scriptControl.GetScriptDescriptors ());
  765. }
  766. void RegisterScriptDescriptors (IEnumerable<ScriptDescriptor> scriptDescriptors) {
  767. if (scriptDescriptors == null)
  768. return;
  769. if (IsInAsyncPostBack && !IsInPartialRendering)
  770. return;
  771. StringBuilder sb = new StringBuilder ();
  772. foreach (ScriptDescriptor scriptDescriptor in scriptDescriptors) {
  773. if (IsMultiForm) {
  774. scriptDescriptor.FormID = Page.Form.ClientID;
  775. sb.AppendLine ("Sys.Application.getInstance($get(\"" + Page.Form.ClientID + "\")).add_init(function() {");
  776. }
  777. else
  778. sb.AppendLine ("Sys.Application.add_init(function() {");
  779. sb.AppendLine (scriptDescriptor.GetScript ());
  780. sb.AppendLine ("});");
  781. }
  782. string script = sb.ToString ();
  783. RegisterStartupScript (this, typeof (ExtenderControl), script, script, true);
  784. }
  785. public static void RegisterStartupScript (Control control, Type type, string key, string script, bool addScriptTags) {
  786. RegisterStartupScript (control.Page, type, key, script, addScriptTags);
  787. }
  788. public static void RegisterStartupScript (Page page, Type type, string key, string script, bool addScriptTags) {
  789. ScriptManager sm = GetCurrent (page);
  790. if (sm.IsInAsyncPostBack)
  791. RegisterScript (ref sm._startupScriptBlocks, type, key, script, addScriptTags ? ScriptEntryType.ScriptContentNoTags : ScriptEntryType.ScriptContentWithTags);
  792. else
  793. page.ClientScript.RegisterStartupScript (type, key, script, addScriptTags);
  794. }
  795. public void RegisterScriptControl<TScriptControl> (TScriptControl scriptControl) where TScriptControl : Control, IScriptControl {
  796. if (scriptControl == null)
  797. throw new ArgumentNullException ("scriptControl");
  798. if (_registeredScriptControls == null)
  799. _registeredScriptControls = new List<IScriptControl> ();
  800. if (!_registeredScriptControls.Contains (scriptControl))
  801. _registeredScriptControls.Add (scriptControl);
  802. }
  803. public void RegisterExtenderControl<TExtenderControl> (TExtenderControl extenderControl, Control targetControl) where TExtenderControl : Control, IExtenderControl {
  804. if (extenderControl == null)
  805. throw new ArgumentNullException ("extenderControl");
  806. if (targetControl == null)
  807. throw new ArgumentNullException ("targetControl");
  808. if (_registeredExtenderControls == null)
  809. _registeredExtenderControls = new Dictionary<IExtenderControl, Control> ();
  810. if (!_registeredExtenderControls.ContainsKey (extenderControl))
  811. _registeredExtenderControls.Add (extenderControl, targetControl);
  812. }
  813. static void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, ScriptEntryType scriptEntryType) {
  814. ScriptEntry last = null;
  815. ScriptEntry entry = scriptList;
  816. while (entry != null) {
  817. if (entry.Type == type && entry.Key == key)
  818. return;
  819. last = entry;
  820. entry = entry.Next;
  821. }
  822. entry = new ScriptEntry (type, key, script, scriptEntryType);
  823. if (last != null)
  824. last.Next = entry;
  825. else
  826. scriptList = entry;
  827. }
  828. protected override void Render (HtmlTextWriter writer) {
  829. // MSDN: This method is used by control developers to extend the ScriptManager control.
  830. // Notes to Inheritors:
  831. // When overriding this method, call the base Render(HtmlTextWriter) method
  832. // so that PageRequestManager is rendered on the page.
  833. if (SupportsPartialRendering) {
  834. writer.WriteLine ("<script type=\"text/javascript\">");
  835. writer.WriteLine ("//<![CDATA[");
  836. writer.WriteLine ("Sys.WebForms.PageRequestManager._initialize('{0}', document.getElementById('{1}'));", UniqueID, Page.Form.ClientID);
  837. if (IsMultiForm)
  838. writer.WriteLine ("Sys.WebForms.PageRequestManager.getInstance($get(\"{0}\"))._updateControls([{1}], [{2}], [{3}], {4});", Page.Form.ClientID, FormatUpdatePanelIDs (_updatePanels, true), FormatListIDs (_asyncPostBackControls, true), FormatListIDs (_postBackControls, true), AsyncPostBackTimeout);
  839. else
  840. writer.WriteLine ("Sys.WebForms.PageRequestManager.getInstance()._updateControls([{0}], [{1}], [{2}], {3});", FormatUpdatePanelIDs (_updatePanels, true), FormatListIDs (_asyncPostBackControls, true), FormatListIDs (_postBackControls, true), AsyncPostBackTimeout);
  841. writer.WriteLine ("//]]");
  842. writer.WriteLine ("</script>");
  843. }
  844. base.Render (writer);
  845. }
  846. static string FormatUpdatePanelIDs (List<UpdatePanel> list, bool useSingleQuote) {
  847. if (list == null || list.Count == 0)
  848. return null;
  849. StringBuilder sb = new StringBuilder ();
  850. for (int i = 0; i < list.Count; i++) {
  851. sb.AppendFormat ("{0}{1}{2}{0},", useSingleQuote ? "'" : String.Empty, list [i].ChildrenAsTriggers ? "t" : "f", list [i].UniqueID);
  852. }
  853. if (sb.Length > 0)
  854. sb.Length--;
  855. return sb.ToString ();
  856. }
  857. static string FormatListIDs<T> (List<T> list, bool useSingleQuote) where T : Control {
  858. if (list == null || list.Count == 0)
  859. return null;
  860. StringBuilder sb = new StringBuilder ();
  861. for (int i = 0; i < list.Count; i++) {
  862. sb.AppendFormat ("{0}{1}{0},", useSingleQuote ? "'" : String.Empty, list [i].UniqueID);
  863. }
  864. if (sb.Length > 0)
  865. sb.Length--;
  866. return sb.ToString ();
  867. }
  868. public void SetFocus (Control control) {
  869. if (control == null)
  870. throw new ArgumentNullException ("control");
  871. if (IsInAsyncPostBack) {
  872. EnsureFocusClientScript ();
  873. _controlIDToFocus = control.ClientID;
  874. }
  875. else
  876. Page.SetFocus (control);
  877. }
  878. public void SetFocus (string clientID) {
  879. if (String.IsNullOrEmpty (clientID))
  880. throw new ArgumentNullException ("control");
  881. if (IsInAsyncPostBack) {
  882. EnsureFocusClientScript ();
  883. _controlIDToFocus = clientID;
  884. }
  885. else
  886. Page.SetFocus (clientID);
  887. }
  888. void EnsureFocusClientScript () {
  889. #if TARGET_DOTNET
  890. RegisterClientScriptResource (this, typeof (ClientScriptManager), "Focus.js");
  891. #endif
  892. }
  893. #region IPostBackDataHandler Members
  894. bool IPostBackDataHandler.LoadPostData (string postDataKey, NameValueCollection postCollection) {
  895. return LoadPostData (postDataKey, postCollection);
  896. }
  897. void IPostBackDataHandler.RaisePostDataChangedEvent () {
  898. RaisePostDataChangedEvent ();
  899. }
  900. #endregion
  901. internal void WriteCallbackException (TextWriter output, Exception ex, bool writeMessage) {
  902. #if TARGET_DOTNET
  903. if (ex is HttpUnhandledException)
  904. ex = ex.InnerException;
  905. #endif
  906. HttpException httpEx = ex as HttpException;
  907. string message = AsyncPostBackErrorMessage;
  908. if (String.IsNullOrEmpty (message) && writeMessage)
  909. message = ex.Message;
  910. WriteCallbackOutput (output, error, httpEx == null ? "500" : httpEx.GetHttpCode ().ToString (), message);
  911. }
  912. static internal void WriteCallbackRedirect (TextWriter output, string redirectUrl) {
  913. WriteCallbackOutput (output, pageRedirect, null, redirectUrl);
  914. }
  915. internal void WriteCallbackPanel (TextWriter output, UpdatePanel panel, StringBuilder panelOutput) {
  916. if (_panelsToRefresh == null)
  917. _panelsToRefresh = new List<UpdatePanel> ();
  918. _panelsToRefresh.Add (panel);
  919. WriteCallbackOutput (output, updatePanel, panel.ClientID, panelOutput);
  920. }
  921. internal void RegisterChildUpdatePanel (UpdatePanel updatePanel) {
  922. if (_childUpdatePanels == null)
  923. _childUpdatePanels = new List<UpdatePanel> ();
  924. _childUpdatePanels.Add (updatePanel);
  925. }
  926. static void WriteCallbackOutput (TextWriter output, string type, string name, object value) {
  927. string str = value as string;
  928. StringBuilder sb = value as StringBuilder;
  929. int length = 0;
  930. if (str != null)
  931. length = str.Length;
  932. else if (sb != null)
  933. length = sb.Length;
  934. //output.Write ("{0}|{1}|{2}|{3}|", value == null ? 0 : value.Length, type, name, value);
  935. output.Write (length);
  936. output.Write ('|');
  937. output.Write (type);
  938. output.Write ('|');
  939. output.Write (name);
  940. output.Write ('|');
  941. for (int i = 0; i < length; i++)
  942. if (str != null)
  943. output.Write (str [i]);
  944. else
  945. output.Write (sb [i]);
  946. output.Write ('|');
  947. }
  948. void RenderPageCallback (HtmlTextWriter output, Control container) {
  949. Page page = (Page) container;
  950. page.Form.SetRenderMethodDelegate (RenderFormCallback);
  951. HtmlTextParser parser = new HtmlTextParser (output);
  952. page.Form.RenderControl (parser);
  953. WriteCallbackOutput (output, asyncPostBackControlIDs, null, FormatListIDs (_asyncPostBackControls, false));
  954. WriteCallbackOutput (output, postBackControlIDs, null, FormatListIDs (_postBackControls, false));
  955. WriteCallbackOutput (output, updatePanelIDs, null, FormatUpdatePanelIDs (_updatePanels, false));
  956. WriteCallbackOutput (output, childUpdatePanelIDs, null, FormatListIDs (_childUpdatePanels, false));
  957. WriteCallbackOutput (output, panelsToRefreshIDs, null, FormatListIDs (_panelsToRefresh, false));
  958. WriteCallbackOutput (output, asyncPostBackTimeout, null, AsyncPostBackTimeout.ToString ());
  959. if (!IsMultiForm)
  960. WriteCallbackOutput (output, pageTitle, null, Page.Title);
  961. if (_dataItems != null)
  962. foreach (Control control in _dataItems.Keys) {
  963. DataItemEntry entry = _dataItems [control];
  964. WriteCallbackOutput (output, entry.IsJsonSerialized ? dataItemJson : dataItem, control.ClientID, entry.DataItem);
  965. }
  966. WriteArrayDeclarations (output);
  967. WriteScriptBlocks (output, _clientScriptBlocks);
  968. WriteScriptBlocks (output, _scriptIncludes);
  969. WriteScriptBlocks (output, _startupScriptBlocks);
  970. WriteScriptBlocks (output, _onSubmitStatements);
  971. WriteHiddenFields (output);
  972. if (!String.IsNullOrEmpty (_controlIDToFocus))
  973. WriteCallbackOutput (output, focus, null, _controlIDToFocus);
  974. if (_disposeScripts != null)
  975. for (int i = 0; i < _disposeScripts.Count; i++) {
  976. DisposeScriptEntry entry = _disposeScripts [i];
  977. if ((_panelsToRefresh != null && _panelsToRefresh.IndexOf (entry.UpdatePanel) >= 0) || (_childUpdatePanels != null && _childUpdatePanels.IndexOf (entry.UpdatePanel) >= 0))
  978. WriteCallbackOutput (output, scriptDispose, entry.UpdatePanel.ClientID, entry.Script);
  979. }
  980. }
  981. void WriteArrayDeclarations (HtmlTextWriter writer) {
  982. if (_arrayDeclarations != null) {
  983. for (int i = 0; i < _arrayDeclarations.Count; i++) {
  984. ArrayDeclaration array = _arrayDeclarations [i];
  985. WriteCallbackOutput (writer, arrayDeclaration, array.ArrayName, array.ArrayValue);
  986. }
  987. }
  988. }
  989. void WriteScriptBlocks (HtmlTextWriter output, ScriptEntry scriptList) {
  990. while (scriptList != null) {
  991. switch (scriptList.ScriptEntryType) {
  992. case ScriptEntryType.ScriptContentNoTags:
  993. WriteCallbackOutput (output, scriptBlock, scriptContentNoTags, scriptList.Script);
  994. break;
  995. case ScriptEntryType.ScriptContentWithTags:
  996. string script = SerializeScriptBlock (scriptList);
  997. WriteCallbackOutput (output, scriptBlock, scriptContentWithTags, script);
  998. break;
  999. case ScriptEntryType.ScriptPath:
  1000. WriteCallbackOutput (output, scriptBlock, scriptPath, scriptList.Script);
  1001. break;
  1002. case ScriptEntryType.OnSubmit:
  1003. WriteCallbackOutput (output, onSubmit, null, scriptList.Script);
  1004. break;
  1005. }
  1006. scriptList = scriptList.Next;
  1007. }
  1008. }
  1009. void WriteHiddenFields (HtmlTextWriter output) {
  1010. if (_hiddenFields == null)
  1011. return;
  1012. foreach (string key in _hiddenFields.Keys) {
  1013. string value = _hiddenFields [key] as string;
  1014. WriteCallbackOutput (output, hiddenField, key, value);
  1015. }
  1016. }
  1017. static string SerializeScriptBlock (ScriptEntry scriptList) {
  1018. try {
  1019. XmlTextReader reader = new XmlTextReader (new StringReader (scriptList.Script));
  1020. while (reader.Read ()) {
  1021. switch (reader.NodeType) {
  1022. case XmlNodeType.Element:
  1023. if (String.Compare ("script", reader.Name, StringComparison.OrdinalIgnoreCase) == 0) {
  1024. Dictionary<string, string> dic = new Dictionary<string, string> ();
  1025. while (reader.MoveToNextAttribute ()) {
  1026. dic.Add (reader.Name, reader.Value);
  1027. }
  1028. reader.MoveToContent ();
  1029. dic.Add ("text", reader.ReadInnerXml ());
  1030. return JavaScriptSerializer.DefaultSerializer.Serialize (dic);
  1031. }
  1032. break;
  1033. default:
  1034. continue;
  1035. }
  1036. }
  1037. }
  1038. catch {
  1039. }
  1040. 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));
  1041. }
  1042. void RenderFormCallback (HtmlTextWriter output, Control container) {
  1043. output = ((HtmlTextParser) output).ResponseOutput;
  1044. HtmlForm form = (HtmlForm) container;
  1045. HtmlTextWriter writer = new HtmlDropWriter (output);
  1046. if (form.HasControls ()) {
  1047. for (int i = 0; i < form.Controls.Count; i++) {
  1048. form.Controls [i].RenderControl (writer);
  1049. }
  1050. }
  1051. }
  1052. internal class AlternativeHtmlTextWriter : HtmlTextWriter
  1053. {
  1054. readonly HtmlTextWriter _responseOutput;
  1055. public HtmlTextWriter ResponseOutput {
  1056. get { return _responseOutput; }
  1057. }
  1058. public AlternativeHtmlTextWriter (TextWriter writer, HtmlTextWriter responseOutput)
  1059. : base (writer) {
  1060. _responseOutput = responseOutput;
  1061. }
  1062. }
  1063. sealed class HtmlTextParser : AlternativeHtmlTextWriter
  1064. {
  1065. public HtmlTextParser (HtmlTextWriter responseOutput)
  1066. : base (new TextParser (responseOutput), responseOutput) {
  1067. }
  1068. }
  1069. sealed class TextParser : TextWriter
  1070. {
  1071. int _state;
  1072. char _charState = (char) 255;
  1073. const char nullCharState = (char) 255;
  1074. StringBuilder _sb = new StringBuilder ();
  1075. Dictionary<string, string> _currentField;
  1076. string _currentAttribute;
  1077. readonly HtmlTextWriter _responseOutput;
  1078. public override Encoding Encoding {
  1079. get { return Encoding.UTF8; }
  1080. }
  1081. public TextParser (HtmlTextWriter responseOutput) {
  1082. _responseOutput = responseOutput;
  1083. }
  1084. public override void Write (char value) {
  1085. switch (_state) {
  1086. case 0:
  1087. ParseBeginTag (value);
  1088. break;
  1089. case 1:
  1090. ParseAttributeName (value);
  1091. break;
  1092. case 2:
  1093. ParseAttributeValue (value);
  1094. break;
  1095. }
  1096. }
  1097. private void ParseAttributeValue (char value) {
  1098. switch (value) {
  1099. case '>':
  1100. ResetState ();
  1101. break;
  1102. case '"':
  1103. _currentField.Add (_currentAttribute, _sb.ToString ());
  1104. _state = 1;
  1105. _sb.Length = 0;
  1106. ProbeWriteOutput ();
  1107. break;
  1108. default:
  1109. _sb.Append (value);
  1110. break;
  1111. }
  1112. }
  1113. private void ParseAttributeName (char value) {
  1114. switch (value) {
  1115. case '>':
  1116. ResetState ();
  1117. break;
  1118. case ' ':
  1119. case '=':
  1120. break;
  1121. case '"':
  1122. _currentAttribute = _sb.ToString ();
  1123. _state = 2;
  1124. _sb.Length = 0;
  1125. break;
  1126. default:
  1127. _sb.Append (value);
  1128. break;
  1129. }
  1130. }
  1131. void ParseBeginTag (char value) {
  1132. switch (_charState) {
  1133. case nullCharState:
  1134. if (value == '<')
  1135. _charState = value;
  1136. break;
  1137. case '<':
  1138. if (value == 'i')
  1139. _charState = value;
  1140. else
  1141. ResetState ();
  1142. break;
  1143. case 'i':
  1144. if (value == 'n')
  1145. _charState = value;
  1146. else
  1147. ResetState ();
  1148. break;
  1149. case 'n':
  1150. if (value == 'p')
  1151. _charState = value;
  1152. else
  1153. ResetState ();
  1154. break;
  1155. case 'p':
  1156. if (value == 'u')
  1157. _charState = value;
  1158. else
  1159. ResetState ();
  1160. break;
  1161. case 'u':
  1162. if (value == 't')
  1163. _charState = value;
  1164. else
  1165. ResetState ();
  1166. break;
  1167. case 't':
  1168. if (value == ' ') {
  1169. _state = 1;
  1170. _currentField = new Dictionary<string, string> ();
  1171. }
  1172. else
  1173. ResetState ();
  1174. break;
  1175. }
  1176. }
  1177. private void ResetState () {
  1178. _charState = nullCharState;
  1179. _state = 0;
  1180. _sb.Length = 0;
  1181. }
  1182. private void ProbeWriteOutput () {
  1183. if (!_currentField.ContainsKey ("name"))
  1184. return;
  1185. if (!_currentField.ContainsKey ("value"))
  1186. return;
  1187. string value = _currentField ["value"];
  1188. if (String.IsNullOrEmpty (value))
  1189. return;
  1190. ScriptManager.WriteCallbackOutput (_responseOutput, hiddenField, _currentField ["name"], HttpUtility.HtmlDecode (value));
  1191. }
  1192. }
  1193. sealed class HtmlDropWriter : AlternativeHtmlTextWriter
  1194. {
  1195. public HtmlDropWriter (HtmlTextWriter responseOutput)
  1196. : base (new DropWriter (), responseOutput) {
  1197. }
  1198. }
  1199. sealed class DropWriter : TextWriter
  1200. {
  1201. public override Encoding Encoding {
  1202. get { return Encoding.UTF8; }
  1203. }
  1204. }
  1205. sealed class ScriptEntry
  1206. {
  1207. readonly public Type Type;
  1208. readonly public string Key;
  1209. readonly public string Script;
  1210. readonly public ScriptEntryType ScriptEntryType;
  1211. public ScriptEntry Next;
  1212. public ScriptEntry (Type type, string key, string script, ScriptEntryType scriptEntryType) {
  1213. Key = key;
  1214. Type = type;
  1215. Script = script;
  1216. ScriptEntryType = scriptEntryType;
  1217. }
  1218. }
  1219. enum ScriptEntryType
  1220. {
  1221. ScriptContentNoTags,
  1222. ScriptContentWithTags,
  1223. ScriptPath,
  1224. OnSubmit
  1225. }
  1226. sealed class ArrayDeclaration
  1227. {
  1228. readonly public string ArrayName;
  1229. readonly public string ArrayValue;
  1230. public ArrayDeclaration (string arrayName, string arrayValue) {
  1231. ArrayName = arrayName;
  1232. ArrayValue = arrayValue;
  1233. }
  1234. }
  1235. sealed class CultureInfoSerializer : JavaScriptSerializer.LazyDictionary
  1236. {
  1237. readonly CultureInfo _ci;
  1238. public CultureInfoSerializer (CultureInfo ci) {
  1239. if (ci == null)
  1240. throw new ArgumentNullException ("ci");
  1241. _ci = ci;
  1242. }
  1243. protected override IEnumerator<KeyValuePair<string, object>> GetEnumerator () {
  1244. yield return new KeyValuePair<string, object> ("name", _ci.Name);
  1245. yield return new KeyValuePair<string, object> ("numberFormat", _ci.NumberFormat);
  1246. yield return new KeyValuePair<string, object> ("dateTimeFormat", _ci.DateTimeFormat);
  1247. }
  1248. }
  1249. sealed class ScriptReferenceEntry
  1250. {
  1251. readonly Control _control;
  1252. readonly ScriptReference _scriptReference;
  1253. readonly bool _loadBeforeUI;
  1254. public Control Control { get { return _control; } }
  1255. public ScriptReference ScriptReference { get { return _scriptReference; } }
  1256. public bool LoadScriptsBeforeUI { get { return _loadBeforeUI; } }
  1257. public ScriptReferenceEntry (Control control, ScriptReference scriptReference, bool loadBeforeUI) {
  1258. _control = control;
  1259. _scriptReference = scriptReference;
  1260. _loadBeforeUI = loadBeforeUI;
  1261. }
  1262. }
  1263. sealed class DataItemEntry
  1264. {
  1265. readonly string _dataItem;
  1266. readonly bool _isJsonSerialized;
  1267. public string DataItem { get { return _dataItem; } }
  1268. public bool IsJsonSerialized { get { return _isJsonSerialized; } }
  1269. public DataItemEntry (string dataItem, bool isJsonSerialized) {
  1270. _dataItem = dataItem;
  1271. _isJsonSerialized = isJsonSerialized;
  1272. }
  1273. }
  1274. sealed class DisposeScriptEntry
  1275. {
  1276. readonly UpdatePanel _updatePanel;
  1277. readonly string _script;
  1278. public UpdatePanel UpdatePanel { get { return _updatePanel; } }
  1279. public string Script { get { return _script; } }
  1280. public DisposeScriptEntry (UpdatePanel updatePanel, string script) {
  1281. _updatePanel = updatePanel;
  1282. _script = script;
  1283. }
  1284. }
  1285. }
  1286. }