ScriptManager.cs 56 KB

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