PageParser.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. //
  2. // System.Web.UI.PageParser
  3. //
  4. // Authors:
  5. // Gonzalo Paniagua Javier ([email protected])
  6. //
  7. // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
  8. // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System.Collections;
  30. using System.Collections.Specialized;
  31. using System.Globalization;
  32. using System.Security.Permissions;
  33. using System.Text;
  34. using System.Web.Compilation;
  35. using System.Web.Configuration;
  36. using System.Web.Hosting;
  37. using System.Web.Util;
  38. using System.IO;
  39. namespace System.Web.UI
  40. {
  41. // CAS - no InheritanceDemand here as the class is sealed
  42. [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
  43. public sealed class PageParser : TemplateControlParser
  44. {
  45. PagesEnableSessionState enableSessionState = PagesEnableSessionState.True;
  46. bool enableViewStateMac = true;
  47. bool smartNavigation;
  48. bool haveTrace;
  49. bool trace;
  50. bool notBuffer;
  51. TraceMode tracemode = TraceMode.Default;
  52. string responseEncoding;
  53. string contentType;
  54. int codepage = -1;
  55. int lcid = -1;
  56. string culture;
  57. string uiculture;
  58. string errorPage;
  59. bool validateRequest;
  60. string clientTarget;
  61. #if NET_2_0
  62. bool async;
  63. int asyncTimeout = -1;
  64. string masterPage;
  65. Type masterType;
  66. string masterVirtualPath;
  67. string title;
  68. string theme;
  69. string styleSheetTheme;
  70. bool enable_event_validation;
  71. bool maintainScrollPositionOnPostBack;
  72. int maxPageStateFieldLength = -1;
  73. string pageParserFilter = String.Empty;
  74. Type previousPageType;
  75. string previousPageVirtualPath;
  76. #endif
  77. public PageParser ()
  78. {
  79. LoadConfigDefaults ();
  80. }
  81. internal PageParser (string virtualPath, string inputFile, HttpContext context)
  82. {
  83. Context = context;
  84. BaseVirtualDir = VirtualPathUtility.GetDirectory (virtualPath, false);
  85. InputFile = inputFile;
  86. SetBaseType (null);
  87. AddApplicationAssembly ();
  88. LoadConfigDefaults ();
  89. #if NET_2_0
  90. this.VirtualPath = new VirtualPath (virtualPath);
  91. #endif
  92. }
  93. #if NET_2_0
  94. internal PageParser (string virtualPath, TextReader reader, HttpContext context)
  95. : this (virtualPath, null, reader, context)
  96. {
  97. }
  98. internal PageParser (string virtualPath, string inputFile, TextReader reader, HttpContext context)
  99. {
  100. Context = context;
  101. BaseVirtualDir = VirtualPathUtility.GetDirectory (virtualPath, false);
  102. Reader = reader;
  103. if (String.IsNullOrEmpty (inputFile)) {
  104. HttpRequest req = context != null ? context.Request : null;
  105. if (req != null)
  106. InputFile = req.MapPath (virtualPath);
  107. } else
  108. InputFile = inputFile;
  109. SetBaseType (null);
  110. AddApplicationAssembly ();
  111. LoadConfigDefaults ();
  112. #if NET_2_0
  113. this.VirtualPath = new VirtualPath (virtualPath);
  114. #endif
  115. }
  116. #endif
  117. internal override void LoadConfigDefaults ()
  118. {
  119. base.LoadConfigDefaults ();
  120. #if NET_2_0
  121. PagesSection ps = PagesConfig;
  122. #else
  123. PagesConfiguration ps = PagesConfig;
  124. #endif
  125. notBuffer = !ps.Buffer;
  126. enableSessionState = ps.EnableSessionState;
  127. enableViewStateMac = ps.EnableViewStateMac;
  128. smartNavigation = ps.SmartNavigation;
  129. validateRequest = ps.ValidateRequest;
  130. #if NET_2_0
  131. masterPage = ps.MasterPageFile;
  132. if (masterPage.Length == 0)
  133. masterPage = null;
  134. enable_event_validation = ps.EnableEventValidation;
  135. maxPageStateFieldLength = ps.MaxPageStateFieldLength;
  136. pageParserFilter = ps.PageParserFilterType;
  137. theme = ps.Theme;
  138. if (theme.Length == 0)
  139. theme = null;
  140. styleSheetTheme = ps.StyleSheetTheme;
  141. if (styleSheetTheme.Length == 0)
  142. styleSheetTheme = null;
  143. maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
  144. #endif
  145. }
  146. public static IHttpHandler GetCompiledPageInstance (string virtualPath,
  147. string inputFile,
  148. HttpContext context)
  149. {
  150. #if NET_2_0
  151. return BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (IHttpHandler)) as IHttpHandler;
  152. #else
  153. PageParser pp = new PageParser (virtualPath, inputFile, context);
  154. IHttpHandler h = (IHttpHandler) pp.GetCompiledInstance ();
  155. return h;
  156. #endif
  157. }
  158. internal override void ProcessMainAttributes (Hashtable atts)
  159. {
  160. // note: the 'enableSessionState' configuration property is
  161. // processed in a case-sensitive manner while the page-level
  162. // attribute is processed case-insensitive
  163. string enabless = GetString (atts, "EnableSessionState", null);
  164. if (enabless != null) {
  165. if (String.Compare (enabless, "readonly", true) == 0)
  166. enableSessionState = PagesEnableSessionState.ReadOnly;
  167. else if (String.Compare (enabless, "true", true) == 0)
  168. enableSessionState = PagesEnableSessionState.True;
  169. else if (String.Compare (enabless, "false", true) == 0)
  170. enableSessionState = PagesEnableSessionState.False;
  171. else
  172. ThrowParseException ("Invalid value for enableSessionState: " + enabless);
  173. }
  174. string cp = GetString (atts, "CodePage", null);
  175. if (cp != null) {
  176. if (responseEncoding != null)
  177. ThrowParseException ("CodePage and ResponseEncoding are " +
  178. "mutually exclusive.");
  179. int codepage = 0;
  180. try {
  181. codepage = (int) UInt32.Parse (cp);
  182. } catch {
  183. ThrowParseException ("Invalid value for CodePage: " + cp);
  184. }
  185. try {
  186. Encoding.GetEncoding (codepage);
  187. } catch {
  188. ThrowParseException ("Unsupported codepage: " + cp);
  189. }
  190. }
  191. responseEncoding = GetString (atts, "ResponseEncoding", null);
  192. if (responseEncoding != null) {
  193. if (codepage != -1)
  194. ThrowParseException ("CodePage and ResponseEncoding are " +
  195. "mutually exclusive.");
  196. try {
  197. Encoding.GetEncoding (responseEncoding);
  198. } catch {
  199. ThrowParseException ("Unsupported encoding: " + responseEncoding);
  200. }
  201. }
  202. contentType = GetString (atts, "ContentType", null);
  203. string lcidStr = GetString (atts, "LCID", null);
  204. if (lcidStr != null) {
  205. try {
  206. lcid = (int) UInt32.Parse (lcidStr);
  207. } catch {
  208. ThrowParseException ("Invalid value for LCID: " + lcid);
  209. }
  210. CultureInfo ci = null;
  211. try {
  212. ci = new CultureInfo (lcid);
  213. } catch {
  214. ThrowParseException ("Unsupported LCID: " + lcid);
  215. }
  216. if (ci.IsNeutralCulture) {
  217. string suggestedCulture = SuggestCulture (ci.Name);
  218. string fmt = "LCID attribute must be set to a non-neutral Culture.";
  219. if (suggestedCulture != null) {
  220. ThrowParseException (fmt + " Please try one of these: " +
  221. suggestedCulture);
  222. } else {
  223. ThrowParseException (fmt);
  224. }
  225. }
  226. }
  227. culture = GetString (atts, "Culture", null);
  228. if (culture != null) {
  229. if (lcidStr != null)
  230. ThrowParseException ("Culture and LCID are mutually exclusive.");
  231. CultureInfo ci = null;
  232. try {
  233. #if NET_2_0
  234. if (!culture.StartsWith ("auto"))
  235. #endif
  236. ci = new CultureInfo (culture);
  237. } catch {
  238. ThrowParseException ("Unsupported Culture: " + culture);
  239. }
  240. if (ci != null && ci.IsNeutralCulture) {
  241. string suggestedCulture = SuggestCulture (culture);
  242. string fmt = "Culture attribute must be set to a non-neutral Culture.";
  243. if (suggestedCulture != null)
  244. ThrowParseException (fmt +
  245. " Please try one of these: " + suggestedCulture);
  246. else
  247. ThrowParseException (fmt);
  248. }
  249. }
  250. uiculture = GetString (atts, "UICulture", null);
  251. if (uiculture != null) {
  252. CultureInfo ci = null;
  253. try {
  254. #if NET_2_0
  255. if (!uiculture.StartsWith ("auto"))
  256. #endif
  257. ci = new CultureInfo (uiculture);
  258. } catch {
  259. ThrowParseException ("Unsupported Culture: " + uiculture);
  260. }
  261. if (ci != null && ci.IsNeutralCulture) {
  262. string suggestedCulture = SuggestCulture (uiculture);
  263. string fmt = "UICulture attribute must be set to a non-neutral Culture.";
  264. if (suggestedCulture != null)
  265. ThrowParseException (fmt +
  266. " Please try one of these: " + suggestedCulture);
  267. else
  268. ThrowParseException (fmt);
  269. }
  270. }
  271. string tracestr = GetString (atts, "Trace", null);
  272. if (tracestr != null) {
  273. haveTrace = true;
  274. atts ["Trace"] = tracestr;
  275. trace = GetBool (atts, "Trace", false);
  276. }
  277. string tracemodes = GetString (atts, "TraceMode", null);
  278. if (tracemodes != null) {
  279. bool valid = true;
  280. try {
  281. tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
  282. } catch {
  283. valid = false;
  284. }
  285. if (!valid || tracemode == TraceMode.Default)
  286. ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
  287. "one of the following values: SortByTime, SortByCategory.");
  288. }
  289. errorPage = GetString (atts, "ErrorPage", null);
  290. validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
  291. clientTarget = GetString (atts, "ClientTarget", null);
  292. if (clientTarget != null) {
  293. clientTarget = clientTarget.Trim ();
  294. #if NET_2_0
  295. ClientTargetSection sec = (ClientTargetSection)WebConfigurationManager.GetSection ("system.web/clientTarget");
  296. ClientTarget ct = null;
  297. if ((ct = sec.ClientTargets [clientTarget]) == null)
  298. clientTarget = clientTarget.ToLower (CultureInfo.InvariantCulture);
  299. if (ct == null && (ct = sec.ClientTargets [clientTarget]) == null) {
  300. ThrowParseException (String.Format (
  301. "ClientTarget '{0}' is an invalid alias. See the " +
  302. "documentation for <clientTarget> config. section.",
  303. clientTarget));
  304. }
  305. clientTarget = ct.UserAgent;
  306. #else
  307. NameValueCollection coll;
  308. coll = (NameValueCollection) Context.GetConfig ("system.web/clientTarget");
  309. object ct = null;
  310. if (coll != null) {
  311. ct = coll [clientTarget];
  312. if (ct == null)
  313. ct = coll [clientTarget.ToLower ()];
  314. }
  315. if (ct == null) {
  316. ThrowParseException (String.Format (
  317. "ClientTarget '{0}' is an invalid alias. See the " +
  318. "documentation for <clientTarget> config. section.",
  319. clientTarget));
  320. }
  321. clientTarget = (string) ct;
  322. #endif
  323. }
  324. notBuffer = !GetBool (atts, "Buffer", true);
  325. #if NET_2_0
  326. async = GetBool (atts, "Async", false);
  327. string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
  328. if (asyncTimeoutVal != null) {
  329. try {
  330. asyncTimeout = Int32.Parse (asyncTimeoutVal);
  331. } catch (Exception) {
  332. ThrowParseException ("AsyncTimeout must be an integer value");
  333. }
  334. }
  335. masterPage = GetString (atts, "MasterPageFile", masterPage);
  336. if (!String.IsNullOrEmpty (masterPage)) {
  337. if (!HostingEnvironment.VirtualPathProvider.FileExists (masterPage))
  338. ThrowParseFileNotFound (masterPage);
  339. AddDependency (masterPage);
  340. }
  341. title = GetString(atts, "Title", null);
  342. theme = GetString (atts, "Theme", theme);
  343. styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
  344. enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
  345. maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
  346. #endif
  347. // Ignored by now
  348. GetString (atts, "EnableViewStateMac", null);
  349. GetString (atts, "SmartNavigation", null);
  350. base.ProcessMainAttributes (atts);
  351. }
  352. #if NET_2_0
  353. internal override void AddDirective (string directive, Hashtable atts)
  354. {
  355. bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
  356. bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
  357. StringComparison.OrdinalIgnoreCase) == 0;
  358. string typeName = null;
  359. string virtualPath = null;
  360. Type type = null;
  361. if (isMasterType || isPreviousPageType) {
  362. typeName = GetString (atts, "TypeName", null);
  363. virtualPath = GetString (atts, "VirtualPath", null);
  364. if (typeName != null && virtualPath != null)
  365. ThrowParseException (
  366. String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
  367. if (typeName != null) {
  368. type = LoadType (typeName);
  369. if (type == null)
  370. ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
  371. if (isMasterType)
  372. masterType = type;
  373. else
  374. previousPageType = type;
  375. } else if (!String.IsNullOrEmpty (virtualPath)) {
  376. if (!HostingEnvironment.VirtualPathProvider.FileExists (virtualPath))
  377. ThrowParseFileNotFound (virtualPath);
  378. AddDependency (virtualPath);
  379. if (isMasterType)
  380. masterVirtualPath = virtualPath;
  381. else
  382. previousPageVirtualPath = virtualPath;
  383. } else
  384. ThrowParseException (String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
  385. if (type != null)
  386. AddAssembly (type.Assembly, true);
  387. } else
  388. base.AddDirective (directive, atts);
  389. }
  390. #endif
  391. static string SuggestCulture (string culture)
  392. {
  393. string retval = null;
  394. foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
  395. if (ci.Name.StartsWith (culture))
  396. retval += ci.Name + " ";
  397. }
  398. return retval;
  399. }
  400. public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
  401. {
  402. #if NET_2_0
  403. return BuildManager.GetCompiledType (virtualPath);
  404. #else
  405. PageParser pp = new PageParser (virtualPath, inputFile, context);
  406. return pp.CompileIntoType ();
  407. #endif
  408. }
  409. protected override Type CompileIntoType ()
  410. {
  411. AspGenerator generator = new AspGenerator (this);
  412. return generator.GetCompiledType ();
  413. }
  414. internal bool EnableSessionState {
  415. get {
  416. return enableSessionState == PagesEnableSessionState.True ||
  417. ReadOnlySessionState;
  418. }
  419. }
  420. internal bool EnableViewStateMac {
  421. get { return enableViewStateMac; }
  422. }
  423. internal bool SmartNavigation {
  424. get { return smartNavigation; }
  425. }
  426. internal bool ReadOnlySessionState {
  427. get {
  428. return enableSessionState == PagesEnableSessionState.ReadOnly;
  429. }
  430. }
  431. internal bool HaveTrace {
  432. get { return haveTrace; }
  433. }
  434. internal bool Trace {
  435. get { return trace; }
  436. }
  437. internal TraceMode TraceMode {
  438. get { return tracemode; }
  439. }
  440. #if NET_2_0
  441. internal override string DefaultBaseTypeName {
  442. get { return PagesConfig.PageBaseType; }
  443. }
  444. #else
  445. internal override string DefaultBaseTypeName {
  446. get { return "System.Web.UI.Page"; }
  447. }
  448. #endif
  449. internal override string DefaultDirectiveName {
  450. get { return "page"; }
  451. }
  452. internal string ResponseEncoding {
  453. get { return responseEncoding; }
  454. }
  455. internal string ContentType {
  456. get { return contentType; }
  457. }
  458. internal int CodePage {
  459. get { return codepage; }
  460. }
  461. internal string Culture {
  462. get { return culture; }
  463. }
  464. internal string UICulture {
  465. get { return uiculture; }
  466. }
  467. internal int LCID {
  468. get { return lcid; }
  469. }
  470. internal string ErrorPage {
  471. get { return errorPage; }
  472. }
  473. internal bool ValidateRequest {
  474. get { return validateRequest; }
  475. }
  476. internal string ClientTarget {
  477. get { return clientTarget; }
  478. }
  479. internal bool NotBuffer {
  480. get { return notBuffer; }
  481. }
  482. #if NET_2_0
  483. internal bool Async {
  484. get { return async; }
  485. }
  486. internal int AsyncTimeout {
  487. get { return asyncTimeout; }
  488. }
  489. internal string Theme {
  490. get { return theme; }
  491. }
  492. internal string StyleSheetTheme {
  493. get { return styleSheetTheme; }
  494. }
  495. internal string MasterPageFile {
  496. get { return masterPage; }
  497. }
  498. internal Type MasterType {
  499. get {
  500. if (masterType == null && !String.IsNullOrEmpty (masterVirtualPath))
  501. masterType = BuildManager.GetCompiledType (masterVirtualPath);
  502. return masterType;
  503. }
  504. }
  505. internal string Title {
  506. get { return title; }
  507. }
  508. internal bool EnableEventValidation {
  509. get { return enable_event_validation; }
  510. }
  511. internal bool MaintainScrollPositionOnPostBack {
  512. get { return maintainScrollPositionOnPostBack; }
  513. }
  514. internal int MaxPageStateFieldLength {
  515. get { return maxPageStateFieldLength; }
  516. }
  517. internal string PageParserFilterType {
  518. get { return pageParserFilter; }
  519. }
  520. internal Type PreviousPageType {
  521. get {
  522. if (previousPageType == null && !String.IsNullOrEmpty (previousPageVirtualPath)) {
  523. string mappedPath = MapPath (previousPageVirtualPath);
  524. previousPageType = GetCompiledPageType (previousPageVirtualPath, mappedPath, HttpContext.Current);
  525. }
  526. return previousPageType;
  527. }
  528. }
  529. #endif
  530. }
  531. }