2 // System.Web.UI.PageParser
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
8 // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
30 using System.Collections;
31 using System.Collections.Specialized;
32 using System.Globalization;
33 using System.Security.Permissions;
35 using System.Web.Compilation;
36 using System.Web.Configuration;
37 using System.Web.Hosting;
38 using System.Web.Util;
41 namespace System.Web.UI
43 // CAS - no InheritanceDemand here as the class is sealed
44 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
45 public sealed class PageParser : TemplateControlParser
47 PagesEnableSessionState enableSessionState = PagesEnableSessionState.True;
48 bool enableViewStateMac = true;
53 TraceMode tracemode = TraceMode.Default;
54 string responseEncoding;
64 int asyncTimeout = -1;
67 string masterVirtualPath;
70 string styleSheetTheme;
71 bool enable_event_validation;
72 bool maintainScrollPositionOnPostBack;
73 int maxPageStateFieldLength = -1;
74 Type previousPageType;
75 string previousPageVirtualPath;
79 LoadConfigDefaults ();
82 internal PageParser (string virtualPath, string inputFile, HttpContext context)
84 this.VirtualPath = new VirtualPath (virtualPath);
86 BaseVirtualDir = VirtualPathUtility.GetDirectory (virtualPath, false);
87 InputFile = inputFile;
89 AddApplicationAssembly ();
90 LoadConfigDefaults ();
93 internal PageParser (VirtualPath virtualPath, TextReader reader, HttpContext context)
94 : this (virtualPath, null, reader, context)
98 internal PageParser (VirtualPath virtualPath, string inputFile, TextReader reader, HttpContext context)
100 this.VirtualPath = virtualPath;
102 BaseVirtualDir = virtualPath.DirectoryNoNormalize;
104 if (String.IsNullOrEmpty (inputFile))
105 InputFile = virtualPath.PhysicalPath;
107 InputFile = inputFile;
109 AddApplicationAssembly ();
110 LoadConfigDefaults ();
113 internal override void LoadConfigDefaults ()
115 base.LoadConfigDefaults ();
116 PagesSection ps = PagesConfig;
118 notBuffer = !ps.Buffer;
119 enableSessionState = ps.EnableSessionState;
120 enableViewStateMac = ps.EnableViewStateMac;
121 smartNavigation = ps.SmartNavigation;
122 validateRequest = ps.ValidateRequest;
123 masterPage = ps.MasterPageFile;
124 if (masterPage.Length == 0)
126 enable_event_validation = ps.EnableEventValidation;
127 maxPageStateFieldLength = ps.MaxPageStateFieldLength;
129 if (theme.Length == 0)
131 styleSheetTheme = ps.StyleSheetTheme;
132 if (styleSheetTheme.Length == 0)
133 styleSheetTheme = null;
134 maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
137 public static IHttpHandler GetCompiledPageInstance (string virtualPath, string inputFile, HttpContext context)
141 if (!String.IsNullOrEmpty (inputFile))
142 isFake = !inputFile.StartsWith (HttpRuntime.AppDomainAppPath);
144 return BuildManager.CreateInstanceFromVirtualPath (new VirtualPath (virtualPath, inputFile, isFake), typeof (IHttpHandler)) as IHttpHandler;
147 internal override void ProcessMainAttributes (Hashtable atts)
149 // note: the 'enableSessionState' configuration property is
150 // processed in a case-sensitive manner while the page-level
151 // attribute is processed case-insensitive
152 string enabless = GetString (atts, "EnableSessionState", null);
153 if (enabless != null) {
154 if (String.Compare (enabless, "readonly", true, Helpers.InvariantCulture) == 0)
155 enableSessionState = PagesEnableSessionState.ReadOnly;
156 else if (String.Compare (enabless, "true", true, Helpers.InvariantCulture) == 0)
157 enableSessionState = PagesEnableSessionState.True;
158 else if (String.Compare (enabless, "false", true, Helpers.InvariantCulture) == 0)
159 enableSessionState = PagesEnableSessionState.False;
161 ThrowParseException ("Invalid value for enableSessionState: " + enabless);
164 string cp = GetString (atts, "CodePage", null);
166 if (responseEncoding != null)
167 ThrowParseException ("CodePage and ResponseEncoding are " +
168 "mutually exclusive.");
172 codepage = (int) UInt32.Parse (cp);
174 ThrowParseException ("Invalid value for CodePage: " + cp);
178 Encoding.GetEncoding (codepage);
180 ThrowParseException ("Unsupported codepage: " + cp);
184 responseEncoding = GetString (atts, "ResponseEncoding", null);
185 if (responseEncoding != null) {
187 ThrowParseException ("CodePage and ResponseEncoding are " +
188 "mutually exclusive.");
191 Encoding.GetEncoding (responseEncoding);
193 ThrowParseException ("Unsupported encoding: " + responseEncoding);
197 contentType = GetString (atts, "ContentType", null);
199 string lcidStr = GetString (atts, "LCID", null);
200 if (lcidStr != null) {
202 lcid = (int) UInt32.Parse (lcidStr);
204 ThrowParseException ("Invalid value for LCID: " + lcid);
207 CultureInfo ci = null;
209 ci = new CultureInfo (lcid);
211 ThrowParseException ("Unsupported LCID: " + lcid);
214 if (ci.IsNeutralCulture) {
215 string suggestedCulture = SuggestCulture (ci.Name);
216 string fmt = "LCID attribute must be set to a non-neutral Culture.";
217 if (suggestedCulture != null) {
218 ThrowParseException (fmt + " Please try one of these: " +
221 ThrowParseException (fmt);
226 culture = GetString (atts, "Culture", null);
227 if (culture != null) {
229 ThrowParseException ("Culture and LCID are mutually exclusive.");
231 CultureInfo ci = null;
233 if (!culture.StartsWith ("auto"))
234 ci = new CultureInfo (culture);
236 ThrowParseException ("Unsupported Culture: " + culture);
239 if (ci != null && ci.IsNeutralCulture) {
240 string suggestedCulture = SuggestCulture (culture);
241 string fmt = "Culture attribute must be set to a non-neutral Culture.";
242 if (suggestedCulture != null)
243 ThrowParseException (fmt +
244 " Please try one of these: " + suggestedCulture);
246 ThrowParseException (fmt);
250 uiculture = GetString (atts, "UICulture", null);
251 if (uiculture != null) {
252 CultureInfo ci = null;
254 if (!uiculture.StartsWith ("auto"))
255 ci = new CultureInfo (uiculture);
257 ThrowParseException ("Unsupported Culture: " + uiculture);
260 if (ci != null && ci.IsNeutralCulture) {
261 string suggestedCulture = SuggestCulture (uiculture);
262 string fmt = "UICulture attribute must be set to a non-neutral Culture.";
263 if (suggestedCulture != null)
264 ThrowParseException (fmt +
265 " Please try one of these: " + suggestedCulture);
267 ThrowParseException (fmt);
271 string tracestr = GetString (atts, "Trace", null);
272 if (tracestr != null) {
274 atts ["Trace"] = tracestr;
275 trace = GetBool (atts, "Trace", false);
278 string tracemodes = GetString (atts, "TraceMode", null);
279 if (tracemodes != null) {
282 tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
287 if (!valid || tracemode == TraceMode.Default)
288 ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
289 "one of the following values: SortByTime, SortByCategory.");
292 errorPage = GetString (atts, "ErrorPage", null);
293 validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
294 clientTarget = GetString (atts, "ClientTarget", null);
295 if (clientTarget != null) {
296 clientTarget = clientTarget.Trim ();
297 ClientTargetSection sec = GetConfigSection <ClientTargetSection> ("system.web/clientTarget");
298 ClientTarget ct = null;
300 if ((ct = sec.ClientTargets [clientTarget]) == null)
301 clientTarget = clientTarget.ToLowerInvariant ();
303 if (ct == null && (ct = sec.ClientTargets [clientTarget]) == null) {
304 ThrowParseException (String.Format (
305 "ClientTarget '{0}' is an invalid alias. See the " +
306 "documentation for <clientTarget> config. section.",
309 clientTarget = ct.UserAgent;
312 notBuffer = !GetBool (atts, "Buffer", true);
313 async = GetBool (atts, "Async", false);
314 string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
315 if (asyncTimeoutVal != null) {
317 asyncTimeout = Int32.Parse (asyncTimeoutVal);
318 } catch (Exception) {
319 ThrowParseException ("AsyncTimeout must be an integer value");
323 masterPage = GetString (atts, "MasterPageFile", masterPage);
325 if (!String.IsNullOrEmpty (masterPage)) {
326 if (!HostingEnvironment.VirtualPathProvider.FileExists (masterPage))
327 ThrowParseFileNotFound (masterPage);
328 AddDependency (masterPage);
331 title = GetString(atts, "Title", null);
333 theme = GetString (atts, "Theme", theme);
334 styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
335 enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
336 maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
338 enableViewStateMac = GetBool (atts, "EnableViewStateMac", enableViewStateMac);
339 smartNavigation = GetBool (atts, "SmartNavigation", smartNavigation);
341 base.ProcessMainAttributes (atts);
344 internal override void AddDirective (string directive, Hashtable atts)
346 bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
347 bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
348 StringComparison.OrdinalIgnoreCase) == 0;
350 string typeName = null;
351 string virtualPath = null;
354 if (isMasterType || isPreviousPageType) {
355 PageParserFilter pfilter = PageParserFilter;
357 pfilter.PreprocessDirective (directive.ToLowerInvariant (), atts);
359 typeName = GetString (atts, "TypeName", null);
360 virtualPath = GetString (atts, "VirtualPath", null);
362 if (typeName != null && virtualPath != null)
363 ThrowParseException (
364 String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
365 if (typeName != null) {
366 type = LoadType (typeName);
368 ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
372 previousPageType = type;
373 } else if (!String.IsNullOrEmpty (virtualPath)) {
374 if (!HostingEnvironment.VirtualPathProvider.FileExists (virtualPath))
375 ThrowParseFileNotFound (virtualPath);
377 AddDependency (virtualPath);
379 masterVirtualPath = virtualPath;
381 previousPageVirtualPath = virtualPath;
383 ThrowParseException (String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
386 AddAssembly (type.Assembly, true);
388 base.AddDirective (directive, atts);
391 static string SuggestCulture (string culture)
393 string retval = null;
394 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
395 if (ci.Name.StartsWith (culture))
396 retval += ci.Name + " ";
401 public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
403 return BuildManager.GetCompiledType (virtualPath);
406 protected override Type CompileIntoType ()
408 AspGenerator generator = new AspGenerator (this);
409 return generator.GetCompiledType ();
412 internal bool EnableSessionState {
414 return enableSessionState == PagesEnableSessionState.True ||
415 ReadOnlySessionState;
419 internal bool EnableViewStateMac {
420 get { return enableViewStateMac; }
423 internal bool SmartNavigation {
424 get { return smartNavigation; }
427 internal bool ReadOnlySessionState {
429 return enableSessionState == PagesEnableSessionState.ReadOnly;
433 internal bool HaveTrace {
434 get { return haveTrace; }
437 internal bool Trace {
438 get { return trace; }
441 internal TraceMode TraceMode {
442 get { return tracemode; }
445 internal override string DefaultBaseTypeName {
446 get { return PagesConfig.PageBaseType; }
449 internal override string DefaultDirectiveName {
450 get { return "page"; }
453 internal string ResponseEncoding {
454 get { return responseEncoding; }
457 internal string ContentType {
458 get { return contentType; }
461 internal int CodePage {
462 get { return codepage; }
465 internal string Culture {
466 get { return culture; }
469 internal string UICulture {
470 get { return uiculture; }
477 internal string ErrorPage {
478 get { return errorPage; }
481 internal bool ValidateRequest {
482 get { return validateRequest; }
485 internal string ClientTarget {
486 get { return clientTarget; }
489 internal bool NotBuffer {
490 get { return notBuffer; }
493 internal bool Async {
494 get { return async; }
497 internal int AsyncTimeout {
498 get { return asyncTimeout; }
501 internal string Theme {
502 get { return theme; }
505 internal string StyleSheetTheme {
506 get { return styleSheetTheme; }
509 internal string MasterPageFile {
510 get { return masterPage; }
513 internal Type MasterType {
515 if (masterType == null && !String.IsNullOrEmpty (masterVirtualPath))
516 masterType = BuildManager.GetCompiledType (masterVirtualPath);
522 internal string Title {
523 get { return title; }
526 internal bool EnableEventValidation {
527 get { return enable_event_validation; }
530 internal bool MaintainScrollPositionOnPostBack {
531 get { return maintainScrollPositionOnPostBack; }
534 internal int MaxPageStateFieldLength {
535 get { return maxPageStateFieldLength; }
538 internal Type PreviousPageType {
540 if (previousPageType == null && !String.IsNullOrEmpty (previousPageVirtualPath)) {
541 string mappedPath = MapPath (previousPageVirtualPath);
542 previousPageType = GetCompiledPageType (previousPageVirtualPath, mappedPath, HttpContext.Current);
545 return previousPageType;