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);
339 GetString (atts, "EnableViewStateMac", null);
340 GetString (atts, "SmartNavigation", null);
342 base.ProcessMainAttributes (atts);
345 internal override void AddDirective (string directive, Hashtable atts)
347 bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
348 bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
349 StringComparison.OrdinalIgnoreCase) == 0;
351 string typeName = null;
352 string virtualPath = null;
355 if (isMasterType || isPreviousPageType) {
356 PageParserFilter pfilter = PageParserFilter;
358 pfilter.PreprocessDirective (directive.ToLowerInvariant (), atts);
360 typeName = GetString (atts, "TypeName", null);
361 virtualPath = GetString (atts, "VirtualPath", null);
363 if (typeName != null && virtualPath != null)
364 ThrowParseException (
365 String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
366 if (typeName != null) {
367 type = LoadType (typeName);
369 ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
373 previousPageType = type;
374 } else if (!String.IsNullOrEmpty (virtualPath)) {
375 if (!HostingEnvironment.VirtualPathProvider.FileExists (virtualPath))
376 ThrowParseFileNotFound (virtualPath);
378 AddDependency (virtualPath);
380 masterVirtualPath = virtualPath;
382 previousPageVirtualPath = virtualPath;
384 ThrowParseException (String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
387 AddAssembly (type.Assembly, true);
389 base.AddDirective (directive, atts);
392 static string SuggestCulture (string culture)
394 string retval = null;
395 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
396 if (ci.Name.StartsWith (culture))
397 retval += ci.Name + " ";
402 public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
404 return BuildManager.GetCompiledType (virtualPath);
407 protected override Type CompileIntoType ()
409 AspGenerator generator = new AspGenerator (this);
410 return generator.GetCompiledType ();
413 internal bool EnableSessionState {
415 return enableSessionState == PagesEnableSessionState.True ||
416 ReadOnlySessionState;
420 internal bool EnableViewStateMac {
421 get { return enableViewStateMac; }
424 internal bool SmartNavigation {
425 get { return smartNavigation; }
428 internal bool ReadOnlySessionState {
430 return enableSessionState == PagesEnableSessionState.ReadOnly;
434 internal bool HaveTrace {
435 get { return haveTrace; }
438 internal bool Trace {
439 get { return trace; }
442 internal TraceMode TraceMode {
443 get { return tracemode; }
446 internal override string DefaultBaseTypeName {
447 get { return PagesConfig.PageBaseType; }
450 internal override string DefaultDirectiveName {
451 get { return "page"; }
454 internal string ResponseEncoding {
455 get { return responseEncoding; }
458 internal string ContentType {
459 get { return contentType; }
462 internal int CodePage {
463 get { return codepage; }
466 internal string Culture {
467 get { return culture; }
470 internal string UICulture {
471 get { return uiculture; }
478 internal string ErrorPage {
479 get { return errorPage; }
482 internal bool ValidateRequest {
483 get { return validateRequest; }
486 internal string ClientTarget {
487 get { return clientTarget; }
490 internal bool NotBuffer {
491 get { return notBuffer; }
494 internal bool Async {
495 get { return async; }
498 internal int AsyncTimeout {
499 get { return asyncTimeout; }
502 internal string Theme {
503 get { return theme; }
506 internal string StyleSheetTheme {
507 get { return styleSheetTheme; }
510 internal string MasterPageFile {
511 get { return masterPage; }
514 internal Type MasterType {
516 if (masterType == null && !String.IsNullOrEmpty (masterVirtualPath))
517 masterType = BuildManager.GetCompiledType (masterVirtualPath);
523 internal string Title {
524 get { return title; }
527 internal bool EnableEventValidation {
528 get { return enable_event_validation; }
531 internal bool MaintainScrollPositionOnPostBack {
532 get { return maintainScrollPositionOnPostBack; }
535 internal int MaxPageStateFieldLength {
536 get { return maxPageStateFieldLength; }
539 internal Type PreviousPageType {
541 if (previousPageType == null && !String.IsNullOrEmpty (previousPageVirtualPath)) {
542 string mappedPath = MapPath (previousPageVirtualPath);
543 previousPageType = GetCompiledPageType (previousPageVirtualPath, mappedPath, HttpContext.Current);
546 return previousPageType;