ClientScriptManager.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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. internal const string EventStateFieldName = "__EVENTVALIDATION";
  52. Hashtable registeredArrayDeclares;
  53. ScriptEntry clientScriptBlocks;
  54. ScriptEntry startupScriptBlocks;
  55. internal Hashtable hiddenFields;
  56. ScriptEntry submitStatements;
  57. Page page;
  58. #if NET_2_0
  59. int [] eventValidationValues;
  60. int eventValidationPos = 0;
  61. Hashtable expandoAttributes;
  62. bool _hasRegisteredForEventValidationOnCallback;
  63. #endif
  64. internal ClientScriptManager (Page page)
  65. {
  66. this.page = page;
  67. }
  68. #if !NET_2_0
  69. public string GetPostBackClientEvent (Control control, string argument)
  70. {
  71. return GetPostBackEventReference (control, argument);
  72. }
  73. #endif
  74. public string GetPostBackClientHyperlink (Control control, string argument)
  75. {
  76. return "javascript:" + GetPostBackEventReference (control, argument);
  77. }
  78. #if NET_2_0
  79. public string GetPostBackClientHyperlink (Control control, string argument, bool registerForEventValidation)
  80. {
  81. if (registerForEventValidation)
  82. RegisterForEventValidation (control.UniqueID, argument);
  83. return "javascript:" + GetPostBackEventReference (control, argument);
  84. }
  85. #endif
  86. #if !NET_2_0
  87. internal
  88. #else
  89. public
  90. #endif
  91. string GetPostBackEventReference (Control control, string argument)
  92. {
  93. if (control == null)
  94. throw new ArgumentNullException ("control");
  95. page.RequiresPostBackScript ();
  96. if(page.IsMultiForm)
  97. return String.Format ("{0}.__doPostBack('{1}','{2}')", page.theForm, control.UniqueID, argument);
  98. else
  99. return String.Format ("__doPostBack('{0}','{1}')", control.UniqueID, argument);
  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 (page.IsMultiForm)
  140. prefix += page.theForm + ".";
  141. #if TARGET_J2EE
  142. // Allow the page to transform ActionUrl to a portlet action url
  143. if (actionUrl != null && page.PortletNamespace != null) {
  144. actionUrl = page.CreateActionUrl(actionUrl);
  145. prefix += "Portal";
  146. }
  147. #endif
  148. return String.Format ("{0}WebForm_DoPostback({1},{2},{3},{4},{5},{6},{7},{8})",
  149. prefix,
  150. ClientScriptManager.GetScriptLiteral (options.TargetControl.UniqueID),
  151. ClientScriptManager.GetScriptLiteral (options.Argument),
  152. ClientScriptManager.GetScriptLiteral (actionUrl),
  153. ClientScriptManager.GetScriptLiteral (options.AutoPostBack),
  154. ClientScriptManager.GetScriptLiteral (options.PerformValidation),
  155. ClientScriptManager.GetScriptLiteral (options.TrackFocus),
  156. ClientScriptManager.GetScriptLiteral (options.ClientSubmit),
  157. ClientScriptManager.GetScriptLiteral (options.ValidationGroup)
  158. );
  159. }
  160. internal void RegisterWebFormClientScript ()
  161. {
  162. if (_webFormClientScriptRequired)
  163. return;
  164. page.RequiresPostBackScript ();
  165. _webFormClientScriptRequired = true;
  166. }
  167. bool _webFormClientScriptRendered;
  168. bool _webFormClientScriptRequired;
  169. internal void WriteWebFormClientScript (HtmlTextWriter writer) {
  170. if (!_webFormClientScriptRendered && _webFormClientScriptRequired) {
  171. writer.WriteLine ();
  172. WriteClientScriptInclude (writer, GetWebResourceUrl (typeof (Page), "webform.js"));
  173. WriteBeginScriptBlock (writer);
  174. writer.WriteLine ("WebForm_Initialize({0});", page.IsMultiForm ? page.theForm : "window");
  175. WriteEndScriptBlock (writer);
  176. _webFormClientScriptRendered = true;
  177. }
  178. }
  179. public string GetCallbackEventReference (Control control, string argument, string clientCallback, string context)
  180. {
  181. return GetCallbackEventReference (control, argument, clientCallback, context, null, false);
  182. }
  183. public string GetCallbackEventReference (Control control, string argument, string clientCallback, string context, bool useAsync)
  184. {
  185. return GetCallbackEventReference (control, argument, clientCallback, context, null, useAsync);
  186. }
  187. public string GetCallbackEventReference (Control control, string argument, string clientCallback, string context, string clientErrorCallback, bool useAsync)
  188. {
  189. if (control == null)
  190. throw new ArgumentNullException ("control");
  191. if(!(control is ICallbackEventHandler))
  192. throw new InvalidOperationException ("The control must implement the ICallbackEventHandler interface and provide a RaiseCallbackEvent method.");
  193. return GetCallbackEventReference ("'" + control.UniqueID + "'", argument, clientCallback, context, clientErrorCallback, useAsync);
  194. }
  195. public string GetCallbackEventReference (string target, string argument, string clientCallback, string context, string clientErrorCallback, bool useAsync)
  196. {
  197. RegisterWebFormClientScript ();
  198. return string.Format ("{6}WebForm_DoCallback({0},{1},{2},{3},{4},{5})", target, ((argument == null) ? "null" : argument), clientCallback, ((context == null) ? "null" : context), ((clientErrorCallback == null) ? "null" : clientErrorCallback), (useAsync ? "true" : "false"), (page.IsMultiForm ? page.theForm + "." : null));
  199. }
  200. #endif
  201. #if NET_2_0
  202. public
  203. #else
  204. internal
  205. #endif
  206. string GetWebResourceUrl(Type type, string resourceName)
  207. {
  208. if (type == null)
  209. throw new ArgumentNullException ("type");
  210. if (resourceName == null || resourceName.Length == 0)
  211. throw new ArgumentNullException ("type");
  212. return System.Web.Handlers.AssemblyResourceLoader.GetResourceUrl (type, resourceName);
  213. }
  214. public bool IsClientScriptBlockRegistered (string key)
  215. {
  216. return IsScriptRegistered (clientScriptBlocks, GetType(), key);
  217. }
  218. public bool IsClientScriptBlockRegistered (Type type, string key)
  219. {
  220. return IsScriptRegistered (clientScriptBlocks, type, key);
  221. }
  222. public bool IsStartupScriptRegistered (string key)
  223. {
  224. return IsScriptRegistered (startupScriptBlocks, GetType(), key);
  225. }
  226. public bool IsStartupScriptRegistered (Type type, string key)
  227. {
  228. return IsScriptRegistered (startupScriptBlocks, type, key);
  229. }
  230. public bool IsOnSubmitStatementRegistered (string key)
  231. {
  232. return IsScriptRegistered (submitStatements, GetType(), key);
  233. }
  234. public bool IsOnSubmitStatementRegistered (Type type, string key)
  235. {
  236. return IsScriptRegistered (submitStatements, type, key);
  237. }
  238. public bool IsClientScriptIncludeRegistered (string key)
  239. {
  240. return IsClientScriptIncludeRegistered (GetType (), key);
  241. }
  242. public bool IsClientScriptIncludeRegistered (Type type, string key)
  243. {
  244. return IsScriptRegistered (clientScriptBlocks, type, "include-" + key);
  245. }
  246. bool IsScriptRegistered (ScriptEntry scriptList, Type type, string key)
  247. {
  248. while (scriptList != null) {
  249. if (scriptList.Type == type && scriptList.Key == key)
  250. return true;
  251. scriptList = scriptList.Next;
  252. }
  253. return false;
  254. }
  255. public void RegisterArrayDeclaration (string arrayName, string arrayValue)
  256. {
  257. if (registeredArrayDeclares == null)
  258. registeredArrayDeclares = new Hashtable();
  259. if (!registeredArrayDeclares.ContainsKey (arrayName))
  260. registeredArrayDeclares.Add (arrayName, new ArrayList());
  261. ((ArrayList) registeredArrayDeclares[arrayName]).Add(arrayValue);
  262. }
  263. void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, bool addScriptTags)
  264. {
  265. RegisterScript (ref scriptList, type, key, script, addScriptTags ? ScriptEntryFormat.AddScriptTag : ScriptEntryFormat.None);
  266. }
  267. void RegisterScript (ref ScriptEntry scriptList, Type type, string key, string script, ScriptEntryFormat format)
  268. {
  269. ScriptEntry last = null;
  270. ScriptEntry entry = scriptList;
  271. while (entry != null) {
  272. if (entry.Type == type && entry.Key == key)
  273. return;
  274. last = entry;
  275. entry = entry.Next;
  276. }
  277. entry = new ScriptEntry (type, key, script, format);
  278. if (last != null) last.Next = entry;
  279. else scriptList = entry;
  280. }
  281. internal void RegisterClientScriptBlock (string key, string script)
  282. {
  283. RegisterScript (ref clientScriptBlocks, GetType(), key, script, false);
  284. }
  285. public void RegisterClientScriptBlock (Type type, string key, string script)
  286. {
  287. RegisterClientScriptBlock (type, key, script, false);
  288. }
  289. public void RegisterClientScriptBlock (Type type, string key, string script, bool addScriptTags)
  290. {
  291. if (type == null)
  292. throw new ArgumentNullException ("type");
  293. RegisterScript (ref clientScriptBlocks, type, key, script, addScriptTags);
  294. }
  295. public void RegisterHiddenField (string hiddenFieldName, string hiddenFieldInitialValue)
  296. {
  297. if (hiddenFields == null)
  298. hiddenFields = new Hashtable ();
  299. if (!hiddenFields.ContainsKey (hiddenFieldName))
  300. hiddenFields.Add (hiddenFieldName, hiddenFieldInitialValue);
  301. }
  302. internal void RegisterOnSubmitStatement (string key, string script)
  303. {
  304. RegisterScript (ref submitStatements, GetType (), key, script, false);
  305. }
  306. public void RegisterOnSubmitStatement (Type type, string key, string script)
  307. {
  308. if (type == null)
  309. throw new ArgumentNullException ("type");
  310. RegisterScript (ref submitStatements, type, key, script, false);
  311. }
  312. internal void RegisterStartupScript (string key, string script)
  313. {
  314. RegisterScript (ref startupScriptBlocks, GetType(), key, script, false);
  315. }
  316. public void RegisterStartupScript (Type type, string key, string script)
  317. {
  318. RegisterStartupScript (type, key, script, false);
  319. }
  320. public void RegisterStartupScript (Type type, string key, string script, bool addScriptTags)
  321. {
  322. if (type == null)
  323. throw new ArgumentNullException ("type");
  324. RegisterScript (ref startupScriptBlocks, type, key, script, addScriptTags);
  325. }
  326. public void RegisterClientScriptInclude (string key, string url)
  327. {
  328. RegisterClientScriptInclude (GetType (), key, url);
  329. }
  330. public void RegisterClientScriptInclude (Type type, string key, string url)
  331. {
  332. if (type == null)
  333. throw new ArgumentNullException ("type");
  334. if (url == null || url.Length == 0)
  335. throw new ArgumentException ("url");
  336. RegisterScript (ref clientScriptBlocks, type, "include-" + key, url, ScriptEntryFormat.Include);
  337. }
  338. #if NET_2_0
  339. public void RegisterClientScriptResource (Type type, string resourceName)
  340. {
  341. RegisterScript (ref clientScriptBlocks, type, "resource-" + resourceName, GetWebResourceUrl (type, resourceName), ScriptEntryFormat.Include);
  342. }
  343. public void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue)
  344. {
  345. RegisterExpandoAttribute (controlId, attributeName, attributeValue, true);
  346. }
  347. public void RegisterExpandoAttribute (string controlId, string attributeName, string attributeValue, bool encode)
  348. {
  349. if (controlId == null)
  350. throw new ArgumentNullException ("controlId");
  351. if (attributeName == null)
  352. throw new ArgumentNullException ("attributeName");
  353. if (expandoAttributes == null)
  354. expandoAttributes = new Hashtable ();
  355. ListDictionary list = (ListDictionary)expandoAttributes [controlId];
  356. if (list == null) {
  357. list = new ListDictionary ();
  358. expandoAttributes [controlId] = list;
  359. }
  360. list.Add (attributeName, encode ? StrUtils.EscapeQuotesAndBackslashes (attributeValue) : attributeValue);
  361. }
  362. private void EnsureEventValidationArray ()
  363. {
  364. if (eventValidationValues == null || eventValidationValues.Length == 0)
  365. eventValidationValues = new int [64];
  366. int len = eventValidationValues.Length;
  367. if (eventValidationPos >= len) {
  368. int [] tmp = new int [len * 2];
  369. Array.Copy (eventValidationValues, tmp, len);
  370. eventValidationValues = tmp;
  371. }
  372. }
  373. internal void ResetEventValidationState ()
  374. {
  375. eventValidationPos = 0;
  376. }
  377. // Implemented following the description in http://odetocode.com/Blogs/scott/archive/2006/03/20/3145.aspx
  378. private int CalculateEventHash (string uniqueId, string argument)
  379. {
  380. int uniqueIdHash = uniqueId.GetHashCode ();
  381. int argumentHash = String.IsNullOrEmpty (argument) ? 0 : argument.GetHashCode ();
  382. return (uniqueIdHash ^ argumentHash);
  383. }
  384. public void RegisterForEventValidation (PostBackOptions options)
  385. {
  386. // MS.NET does not check for options == null, so we won't too...
  387. RegisterForEventValidation (options.TargetControl.UniqueID, options.Argument);
  388. }
  389. public void RegisterForEventValidation (string uniqueId)
  390. {
  391. RegisterForEventValidation (uniqueId, null);
  392. }
  393. public void RegisterForEventValidation (string uniqueId, string argument)
  394. {
  395. if (!page.EnableEventValidation)
  396. return;
  397. if (uniqueId == null || uniqueId.Length == 0)
  398. return;
  399. if (page.IsCallback)
  400. _hasRegisteredForEventValidationOnCallback = true;
  401. else if (page.LifeCycle < PageLifeCycle.Render)
  402. throw new InvalidOperationException ("RegisterForEventValidation may only be called from the Render method");
  403. EnsureEventValidationArray ();
  404. int hash = CalculateEventHash (uniqueId, argument);
  405. for (int i = 0; i < eventValidationPos; i++)
  406. if (eventValidationValues [i] == hash)
  407. return;
  408. eventValidationValues [eventValidationPos++] = hash;
  409. }
  410. public void ValidateEvent (string uniqueId)
  411. {
  412. ValidateEvent (uniqueId, null);
  413. }
  414. public void ValidateEvent (string uniqueId, string argument)
  415. {
  416. if (uniqueId == null || uniqueId.Length == 0)
  417. throw new ArgumentException ("must not be null or empty", "uniqueId");
  418. if (!page.EnableEventValidation)
  419. return;
  420. if (eventValidationValues == null)
  421. goto bad;
  422. int hash = CalculateEventHash (uniqueId, argument);
  423. for (int i = 0; i < eventValidationValues.Length; i++)
  424. if (eventValidationValues [i] == hash)
  425. return;
  426. bad:
  427. 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.");
  428. }
  429. #endif
  430. void WriteScripts (HtmlTextWriter writer, ScriptEntry scriptList)
  431. {
  432. if (scriptList == null)
  433. return;
  434. writer.WriteLine ();
  435. while (scriptList != null) {
  436. switch (scriptList.Format) {
  437. case ScriptEntryFormat.AddScriptTag:
  438. EnsureBeginScriptBlock (writer);
  439. writer.Write (scriptList.Script);
  440. break;
  441. case ScriptEntryFormat.Include:
  442. EnsureEndScriptBlock (writer);
  443. WriteClientScriptInclude (writer, scriptList.Script);
  444. break;
  445. default:
  446. EnsureEndScriptBlock (writer);
  447. writer.WriteLine (scriptList.Script);
  448. break;
  449. }
  450. scriptList = scriptList.Next;
  451. }
  452. EnsureEndScriptBlock (writer);
  453. }
  454. bool _scriptTagOpened;
  455. void EnsureBeginScriptBlock (HtmlTextWriter writer) {
  456. if (!_scriptTagOpened) {
  457. WriteBeginScriptBlock (writer);
  458. _scriptTagOpened = true;
  459. }
  460. }
  461. void EnsureEndScriptBlock (HtmlTextWriter writer) {
  462. if (_scriptTagOpened) {
  463. WriteEndScriptBlock (writer);
  464. _scriptTagOpened = false;
  465. }
  466. }
  467. #if NET_2_0
  468. internal void RestoreEventValidationState (string fieldValue)
  469. {
  470. if (!page.EnableEventValidation || fieldValue == null || fieldValue.Length == 0)
  471. return;
  472. IStateFormatter fmt = page.GetFormatter ();
  473. eventValidationValues = (int []) fmt.Deserialize (fieldValue);
  474. eventValidationPos = eventValidationValues.Length;
  475. }
  476. internal void SaveEventValidationState ()
  477. {
  478. if (!page.EnableEventValidation)
  479. return;
  480. string eventValidation = GetEventValidationStateFormatted ();
  481. if (eventValidation == null)
  482. return;
  483. RegisterHiddenField (EventStateFieldName, eventValidation);
  484. }
  485. internal string GetEventValidationStateFormatted ()
  486. {
  487. if (eventValidationValues == null || eventValidationValues.Length == 0)
  488. return null;
  489. if(page.IsCallback && !_hasRegisteredForEventValidationOnCallback)
  490. return null;
  491. IStateFormatter fmt = page.GetFormatter ();
  492. int [] array = new int [eventValidationPos];
  493. Array.Copy (eventValidationValues, array, eventValidationPos);
  494. return fmt.Serialize (array);
  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. #if NET_2_0
  514. internal const string SCRIPT_BLOCK_START = "//<![CDATA[";
  515. internal const string SCRIPT_BLOCK_END = "//]]>";
  516. #else
  517. internal const string SCRIPT_BLOCK_START = "<!--";
  518. internal const string SCRIPT_BLOCK_END ="// -->";
  519. #endif
  520. internal static void WriteBeginScriptBlock (HtmlTextWriter writer)
  521. {
  522. writer.WriteLine ("<script"+
  523. #if !NET_2_0
  524. " language=\"javascript\""+
  525. #endif
  526. " type=\"text/javascript\">");
  527. writer.WriteLine (SCRIPT_BLOCK_START);
  528. }
  529. internal static void WriteEndScriptBlock (HtmlTextWriter writer)
  530. {
  531. writer.WriteLine (SCRIPT_BLOCK_END);
  532. writer.WriteLine ("</script>");
  533. }
  534. internal void WriteHiddenFields (HtmlTextWriter writer)
  535. {
  536. if (hiddenFields == null)
  537. return;
  538. writer.RenderBeginTag (HtmlTextWriterTag.Div);
  539. foreach (string key in hiddenFields.Keys) {
  540. string value = hiddenFields [key] as string;
  541. writer.WriteLine ("<input type=\"hidden\" name=\"{0}\" id=\"{0}\" value=\"{1}\" />", key, HttpUtility.HtmlAttributeEncode (value));
  542. }
  543. writer.RenderEndTag (); // DIV
  544. hiddenFields = null;
  545. }
  546. internal void WriteClientScriptInclude (HtmlTextWriter writer, string path) {
  547. if (!page.IsMultiForm)
  548. writer.WriteLine ("<script src=\"{0}\" type=\"text/javascript\"></script>", path);
  549. else {
  550. string scriptKey = "inc_" + path.GetHashCode ().ToString ("X");
  551. writer.WriteLine ("<script type=\"text/javascript\">");
  552. writer.WriteLine (SCRIPT_BLOCK_START);
  553. writer.WriteLine ("if (document.{0} == null) {{", scriptKey);
  554. writer.WriteLine ("\tdocument.{0} = true", scriptKey);
  555. writer.WriteLine ("\tdocument.write('<script src=\"{0}\" type=\"text/javascript\"><\\/script>'); }}", path);
  556. writer.WriteLine (SCRIPT_BLOCK_END);
  557. writer.WriteLine ("</script>");
  558. }
  559. }
  560. internal void WriteClientScriptBlocks (HtmlTextWriter writer)
  561. {
  562. WriteScripts (writer, clientScriptBlocks);
  563. }
  564. internal void WriteStartupScriptBlocks (HtmlTextWriter writer)
  565. {
  566. WriteScripts (writer, startupScriptBlocks);
  567. }
  568. internal void WriteArrayDeclares (HtmlTextWriter writer)
  569. {
  570. if (registeredArrayDeclares != null) {
  571. writer.WriteLine();
  572. WriteBeginScriptBlock (writer);
  573. IDictionaryEnumerator arrayEnum = registeredArrayDeclares.GetEnumerator();
  574. while (arrayEnum.MoveNext()) {
  575. if (page.IsMultiForm)
  576. writer.Write ("\t" + page.theForm + ".");
  577. else
  578. writer.Write ("\tvar ");
  579. writer.Write(arrayEnum.Key);
  580. writer.Write(" = new Array(");
  581. IEnumerator arrayListEnum = ((ArrayList) arrayEnum.Value).GetEnumerator();
  582. bool isFirst = true;
  583. while (arrayListEnum.MoveNext()) {
  584. if (isFirst)
  585. isFirst = false;
  586. else
  587. writer.Write(", ");
  588. writer.Write(arrayListEnum.Current);
  589. }
  590. writer.WriteLine(");");
  591. }
  592. WriteEndScriptBlock (writer);
  593. writer.WriteLine ();
  594. }
  595. }
  596. #if NET_2_0
  597. internal string GetClientValidationEvent (string validationGroup) {
  598. if (page.IsMultiForm)
  599. return "if (typeof(" + page.theForm + ".Page_ClientValidate) == 'function') " + page.theForm + ".Page_ClientValidate('" + validationGroup + "');";
  600. return "if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate('" + validationGroup + "');";
  601. }
  602. #endif
  603. internal string GetClientValidationEvent ()
  604. {
  605. if (page.IsMultiForm)
  606. return "if (typeof(" + page.theForm + ".Page_ClientValidate) == 'function') " + page.theForm + ".Page_ClientValidate();";
  607. return "if (typeof(Page_ClientValidate) == 'function') Page_ClientValidate();";
  608. }
  609. internal string WriteSubmitStatements ()
  610. {
  611. if (submitStatements == null) return null;
  612. StringBuilder sb = new StringBuilder ();
  613. ScriptEntry entry = submitStatements;
  614. while (entry != null) {
  615. #if NET_2_0
  616. sb.Append (EnsureEndsWithSemicolon (entry.Script));
  617. #else
  618. sb.Append (entry.Script);
  619. #endif
  620. entry = entry.Next;
  621. }
  622. #if NET_2_0
  623. RegisterClientScriptBlock (GetType(), "HtmlForm-OnSubmitStatemen",
  624. @"
  625. " + (page.IsMultiForm ? page.theForm + "." : null) + @"WebForm_OnSubmit = function () {
  626. " + sb.ToString () + @"
  627. return true;
  628. }
  629. ", true);
  630. if (page.IsMultiForm)
  631. return "javascript:return " + page.theForm + ".WebForm_OnSubmit();";
  632. else
  633. return "javascript:return WebForm_OnSubmit();";
  634. #else
  635. return sb.ToString ();
  636. #endif
  637. }
  638. internal static string GetScriptLiteral (object ob)
  639. {
  640. if (ob == null)
  641. return "null";
  642. else if (ob is string) {
  643. string s = (string)ob;
  644. bool escape = false;
  645. int len = s.Length;
  646. for (int i = 0; i < len; i++)
  647. if (s [i] == '\\' || s [i] == '\"') {
  648. escape = true;
  649. break;
  650. }
  651. if (!escape)
  652. return string.Concat ("\"", s, "\"");
  653. StringBuilder sb = new StringBuilder (len + 10);
  654. sb.Append ('\"');
  655. for (int si = 0; si < len; si++) {
  656. if (s [si] == '\"')
  657. sb.Append ("\\\"");
  658. else if (s [si] == '\\')
  659. sb.Append ("\\\\");
  660. else
  661. sb.Append (s [si]);
  662. }
  663. sb.Append ('\"');
  664. return sb.ToString ();
  665. } else if (ob is bool) {
  666. return ob.ToString ().ToLower (CultureInfo.InvariantCulture);
  667. } else {
  668. return ob.ToString ();
  669. }
  670. }
  671. sealed class ScriptEntry
  672. {
  673. public readonly Type Type;
  674. public readonly string Key;
  675. public readonly string Script;
  676. public readonly ScriptEntryFormat Format;
  677. public ScriptEntry Next;
  678. public ScriptEntry (Type type, string key, string script, ScriptEntryFormat format) {
  679. Key = key;
  680. Type = type;
  681. Script = script;
  682. Format = format;
  683. }
  684. }
  685. enum ScriptEntryFormat
  686. {
  687. None,
  688. AddScriptTag,
  689. Include,
  690. }
  691. #if NET_2_0
  692. // helper method
  693. internal static string EnsureEndsWithSemicolon (string value) {
  694. if (value != null && value.Length > 0 && value [value.Length - 1] != ';')
  695. return value += ";";
  696. return value;
  697. }
  698. #endif
  699. }
  700. }