ClientScriptManager.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815
  1. //
  2. // System.Web.UI.ClientScriptManager.cs
  3. //
  4. // Authors:
  5. // Duncan Mak ([email protected])
  6. // Gonzalo Paniagua ([email protected])
  7. // Andreas Nahr ([email protected])
  8. // Lluis Sanchez ([email protected])
  9. //
  10. // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
  11. // (c) 2003 Novell, Inc. (http://www.novell.com)
  12. //
  13. //
  14. // Permission is hereby granted, free of charge, to any person obtaining
  15. // a copy of this software and associated documentation files (the
  16. // "Software"), to deal in the Software without restriction, including
  17. // without limitation the rights to use, copy, modify, merge, publish,
  18. // distribute, sublicense, and/or sell copies of the Software, and to
  19. // permit persons to whom the Software is furnished to do so, subject to
  20. // the following conditions:
  21. //
  22. // The above copyright notice and this permission notice shall be
  23. // included in all copies or substantial portions of the Software.
  24. //
  25. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  26. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  27. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  28. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  29. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  30. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  31. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  32. //
  33. using System;
  34. using System.Collections;
  35. #if NET_2_0
  36. using System.Collections.Generic;
  37. #endif
  38. using System.Text;
  39. using System.Collections.Specialized;
  40. using System.Web.Util;
  41. using System.Globalization;
  42. namespace System.Web.UI
  43. {
  44. #if NET_2_0
  45. public sealed
  46. #else
  47. internal
  48. #endif
  49. class ClientScriptManager
  50. {
  51. Hashtable registeredArrayDeclares;
  52. ScriptEntry clientScriptBlocks;
  53. ScriptEntry startupScriptBlocks;
  54. internal Hashtable hiddenFields;
  55. ScriptEntry submitStatements;
  56. Page page;
  57. #if NET_2_0
  58. int [] eventValidationValues;
  59. int eventValidationPos = 0;
  60. Hashtable expandoAttributes;
  61. bool _hasRegisteredForEventValidationOnCallback;
  62. #endif
  63. internal ClientScriptManager (Page page)
  64. {
  65. this.page = page;
  66. }
  67. #if !NET_2_0
  68. public string GetPostBackClientEvent (Control control, string argument)
  69. {
  70. return GetPostBackEventReference (control, argument);
  71. }
  72. #endif
  73. public string GetPostBackClientHyperlink (Control control, string argument)
  74. {
  75. return "javascript:" + GetPostBackEventReference (control, argument);
  76. }
  77. #if NET_2_0
  78. public string GetPostBackClientHyperlink (Control control, string argument, bool registerForEventValidation)
  79. {
  80. if (registerForEventValidation)
  81. RegisterForEventValidation (control.UniqueID, argument);
  82. return "javascript:" + GetPostBackEventReference (control, argument);
  83. }
  84. #endif
  85. #if !NET_2_0
  86. internal
  87. #else
  88. public
  89. #endif
  90. string GetPostBackEventReference (Control control, string argument)
  91. {
  92. if (control == null)
  93. throw new ArgumentNullException ("control");
  94. page.RequiresPostBackScript ();
  95. #if NET_2_0
  96. return String.Format ("{0}.__doPostBack('{1}','{2}')", page.theForm, control.UniqueID, argument);
  97. #else
  98. return String.Format ("__doPostBack('{0}','{1}')", control.UniqueID, argument);
  99. #endif
  100. }
  101. #if NET_2_0
  102. public string GetPostBackEventReference (Control control, string argument, bool registerForEventValidation)
  103. {
  104. if (control == null)
  105. throw new ArgumentNullException ("control");
  106. if (registerForEventValidation)
  107. RegisterForEventValidation (control.UniqueID, argument);
  108. return GetPostBackEventReference (control, argument);
  109. }
  110. public string GetPostBackEventReference (PostBackOptions options, bool registerForEventValidation)
  111. {
  112. if (options == null)
  113. throw new ArgumentNullException ("options");
  114. if (registerForEventValidation)
  115. RegisterForEventValidation (options);
  116. return GetPostBackEventReference (options);
  117. }
  118. public string GetPostBackEventReference (PostBackOptions options)
  119. {
  120. if (options == null)
  121. throw new ArgumentNullException ("options");
  122. if (options.ActionUrl == null && options.ValidationGroup == null && !options.TrackFocus &&
  123. !options.AutoPostBack && !options.PerformValidation)
  124. {
  125. if (!options.ClientSubmit)
  126. return null;
  127. if (options.RequiresJavaScriptProtocol)
  128. return GetPostBackClientHyperlink (options.TargetControl, options.Argument);
  129. else
  130. return GetPostBackEventReference (options.TargetControl, options.Argument);
  131. }
  132. RegisterWebFormClientScript ();
  133. string actionUrl = options.ActionUrl;
  134. if (actionUrl != null)
  135. RegisterHiddenField (Page.PreviousPageID, page.Request.FilePath);
  136. if(options.TrackFocus)
  137. RegisterHiddenField (Page.LastFocusID, String.Empty);
  138. string prefix = options.RequiresJavaScriptProtocol ? "javascript:" : "";
  139. #if TARGET_J2EE
  140. // Allow the page to transform ActionUrl to a portlet action url
  141. if (actionUrl != null && page.PortletNamespace != null) {
  142. actionUrl = page.CreateActionUrl(actionUrl);
  143. prefix += "Portal";
  144. }
  145. #endif
  146. return String.Format ("{0}WebForm_DoPostback({1},{2},{3},{4},{5},{6},{7},{8},{9})",
  147. prefix,
  148. ClientScriptManager.GetScriptLiteral (options.TargetControl.UniqueID),
  149. ClientScriptManager.GetScriptLiteral (options.Argument),
  150. ClientScriptManager.GetScriptLiteral (actionUrl),
  151. ClientScriptManager.GetScriptLiteral (options.AutoPostBack),
  152. ClientScriptManager.GetScriptLiteral (options.PerformValidation),
  153. ClientScriptManager.GetScriptLiteral (options.TrackFocus),
  154. ClientScriptManager.GetScriptLiteral (options.ClientSubmit),
  155. ClientScriptManager.GetScriptLiteral (options.ValidationGroup),
  156. page.theForm
  157. );
  158. }
  159. internal void RegisterWebFormClientScript ()
  160. {
  161. if (_webFormClientScriptRequired)
  162. return;
  163. page.RequiresPostBackScript ();
  164. _webFormClientScriptRequired = true;
  165. }
  166. bool _webFormClientScriptRendered;
  167. bool _webFormClientScriptRequired;
  168. internal void WriteWebFormClientScript (HtmlTextWriter writer) {
  169. if (!_webFormClientScriptRendered && _webFormClientScriptRequired) {
  170. writer.WriteLine ();
  171. WriteClientScriptInclude (writer, GetWebResourceUrl (typeof (Page), "webform.js"));
  172. _webFormClientScriptRendered = true;
  173. }
  174. }
  175. public string GetCallbackEventReference (Control control, string argument, string clientCallback, string context)
  176. {
  177. return GetCallbackEventReference (control, argument, clientCallback, context, null, false);
  178. }
  179. public string GetCallbackEventReference (Control control, string argument, string clientCallback, string context, bool useAsync)
  180. {
  181. return GetCallbackEventReference (control, argument, clientCallback, context, null, useAsync);
  182. }
  183. public string GetCallbackEventReference (Control control, string argument, string clientCallback, string context, string clientErrorCallback, bool useAsync)
  184. {
  185. if (control == null)
  186. throw new ArgumentNullException ("control");
  187. if(!(control is ICallbackEventHandler))
  188. throw new InvalidOperationException ("The control must implement the ICallbackEventHandler interface and provide a RaiseCallbackEvent method.");
  189. return GetCallbackEventReference (control.UniqueID, argument, clientCallback, context, clientErrorCallback, useAsync);
  190. }
  191. public string GetCallbackEventReference (string target, string argument, string clientCallback, string context, string clientErrorCallback, bool useAsync)
  192. {
  193. RegisterWebFormClientScript ();
  194. return string.Format ("WebForm_DoCallback('{0}',{1},{2},{3},{4},{5},{6})", target, argument, clientCallback, context, ((clientErrorCallback == null) ? "null" : clientErrorCallback), (useAsync ? "true" : "false"), page.theForm);
  195. }
  196. #endif
  197. #if NET_2_0
  198. public
  199. #else
  200. internal
  201. #endif
  202. string GetWebResourceUrl(Type type, string resourceName)
  203. {
  204. if (type == null)
  205. throw new ArgumentNullException ("type");
  206. if (resourceName == null || resourceName.Length == 0)
  207. throw new ArgumentNullException ("type");
  208. return System.Web.Handlers.AssemblyResourceLoader.GetResourceUrl (type, resourceName);
  209. }
  210. public bool IsClientScriptBlockRegistered (string key)
  211. {
  212. return IsScriptRegistered (clientScriptBlocks, GetType(), key);
  213. }
  214. public bool IsClientScriptBlockRegistered (Type type, string key)
  215. {
  216. return IsScriptRegistered (clientScriptBlocks, type, key);
  217. }
  218. public bool IsStartupScriptRegistered (string key)
  219. {
  220. return IsScriptRegistered (startupScriptBlocks, GetType(), key);
  221. }
  222. public bool IsStartupScriptRegistered (Type type, string key)
  223. {
  224. return IsScriptRegistered (startupScriptBlocks, type, key);
  225. }
  226. public bool IsOnSubmitStatementRegistered (string key)
  227. {
  228. return IsScriptRegistered (submitStatements, GetType(), key);
  229. }
  230. public bool IsOnSubmitStatementRegistered (Type type, string key)
  231. {
  232. return IsScriptRegistered (submitStatements, type, key);
  233. }
  234. public bool IsClientScriptIncludeRegistered (string key)
  235. {
  236. return IsClientScriptIncludeRegistered (GetType (), key);
  237. }
  238. public bool IsClientScriptIncludeRegistered (Type type, string key)
  239. {
  240. return IsScriptRegistered (clientScriptBlocks, type, "include-" + key);
  241. }
  242. bool IsScriptRegistered (ScriptEntry scriptList, Type type, string key)
  243. {
  244. while (scriptList != null) {
  245. if (scriptList.Type == type && scriptList.Key == key)
  246. return true;
  247. scriptList = scriptList.Next;
  248. }
  249. return false;
  250. }
  251. public void RegisterArrayDeclaration (string arrayName, string arrayValue)
  252. {
  253. if (registeredArrayDeclares == null)
  254. registeredArrayDeclares = new Hashtable();
  255. if (!registeredArrayDeclares.ContainsKey (arrayName))
  256. registeredArrayDeclares.Add (arrayName, new ArrayList());
  257. ((ArrayList) registeredArrayDeclares[arrayName]).Add(arrayValue);
  258. }
  259. void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, bool addScriptTags)
  260. {
  261. RegisterScript (ref scriptList, type, key, script, addScriptTags ? ScriptEntryFormat.AddScriptTag : ScriptEntryFormat.None);
  262. }
  263. void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, ScriptEntryFormat format)
  264. {
  265. ScriptEntry last = null;
  266. ScriptEntry entry = scriptList;
  267. while (entry != null) {
  268. if (entry.Type == type && entry.Key == key)
  269. return;
  270. last = entry;
  271. entry = entry.Next;
  272. }
  273. entry = new ScriptEntry (type, key, script, format);
  274. if (last != null) last.Next = entry;
  275. else scriptList = entry;
  276. }
  277. internal void RegisterClientScriptBlock (string key, string script)
  278. {
  279. RegisterScript (ref clientScriptBlocks, GetType(), key, script, false);
  280. }
  281. public void RegisterClientScriptBlock (Type type, string key, string script)
  282. {
  283. RegisterClientScriptBlock (type, key, script, false);
  284. }
  285. public void RegisterClientScriptBlock (Type type, string key, string script, bool addScriptTags)
  286. {
  287. if (type == null)
  288. throw new ArgumentNullException ("type");
  289. RegisterScript (ref clientScriptBlocks, type, key, script, addScriptTags);
  290. }
  291. public void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
  292. {
  293. if (hiddenFields == null)
  294. hiddenFields = new Hashtable ();
  295. if (!hiddenFields.ContainsKey (hiddenFieldName))
  296. hiddenFields.Add (hiddenFieldName, hiddenFieldInitialValue);
  297. }
  298. internal void RegisterOnSubmitStatement (string key, string script)
  299. {
  300. RegisterScript (ref submitStatements, GetType (), key, script, false);
  301. }
  302. public void RegisterOnSubmitStatement (Type type, string key, string script)
  303. {
  304. if (type == null)
  305. throw new ArgumentNullException ("type");
  306. RegisterScript (ref submitStatements, type, key, script, false);
  307. }
  308. internal void RegisterStartupScript (string key, string script)
  309. {
  310. RegisterScript (ref startupScriptBlocks, GetType(), key, script, false);
  311. }
  312. public void RegisterStartupScript (Type type, string key, string script)
  313. {
  314. RegisterStartupScript (type, key, script, false);
  315. }
  316. public void RegisterStartupScript (Type type, string key, string script, bool addScriptTags)
  317. {
  318. if (type == null)
  319. throw new ArgumentNullException ("type");
  320. RegisterScript (ref startupScriptBlocks, type, key, script, addScriptTags);
  321. }
  322. public void RegisterClientScriptInclude (string key, string url)
  323. {
  324. RegisterClientScriptInclude (GetType (), key, url);
  325. }
  326. public void RegisterClientScriptInclude (Type type, string key, string url)
  327. {
  328. if (type == null)
  329. throw new ArgumentNullException ("type");
  330. if (url == null || url.Length == 0)
  331. throw new ArgumentException ("url");
  332. RegisterScript (ref clientScriptBlocks, type, "include-" + key, url, ScriptEntryFormat.Include);
  333. }
  334. #if NET_2_0
  335. public void RegisterClientScriptResource (Type type, string resourceName)
  336. {
  337. RegisterScript (ref clientScriptBlocks, type, "resource-" + resourceName, GetWebResourceUrl (type, resourceName), ScriptEntryFormat.Include);
  338. }
  339. public void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue)
  340. {
  341. RegisterExpandoAttribute (controlId, attributeName, attributeValue, true);
  342. }
  343. public void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue, bool encode)
  344. {
  345. if (controlId == null)
  346. throw new ArgumentNullException ("controlId");
  347. if (attributeName == null)
  348. throw new ArgumentNullException ("attributeName");
  349. if (expandoAttributes == null)
  350. expandoAttributes = new Hashtable ();
  351. ListDictionary list = (ListDictionary)expandoAttributes [controlId];
  352. if (list == null) {
  353. list = new ListDictionary ();
  354. expandoAttributes [controlId] = list;
  355. }
  356. list.Add (attributeName, encode ? StrUtils.EscapeQuotesAndBackslashes (attributeValue) : attributeValue);
  357. }
  358. private void EnsureEventValidationArray ()
  359. {
  360. if (eventValidationValues == null)
  361. eventValidationValues = new int [64];
  362. int len = eventValidationValues.Length;
  363. if (eventValidationPos >= len) {
  364. int [] tmp = new int [len * 2];
  365. Array.Copy (eventValidationValues, tmp, len);
  366. eventValidationValues = tmp;
  367. }
  368. }
  369. internal void ResetEventValidationState ()
  370. {
  371. eventValidationPos = 0;
  372. }
  373. // Implemented following the description in http://odetocode.com/Blogs/scott/archive/2006/03/20/3145.aspx
  374. private int CalculateEventHash (string uniqueId, string argument)
  375. {
  376. int uniqueIdHash = uniqueId.GetHashCode ();
  377. int argumentHash = String.IsNullOrEmpty (argument) ? 0 : argument.GetHashCode ();
  378. return (uniqueIdHash ^ argumentHash);
  379. }
  380. public void RegisterForEventValidation (PostBackOptions options)
  381. {
  382. // MS.NET does not check for options == null, so we won't too...
  383. RegisterForEventValidation (options.TargetControl.UniqueID, options.Argument);
  384. }
  385. public void RegisterForEventValidation (string uniqueId)
  386. {
  387. RegisterForEventValidation (uniqueId, null);
  388. }
  389. public void RegisterForEventValidation (string uniqueId, string argument)
  390. {
  391. if (!page.EnableEventValidation)
  392. return;
  393. if (uniqueId == null || uniqueId.Length == 0)
  394. return;
  395. if (page.IsCallback)
  396. _hasRegisteredForEventValidationOnCallback = true;
  397. else if (page.LifeCycle < PageLifeCycle.Render)
  398. throw new InvalidOperationException ("RegisterForEventValidation may only be called from the Render method");
  399. EnsureEventValidationArray ();
  400. int hash = CalculateEventHash (uniqueId, argument);
  401. for (int i = 0; i < eventValidationPos; i++)
  402. if (eventValidationValues [i] == hash)
  403. return;
  404. eventValidationValues [eventValidationPos++] = hash;
  405. }
  406. public void ValidateEvent (string uniqueId)
  407. {
  408. ValidateEvent (uniqueId, null);
  409. }
  410. public void ValidateEvent (string uniqueId, string argument)
  411. {
  412. if (uniqueId == null || uniqueId.Length == 0)
  413. throw new ArgumentException ("must not be null or empty", "uniqueId");
  414. if (!page.EnableEventValidation)
  415. return;
  416. if (eventValidationValues == null)
  417. goto bad;
  418. int hash = CalculateEventHash (uniqueId, argument);
  419. for (int i = 0; i < eventValidationValues.Length; i++)
  420. if (eventValidationValues [i] == hash)
  421. return;
  422. bad:
  423. throw new ArgumentException ("Invalid postback or callback argument. Event validation is enabled using <pages enableEventValidation=\"true\"/> in configuration or <%@ Page EnableEventValidation=\"true\" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation.");
  424. }
  425. #endif
  426. void WriteScripts (HtmlTextWriter writer, ScriptEntry scriptList)
  427. {
  428. if (scriptList == null)
  429. return;
  430. writer.WriteLine ();
  431. while (scriptList != null) {
  432. switch (scriptList.Format) {
  433. case ScriptEntryFormat.AddScriptTag:
  434. EnsureBeginScriptBlock (writer);
  435. writer.Write (scriptList.Script);
  436. break;
  437. case ScriptEntryFormat.Include:
  438. EnsureEndScriptBlock (writer);
  439. WriteClientScriptInclude (writer, scriptList.Script);
  440. break;
  441. default:
  442. EnsureEndScriptBlock (writer);
  443. writer.WriteLine (scriptList.Script);
  444. break;
  445. }
  446. scriptList = scriptList.Next;
  447. }
  448. EnsureEndScriptBlock (writer);
  449. }
  450. bool _scriptTagOpened;
  451. void EnsureBeginScriptBlock (HtmlTextWriter writer) {
  452. if (!_scriptTagOpened) {
  453. WriteBeginScriptBlock (writer);
  454. _scriptTagOpened = true;
  455. }
  456. }
  457. void EnsureEndScriptBlock (HtmlTextWriter writer) {
  458. if (_scriptTagOpened) {
  459. WriteEndScriptBlock (writer);
  460. _scriptTagOpened = false;
  461. }
  462. }
  463. #if NET_2_0
  464. internal void RestoreEventValidationState (string fieldValue)
  465. {
  466. if (!page.EnableEventValidation || fieldValue == null || fieldValue.Length == 0)
  467. return;
  468. IStateFormatter fmt = page.GetFormatter ();
  469. eventValidationValues = (int []) fmt.Deserialize (fieldValue);
  470. eventValidationPos = eventValidationValues.Length;
  471. }
  472. internal void SaveEventValidationState ()
  473. {
  474. if (!page.EnableEventValidation)
  475. return;
  476. string eventValidation = GetEventValidationStateFormatted ();
  477. if (eventValidation == null)
  478. return;
  479. RegisterHiddenField (EventStateFieldName, eventValidation);
  480. }
  481. internal string GetEventValidationStateFormatted ()
  482. {
  483. if (eventValidationValues == null || eventValidationValues.Length == 0)
  484. return null;
  485. if(page.IsCallback && !_hasRegisteredForEventValidationOnCallback)
  486. return null;
  487. IStateFormatter fmt = page.GetFormatter ();
  488. int [] array = new int [eventValidationPos];
  489. Array.Copy (eventValidationValues, array, eventValidationPos);
  490. return fmt.Serialize (array);
  491. }
  492. internal string EventStateFieldName
  493. {
  494. get { return "__EVENTVALIDATION"; }
  495. }
  496. internal void WriteExpandoAttributes (HtmlTextWriter writer)
  497. {
  498. if (expandoAttributes == null)
  499. return;
  500. writer.WriteLine ();
  501. WriteBeginScriptBlock (writer);
  502. foreach (string controlId in expandoAttributes.Keys) {
  503. writer.WriteLine ("var {0} = document.all ? document.all [\"{0}\"] : document.getElementById (\"{0}\");", controlId);
  504. ListDictionary attrs = (ListDictionary) expandoAttributes [controlId];
  505. foreach (string attributeName in attrs.Keys) {
  506. writer.WriteLine ("{0}.{1} = \"{2}\";", controlId, attributeName, attrs [attributeName]);
  507. }
  508. }
  509. WriteEndScriptBlock (writer);
  510. writer.WriteLine ();
  511. }
  512. #endif
  513. internal static void WriteBeginScriptBlock (HtmlTextWriter writer)
  514. {
  515. writer.WriteLine ("<script"+
  516. #if !NET_2_0
  517. " language=\"javascript\""+
  518. #endif
  519. " type=\"text/javascript\">");
  520. writer.WriteLine ("<!--");
  521. }
  522. internal static void WriteEndScriptBlock (HtmlTextWriter writer)
  523. {
  524. writer.WriteLine ("// -->");
  525. writer.WriteLine ("</script>");
  526. }
  527. internal void WriteHiddenFields (HtmlTextWriter writer)
  528. {
  529. if (hiddenFields == null)
  530. return;
  531. writer.RenderBeginTag (HtmlTextWriterTag.Div);
  532. foreach (string key in hiddenFields.Keys) {
  533. string value = hiddenFields [key] as string;
  534. writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" id=\"{0}\" value=\"{1}\" />", key, value);
  535. }
  536. writer.RenderEndTag (); // DIV
  537. hiddenFields = null;
  538. }
  539. internal void WriteClientScriptInclude (HtmlTextWriter writer, string path) {
  540. #if TARGET_J2EE
  541. if (!page.IsPortletRender)
  542. #endif
  543. writer.WriteLine ("<script src=\"{0}\" type=\"text/javascript\"></script>", path);
  544. #if TARGET_J2EE
  545. else {
  546. string scriptKey = "inc_" + path.GetHashCode ().ToString ("X");
  547. writer.WriteLine ("<script type=\"text/javascript\">");
  548. writer.WriteLine ("<!--");
  549. writer.WriteLine ("if (document.{0} == null) {{", scriptKey);
  550. writer.WriteLine ("\tdocument.{0} = true", scriptKey);
  551. writer.WriteLine ("\tdocument.write('<script src=\"{0}\" type=\"text/javascript\"><\\/script>'); }}", path);
  552. writer.WriteLine ("// -->");
  553. writer.WriteLine ("</script>");
  554. }
  555. #endif
  556. }
  557. internal void WriteClientScriptBlocks (HtmlTextWriter writer)
  558. {
  559. WriteScripts (writer, clientScriptBlocks);
  560. }
  561. internal void WriteStartupScriptBlocks (HtmlTextWriter writer)
  562. {
  563. WriteScripts (writer, startupScriptBlocks);
  564. }
  565. internal void WriteArrayDeclares (HtmlTextWriter writer)
  566. {
  567. if (registeredArrayDeclares != null) {
  568. writer.WriteLine();
  569. WriteBeginScriptBlock (writer);
  570. IDictionaryEnumerator arrayEnum = registeredArrayDeclares.GetEnumerator();
  571. while (arrayEnum.MoveNext()) {
  572. writer.Write("\tvar ");
  573. writer.Write(arrayEnum.Key);
  574. writer.Write(" = new Array(");
  575. IEnumerator arrayListEnum = ((ArrayList) arrayEnum.Value).GetEnumerator();
  576. bool isFirst = true;
  577. while (arrayListEnum.MoveNext()) {
  578. if (isFirst)
  579. isFirst = false;
  580. else
  581. writer.Write(", ");
  582. writer.Write(arrayListEnum.Current);
  583. }
  584. writer.WriteLine(");");
  585. #if TARGET_J2EE
  586. // in addition, add a form array declaration
  587. if (page.IsPortletRender) {
  588. writer.Write ("\t" + page.theForm + ".");
  589. writer.Write (arrayEnum.Key);
  590. writer.Write (" = ");
  591. writer.Write (arrayEnum.Key);
  592. writer.WriteLine (";");
  593. }
  594. #endif
  595. }
  596. WriteEndScriptBlock (writer);
  597. writer.WriteLine ();
  598. }
  599. }
  600. #if NET_2_0
  601. internal string GetClientValidationEvent (string validationGroup) {
  602. string eventScript = "if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate('" + validationGroup + "');";
  603. #if TARGET_J2EE
  604. if (page.IsPortletRender)
  605. return "if (typeof(SetValidatorContext) == 'function') SetValidatorContext ('" + page.theForm + "'); " + eventScript;
  606. #endif
  607. return eventScript;
  608. }
  609. #endif
  610. internal string GetClientValidationEvent ()
  611. {
  612. string eventScript = "if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate();";
  613. #if TARGET_J2EE
  614. if (page.IsPortletRender)
  615. return "if (typeof(SetValidatorContext) == 'function') SetValidatorContext ('" + page.theForm + "'); " + eventScript;
  616. #endif
  617. return eventScript;
  618. }
  619. internal string WriteSubmitStatements ()
  620. {
  621. if (submitStatements == null) return null;
  622. StringBuilder sb = new StringBuilder ();
  623. ScriptEntry entry = submitStatements;
  624. while (entry != null) {
  625. #if NET_2_0
  626. sb.Append (EnsureEndsWithSemicolon (entry.Script));
  627. #else
  628. sb.Append (entry.Script);
  629. #endif
  630. entry = entry.Next;
  631. }
  632. #if NET_2_0
  633. RegisterClientScriptBlock ("HtmlForm-OnSubmitStatemen",
  634. @"<script type=""text/javascript"">
  635. <!--
  636. " + page.theForm + @".WebForm_OnSubmit = function () {
  637. " + sb.ToString () + @"
  638. return true;
  639. }
  640. // -->
  641. </script>");
  642. return "javascript:return this.WebForm_OnSubmit();";
  643. #else
  644. return sb.ToString ();
  645. #endif
  646. }
  647. [MonoTODO ("optimize s.Replace")]
  648. internal static string GetScriptLiteral (object ob)
  649. {
  650. if (ob == null)
  651. return "null";
  652. else if (ob is string) {
  653. string s = (string)ob;
  654. s = s.Replace ("\\", "\\\\");
  655. s = s.Replace ("\"", "\\\"");
  656. return "\"" + s + "\"";
  657. } else if (ob is bool) {
  658. return ob.ToString ().ToLower (CultureInfo.InvariantCulture);
  659. } else {
  660. return ob.ToString ();
  661. }
  662. }
  663. sealed class ScriptEntry
  664. {
  665. public readonly Type Type;
  666. public readonly string Key;
  667. public readonly string Script;
  668. public readonly ScriptEntryFormat Format;
  669. public ScriptEntry Next;
  670. public ScriptEntry (Type type, string key, string script, ScriptEntryFormat format) {
  671. Key = key;
  672. Type = type;
  673. Script = script;
  674. Format = format;
  675. }
  676. }
  677. enum ScriptEntryFormat
  678. {
  679. None,
  680. AddScriptTag,
  681. Include,
  682. }
  683. #if NET_2_0
  684. // helper method
  685. internal static string EnsureEndsWithSemicolon (string value) {
  686. if (value != null && value.Length > 0 && value [value.Length - 1] != ';')
  687. return value += ";";
  688. return value;
  689. }
  690. #endif
  691. }
  692. }