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. Type previousPageType;
  74. string previousPageVirtualPath;
  75. #endif
  76. public PageParser ()
  77. {
  78. LoadConfigDefaults ();
  79. }
  80. internal PageParser (string virtualPath, string inputFile, HttpContext context)
  81. {
  82. #if NET_2_0
  83. this.VirtualPath = new VirtualPath (virtualPath);
  84. #endif
  85. Context = context;
  86. BaseVirtualDir = VirtualPathUtility.GetDirectory (virtualPath, false);
  87. InputFile = inputFile;
  88. SetBaseType (null);
  89. AddApplicationAssembly ();
  90. LoadConfigDefaults ();
  91. }
  92. #if NET_2_0
  93. internal PageParser (VirtualPath virtualPath, TextReader reader, HttpContext context)
  94. : this (virtualPath, null, reader, context)
  95. {
  96. }
  97. internal PageParser (VirtualPath virtualPath, string inputFile, TextReader reader, HttpContext context)
  98. {
  99. this.VirtualPath = virtualPath;
  100. Context = context;
  101. BaseVirtualDir = virtualPath.DirectoryNoNormalize;
  102. Reader = reader;
  103. if (String.IsNullOrEmpty (inputFile))
  104. InputFile = virtualPath.PhysicalPath;
  105. else
  106. InputFile = inputFile;
  107. SetBaseType (null);
  108. AddApplicationAssembly ();
  109. LoadConfigDefaults ();
  110. }
  111. #endif
  112. internal override void LoadConfigDefaults ()
  113. {
  114. base.LoadConfigDefaults ();
  115. #if NET_2_0
  116. PagesSection ps = PagesConfig;
  117. #else
  118. PagesConfiguration ps = PagesConfig;
  119. #endif
  120. notBuffer = !ps.Buffer;
  121. enableSessionState = ps.EnableSessionState;
  122. enableViewStateMac = ps.EnableViewStateMac;
  123. smartNavigation = ps.SmartNavigation;
  124. validateRequest = ps.ValidateRequest;
  125. #if NET_2_0
  126. masterPage = ps.MasterPageFile;
  127. if (masterPage.Length == 0)
  128. masterPage = null;
  129. enable_event_validation = ps.EnableEventValidation;
  130. maxPageStateFieldLength = ps.MaxPageStateFieldLength;
  131. theme = ps.Theme;
  132. if (theme.Length == 0)
  133. theme = null;
  134. styleSheetTheme = ps.StyleSheetTheme;
  135. if (styleSheetTheme.Length == 0)
  136. styleSheetTheme = null;
  137. maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
  138. #endif
  139. }
  140. public static IHttpHandler GetCompiledPageInstance (string virtualPath,
  141. string inputFile,
  142. HttpContext context)
  143. {
  144. #if NET_2_0
  145. bool isFake = false;
  146. if (!String.IsNullOrEmpty (inputFile))
  147. isFake = !inputFile.StartsWith (HttpRuntime.AppDomainAppPath);
  148. return BuildManager.CreateInstanceFromVirtualPath (new VirtualPath (virtualPath, inputFile, isFake), typeof (IHttpHandler)) as IHttpHandler;
  149. #else
  150. PageParser pp = new PageParser (virtualPath, inputFile, context);
  151. IHttpHandler h = (IHttpHandler) pp.GetCompiledInstance ();
  152. return h;
  153. #endif
  154. }
  155. internal override void ProcessMainAttributes (Hashtable atts)
  156. {
  157. // note: the 'enableSessionState' configuration property is
  158. // processed in a case-sensitive manner while the page-level
  159. // attribute is processed case-insensitive
  160. string enabless = GetString (atts, "EnableSessionState", null);
  161. if (enabless != null) {
  162. if (String.Compare (enabless, "readonly", true) == 0)
  163. enableSessionState = PagesEnableSessionState.ReadOnly;
  164. else if (String.Compare (enabless, "true", true) == 0)
  165. enableSessionState = PagesEnableSessionState.True;
  166. else if (String.Compare (enabless, "false", true) == 0)
  167. enableSessionState = PagesEnableSessionState.False;
  168. else
  169. ThrowParseException ("Invalid value for enableSessionState: " + enabless);
  170. }
  171. string cp = GetString (atts, "CodePage", null);
  172. if (cp != null) {
  173. if (responseEncoding != null)
  174. ThrowParseException ("CodePage and ResponseEncoding are " +
  175. "mutually exclusive.");
  176. int codepage = 0;
  177. try {
  178. codepage = (int) UInt32.Parse (cp);
  179. } catch {
  180. ThrowParseException ("Invalid value for CodePage: " + cp);
  181. }
  182. try {
  183. Encoding.GetEncoding (codepage);
  184. } catch {
  185. ThrowParseException ("Unsupported codepage: " + cp);
  186. }
  187. }
  188. responseEncoding = GetString (atts, "ResponseEncoding", null);
  189. if (responseEncoding != null) {
  190. if (codepage != -1)
  191. ThrowParseException ("CodePage and ResponseEncoding are " +
  192. "mutually exclusive.");
  193. try {
  194. Encoding.GetEncoding (responseEncoding);
  195. } catch {
  196. ThrowParseException ("Unsupported encoding: " + responseEncoding);
  197. }
  198. }
  199. contentType = GetString (atts, "ContentType", null);
  200. string lcidStr = GetString (atts, "LCID", null);
  201. if (lcidStr != null) {
  202. try {
  203. lcid = (int) UInt32.Parse (lcidStr);
  204. } catch {
  205. ThrowParseException ("Invalid value for LCID: " + lcid);
  206. }
  207. CultureInfo ci = null;
  208. try {
  209. ci = new CultureInfo (lcid);
  210. } catch {
  211. ThrowParseException ("Unsupported LCID: " + lcid);
  212. }
  213. if (ci.IsNeutralCulture) {
  214. string suggestedCulture = SuggestCulture (ci.Name);
  215. string fmt = "LCID attribute must be set to a non-neutral Culture.";
  216. if (suggestedCulture != null) {
  217. ThrowParseException (fmt + " Please try one of these: " +
  218. suggestedCulture);
  219. } else {
  220. ThrowParseException (fmt);
  221. }
  222. }
  223. }
  224. culture = GetString (atts, "Culture", null);
  225. if (culture != null) {
  226. if (lcidStr != null)
  227. ThrowParseException ("Culture and LCID are mutually exclusive.");
  228. CultureInfo ci = null;
  229. try {
  230. #if NET_2_0
  231. if (!culture.StartsWith ("auto"))
  232. #endif
  233. ci = new CultureInfo (culture);
  234. } catch {
  235. ThrowParseException ("Unsupported Culture: " + culture);
  236. }
  237. if (ci != null && ci.IsNeutralCulture) {
  238. string suggestedCulture = SuggestCulture (culture);
  239. string fmt = "Culture attribute must be set to a non-neutral Culture.";
  240. if (suggestedCulture != null)
  241. ThrowParseException (fmt +
  242. " Please try one of these: " + suggestedCulture);
  243. else
  244. ThrowParseException (fmt);
  245. }
  246. }
  247. uiculture = GetString (atts, "UICulture", null);
  248. if (uiculture != null) {
  249. CultureInfo ci = null;
  250. try {
  251. #if NET_2_0
  252. if (!uiculture.StartsWith ("auto"))
  253. #endif
  254. ci = new CultureInfo (uiculture);
  255. } catch {
  256. ThrowParseException ("Unsupported Culture: " + uiculture);
  257. }
  258. if (ci != null && ci.IsNeutralCulture) {
  259. string suggestedCulture = SuggestCulture (uiculture);
  260. string fmt = "UICulture attribute must be set to a non-neutral Culture.";
  261. if (suggestedCulture != null)
  262. ThrowParseException (fmt +
  263. " Please try one of these: " + suggestedCulture);
  264. else
  265. ThrowParseException (fmt);
  266. }
  267. }
  268. string tracestr = GetString (atts, "Trace", null);
  269. if (tracestr != null) {
  270. haveTrace = true;
  271. atts ["Trace"] = tracestr;
  272. trace = GetBool (atts, "Trace", false);
  273. }
  274. string tracemodes = GetString (atts, "TraceMode", null);
  275. if (tracemodes != null) {
  276. bool valid = true;
  277. try {
  278. tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
  279. } catch {
  280. valid = false;
  281. }
  282. if (!valid || tracemode == TraceMode.Default)
  283. ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
  284. "one of the following values: SortByTime, SortByCategory.");
  285. }
  286. errorPage = GetString (atts, "ErrorPage", null);
  287. validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
  288. clientTarget = GetString (atts, "ClientTarget", null);
  289. if (clientTarget != null) {
  290. clientTarget = clientTarget.Trim ();
  291. #if NET_2_0
  292. ClientTargetSection sec = GetConfigSection <ClientTargetSection> ("system.web/clientTarget");
  293. ClientTarget ct = null;
  294. if ((ct = sec.ClientTargets [clientTarget]) == null)
  295. clientTarget = clientTarget.ToLower (CultureInfo.InvariantCulture);
  296. if (ct == null && (ct = sec.ClientTargets [clientTarget]) == null) {
  297. ThrowParseException (String.Format (
  298. "ClientTarget '{0}' is an invalid alias. See the " +
  299. "documentation for <clientTarget> config. section.",
  300. clientTarget));
  301. }
  302. clientTarget = ct.UserAgent;
  303. #else
  304. NameValueCollection coll;
  305. coll = (NameValueCollection) HttpContext.GetAppConfig ("system.web/clientTarget");
  306. object ct = null;
  307. if (coll != null) {
  308. ct = coll [clientTarget];
  309. if (ct == null)
  310. ct = coll [clientTarget.ToLower ()];
  311. }
  312. if (ct == null) {
  313. ThrowParseException (String.Format (
  314. "ClientTarget '{0}' is an invalid alias. See the " +
  315. "documentation for <clientTarget> config. section.",
  316. clientTarget));
  317. }
  318. clientTarget = (string) ct;
  319. #endif
  320. }
  321. notBuffer = !GetBool (atts, "Buffer", true);
  322. #if NET_2_0
  323. async = GetBool (atts, "Async", false);
  324. string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
  325. if (asyncTimeoutVal != null) {
  326. try {
  327. asyncTimeout = Int32.Parse (asyncTimeoutVal);
  328. } catch (Exception) {
  329. ThrowParseException ("AsyncTimeout must be an integer value");
  330. }
  331. }
  332. masterPage = GetString (atts, "MasterPageFile", masterPage);
  333. if (!String.IsNullOrEmpty (masterPage)) {
  334. if (!HostingEnvironment.VirtualPathProvider.FileExists (masterPage))
  335. ThrowParseFileNotFound (masterPage);
  336. AddDependency (masterPage);
  337. }
  338. title = GetString(atts, "Title", null);
  339. theme = GetString (atts, "Theme", theme);
  340. styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
  341. enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
  342. maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
  343. #endif
  344. // Ignored by now
  345. GetString (atts, "EnableViewStateMac", null);
  346. GetString (atts, "SmartNavigation", null);
  347. base.ProcessMainAttributes (atts);
  348. }
  349. #if NET_2_0
  350. internal override void AddDirective (string directive, Hashtable atts)
  351. {
  352. bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
  353. bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
  354. StringComparison.OrdinalIgnoreCase) == 0;
  355. string typeName = null;
  356. string virtualPath = null;
  357. Type type = null;
  358. if (isMasterType || isPreviousPageType) {
  359. PageParserFilter pfilter = PageParserFilter;
  360. if (pfilter != null)
  361. pfilter.PreprocessDirective (directive.ToLower (CultureInfo.InvariantCulture), atts);
  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 Type PreviousPageType {
  518. get {
  519. if (previousPageType == null && !String.IsNullOrEmpty (previousPageVirtualPath)) {
  520. string mappedPath = MapPath (previousPageVirtualPath);
  521. previousPageType = GetCompiledPageType (previousPageVirtualPath, mappedPath, HttpContext.Current);
  522. }
  523. return previousPageType;
  524. }
  525. }
  526. #endif
  527. }
  528. }