ClientScriptManager.cs 25 KB

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