ClientScriptManager.cs 25 KB

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