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;
49 bool enableViewStateMacSet;
54 TraceMode tracemode = TraceMode.Default;
55 string responseEncoding;
65 int asyncTimeout = -1;
68 string masterVirtualPath;
71 string styleSheetTheme;
72 bool enable_event_validation;
73 bool maintainScrollPositionOnPostBack;
74 int maxPageStateFieldLength = -1;
75 Type previousPageType;
76 string previousPageVirtualPath;
80 LoadConfigDefaults ();
83 internal PageParser (string virtualPath, string inputFile, HttpContext context)
85 this.VirtualPath = new VirtualPath (virtualPath);
87 BaseVirtualDir = VirtualPathUtility.GetDirectory (virtualPath, false);
88 InputFile = inputFile;
90 AddApplicationAssembly ();
91 LoadConfigDefaults ();
94 internal PageParser (VirtualPath virtualPath, TextReader reader, HttpContext context)
95 : this (virtualPath, null, reader, context)
99 internal PageParser (VirtualPath virtualPath, string inputFile, TextReader reader, HttpContext context)
101 this.VirtualPath = virtualPath;
103 BaseVirtualDir = virtualPath.DirectoryNoNormalize;
105 if (String.IsNullOrEmpty (inputFile))
106 InputFile = virtualPath.PhysicalPath;
108 InputFile = inputFile;
110 AddApplicationAssembly ();
111 LoadConfigDefaults ();
114 internal override void LoadConfigDefaults ()
116 base.LoadConfigDefaults ();
117 PagesSection ps = PagesConfig;
119 notBuffer = !ps.Buffer;
120 enableSessionState = ps.EnableSessionState;
121 enableViewStateMac = ps.EnableViewStateMac;
122 smartNavigation = ps.SmartNavigation;
123 validateRequest = ps.ValidateRequest;
124 masterPage = ps.MasterPageFile;
125 if (masterPage.Length == 0)
127 enable_event_validation = ps.EnableEventValidation;
128 maxPageStateFieldLength = ps.MaxPageStateFieldLength;
130 if (theme.Length == 0)
132 styleSheetTheme = ps.StyleSheetTheme;
133 if (styleSheetTheme.Length == 0)
134 styleSheetTheme = null;
135 maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
138 public static IHttpHandler GetCompiledPageInstance (string virtualPath, string inputFile, HttpContext context)
142 if (!String.IsNullOrEmpty (inputFile))
143 isFake = !inputFile.StartsWith (HttpRuntime.AppDomainAppPath);
145 return BuildManager.CreateInstanceFromVirtualPath (new VirtualPath (virtualPath, inputFile, isFake), typeof (IHttpHandler)) as IHttpHandler;
148 internal override void ProcessMainAttributes (Hashtable atts)
150 // note: the 'enableSessionState' configuration property is
151 // processed in a case-sensitive manner while the page-level
152 // attribute is processed case-insensitive
153 string enabless = GetString (atts, "EnableSessionState", null);
154 if (enabless != null) {
155 if (String.Compare (enabless, "readonly", true, Helpers.InvariantCulture) == 0)
156 enableSessionState = PagesEnableSessionState.ReadOnly;
157 else if (String.Compare (enabless, "true", true, Helpers.InvariantCulture) == 0)
158 enableSessionState = PagesEnableSessionState.True;
159 else if (String.Compare (enabless, "false", true, Helpers.InvariantCulture) == 0)
160 enableSessionState = PagesEnableSessionState.False;
162 ThrowParseException ("Invalid value for enableSessionState: " + enabless);
165 string cp = GetString (atts, "CodePage", null);
167 if (responseEncoding != null)
168 ThrowParseException ("CodePage and ResponseEncoding are " +
169 "mutually exclusive.");
173 codepage = (int) UInt32.Parse (cp);
175 ThrowParseException ("Invalid value for CodePage: " + cp);
179 Encoding.GetEncoding (codepage);
181 ThrowParseException ("Unsupported codepage: " + cp);
185 responseEncoding = GetString (atts, "ResponseEncoding", null);
186 if (responseEncoding != null) {
188 ThrowParseException ("CodePage and ResponseEncoding are " +
189 "mutually exclusive.");
192 Encoding.GetEncoding (responseEncoding);
194 ThrowParseException ("Unsupported encoding: " + responseEncoding);
198 contentType = GetString (atts, "ContentType", null);
200 string lcidStr = GetString (atts, "LCID", null);
201 if (lcidStr != null) {
203 lcid = (int) UInt32.Parse (lcidStr);
205 ThrowParseException ("Invalid value for LCID: " + lcid);
208 CultureInfo ci = null;
210 ci = new CultureInfo (lcid);
212 ThrowParseException ("Unsupported LCID: " + lcid);
215 if (ci.IsNeutralCulture) {
216 string suggestedCulture = SuggestCulture (ci.Name);
217 string fmt = "LCID attribute must be set to a non-neutral Culture.";
218 if (suggestedCulture != null) {
219 ThrowParseException (fmt + " Please try one of these: " +
222 ThrowParseException (fmt);
227 culture = GetString (atts, "Culture", null);
228 if (culture != null) {
230 ThrowParseException ("Culture and LCID are mutually exclusive.");
232 CultureInfo ci = null;
234 if (!culture.StartsWith ("auto"))
235 ci = new CultureInfo (culture);
237 ThrowParseException ("Unsupported Culture: " + culture);
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);
247 ThrowParseException (fmt);
251 uiculture = GetString (atts, "UICulture", null);
252 if (uiculture != null) {
253 CultureInfo ci = null;
255 if (!uiculture.StartsWith ("auto"))
256 ci = new CultureInfo (uiculture);
258 ThrowParseException ("Unsupported Culture: " + uiculture);
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);
268 ThrowParseException (fmt);
272 string tracestr = GetString (atts, "Trace", null);
273 if (tracestr != null) {
275 atts ["Trace"] = tracestr;
276 trace = GetBool (atts, "Trace", false);
279 string tracemodes = GetString (atts, "TraceMode", null);
280 if (tracemodes != null) {
283 tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
288 if (!valid || tracemode == TraceMode.Default)
289 ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
290 "one of the following values: SortByTime, SortByCategory.");
293 errorPage = GetString (atts, "ErrorPage", null);
294 validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
295 clientTarget = GetString (atts, "ClientTarget", null);
296 if (clientTarget != null) {
297 clientTarget = clientTarget.Trim ();
298 ClientTargetSection sec = GetConfigSection <ClientTargetSection> ("system.web/clientTarget");
299 ClientTarget ct = null;
301 if ((ct = sec.ClientTargets [clientTarget]) == null)
302 clientTarget = clientTarget.ToLowerInvariant ();
304 if (ct == null && (ct = sec.ClientTargets [clientTarget]) == null) {
305 ThrowParseException (String.Format (
306 "ClientTarget '{0}' is an invalid alias. See the " +
307 "documentation for <clientTarget> config. section.",
310 clientTarget = ct.UserAgent;
313 notBuffer = !GetBool (atts, "Buffer", true);
314 async = GetBool (atts, "Async", false);
315 string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
316 if (asyncTimeoutVal != null) {
318 asyncTimeout = Int32.Parse (asyncTimeoutVal);
319 } catch (Exception) {
320 ThrowParseException ("AsyncTimeout must be an integer value");
324 masterPage = GetString (atts, "MasterPageFile", masterPage);
326 if (!String.IsNullOrEmpty (masterPage)) {
327 if (!HostingEnvironment.VirtualPathProvider.FileExists (masterPage))
328 ThrowParseFileNotFound (masterPage);
329 AddDependency (masterPage);
332 title = GetString(atts, "Title", null);
334 theme = GetString (atts, "Theme", theme);
335 styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
336 enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
337 maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
339 if (atts.ContainsKey ("EnableViewState")) {
340 enableViewStateMac = GetBool (atts, "EnableViewStateMac", enableViewStateMac);
341 enableViewStateMacSet = true;
345 GetString (atts, "SmartNavigation", null);
347 base.ProcessMainAttributes (atts);
350 internal override void AddDirective (string directive, Hashtable atts)
352 bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
353 bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
354 StringComparison.OrdinalIgnoreCase) == 0;
356 string typeName = null;
357 string virtualPath = null;
360 if (isMasterType || isPreviousPageType) {
361 PageParserFilter pfilter = PageParserFilter;
363 pfilter.PreprocessDirective (directive.ToLowerInvariant (), atts);
365 typeName = GetString (atts, "TypeName", null);
366 virtualPath = GetString (atts, "VirtualPath", null);
368 if (typeName != null && virtualPath != null)
369 ThrowParseException (
370 String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
371 if (typeName != null) {
372 type = LoadType (typeName);
374 ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
378 previousPageType = type;
379 } else if (!String.IsNullOrEmpty (virtualPath)) {
380 if (!HostingEnvironment.VirtualPathProvider.FileExists (virtualPath))
381 ThrowParseFileNotFound (virtualPath);
383 AddDependency (virtualPath);
385 masterVirtualPath = virtualPath;
387 previousPageVirtualPath = virtualPath;
389 ThrowParseException (String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
392 AddAssembly (type.Assembly, true);
394 base.AddDirective (directive, atts);
397 static string SuggestCulture (string culture)
399 string retval = null;
400 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
401 if (ci.Name.StartsWith (culture))
402 retval += ci.Name + " ";
407 public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
409 return BuildManager.GetCompiledType (virtualPath);
412 protected override Type CompileIntoType ()
414 AspGenerator generator = new AspGenerator (this);
415 return generator.GetCompiledType ();
418 internal bool EnableSessionState {
420 return enableSessionState == PagesEnableSessionState.True ||
421 ReadOnlySessionState;
425 internal bool EnableViewStateMac {
426 get { return enableViewStateMac; }
429 internal bool EnableViewStateMacSet {
430 get { return enableViewStateMacSet; }
433 internal bool SmartNavigation {
434 get { return smartNavigation; }
437 internal bool ReadOnlySessionState {
439 return enableSessionState == PagesEnableSessionState.ReadOnly;
443 internal bool HaveTrace {
444 get { return haveTrace; }
447 internal bool Trace {
448 get { return trace; }
451 internal TraceMode TraceMode {
452 get { return tracemode; }
455 internal override string DefaultBaseTypeName {
456 get { return PagesConfig.PageBaseType; }
459 internal override string DefaultDirectiveName {
460 get { return "page"; }
463 internal string ResponseEncoding {
464 get { return responseEncoding; }
467 internal string ContentType {
468 get { return contentType; }
471 internal int CodePage {
472 get { return codepage; }
475 internal string Culture {
476 get { return culture; }
479 internal string UICulture {
480 get { return uiculture; }
487 internal string ErrorPage {
488 get { return errorPage; }
491 internal bool ValidateRequest {
492 get { return validateRequest; }
495 internal string ClientTarget {
496 get { return clientTarget; }
499 internal bool NotBuffer {
500 get { return notBuffer; }
503 internal bool Async {
504 get { return async; }
507 internal int AsyncTimeout {
508 get { return asyncTimeout; }
511 internal string Theme {
512 get { return theme; }
515 internal string StyleSheetTheme {
516 get { return styleSheetTheme; }
519 internal string MasterPageFile {
520 get { return masterPage; }
523 internal Type MasterType {
525 if (masterType == null && !String.IsNullOrEmpty (masterVirtualPath))
526 masterType = BuildManager.GetCompiledType (masterVirtualPath);
532 internal string Title {
533 get { return title; }
536 internal bool EnableEventValidation {
537 get { return enable_event_validation; }
540 internal bool MaintainScrollPositionOnPostBack {
541 get { return maintainScrollPositionOnPostBack; }
544 internal int MaxPageStateFieldLength {
545 get { return maxPageStateFieldLength; }
548 internal Type PreviousPageType {
550 if (previousPageType == null && !String.IsNullOrEmpty (previousPageVirtualPath)) {
551 string mappedPath = MapPath (previousPageVirtualPath);
552 previousPageType = GetCompiledPageType (previousPageVirtualPath, mappedPath, HttpContext.Current);
555 return previousPageType;