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 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;
66 int asyncTimeout = -1;
69 string masterVirtualPath;
72 string styleSheetTheme;
73 bool enable_event_validation;
74 bool maintainScrollPositionOnPostBack;
75 int maxPageStateFieldLength = -1;
76 string pageParserFilter = String.Empty;
77 Type previousPageType;
78 string previousPageVirtualPath;
83 LoadConfigDefaults ();
86 internal PageParser (string virtualPath, string inputFile, HttpContext context)
89 BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
90 InputFile = inputFile;
92 AddApplicationAssembly ();
93 LoadConfigDefaults ();
95 this.VirtualPath = new VirtualPath (virtualPath);
100 internal PageParser (string virtualPath, TextReader reader, HttpContext context)
101 : this (virtualPath, null, reader, context)
105 internal PageParser (string virtualPath, string inputFile, TextReader reader, HttpContext context)
108 BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
110 if (String.IsNullOrEmpty (inputFile)) {
111 HttpRequest req = context != null ? context.Request : null;
113 InputFile = req.MapPath (virtualPath);
115 InputFile = inputFile;
117 AddApplicationAssembly ();
118 LoadConfigDefaults ();
120 this.VirtualPath = new VirtualPath (virtualPath);
125 internal override void LoadConfigDefaults ()
127 base.LoadConfigDefaults ();
129 PagesSection ps = PagesConfig;
131 PagesConfiguration ps = PagesConfig;
134 notBuffer = !ps.Buffer;
135 enableSessionState = ps.EnableSessionState;
136 enableViewStateMac = ps.EnableViewStateMac;
137 smartNavigation = ps.SmartNavigation;
138 validateRequest = ps.ValidateRequest;
140 masterPage = ps.MasterPageFile;
141 if (masterPage.Length == 0)
143 enable_event_validation = ps.EnableEventValidation;
144 maxPageStateFieldLength = ps.MaxPageStateFieldLength;
145 pageParserFilter = ps.PageParserFilterType;
147 if (theme.Length == 0)
149 styleSheetTheme = ps.StyleSheetTheme;
150 if (styleSheetTheme.Length == 0)
151 styleSheetTheme = null;
152 maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
156 public static IHttpHandler GetCompiledPageInstance (string virtualPath,
161 return BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (IHttpHandler)) as IHttpHandler;
163 PageParser pp = new PageParser (virtualPath, inputFile, context);
164 IHttpHandler h = (IHttpHandler) pp.GetCompiledInstance ();
169 internal override void ProcessMainAttributes (Hashtable atts)
171 // note: the 'enableSessionState' configuration property is
172 // processed in a case-sensitive manner while the page-level
173 // attribute is processed case-insensitive
174 string enabless = GetString (atts, "EnableSessionState", null);
175 if (enabless != null) {
176 if (String.Compare (enabless, "readonly", true) == 0)
177 enableSessionState = PagesEnableSessionState.ReadOnly;
178 else if (String.Compare (enabless, "true", true) == 0)
179 enableSessionState = PagesEnableSessionState.True;
180 else if (String.Compare (enabless, "false", true) == 0)
181 enableSessionState = PagesEnableSessionState.False;
183 ThrowParseException ("Invalid value for enableSessionState: " + enabless);
186 string cp = GetString (atts, "CodePage", null);
188 if (responseEncoding != null)
189 ThrowParseException ("CodePage and ResponseEncoding are " +
190 "mutually exclusive.");
194 codepage = (int) UInt32.Parse (cp);
196 ThrowParseException ("Invalid value for CodePage: " + cp);
200 Encoding.GetEncoding (codepage);
202 ThrowParseException ("Unsupported codepage: " + cp);
206 responseEncoding = GetString (atts, "ResponseEncoding", null);
207 if (responseEncoding != null) {
209 ThrowParseException ("CodePage and ResponseEncoding are " +
210 "mutually exclusive.");
213 Encoding.GetEncoding (responseEncoding);
215 ThrowParseException ("Unsupported encoding: " + responseEncoding);
219 contentType = GetString (atts, "ContentType", null);
221 string lcidStr = GetString (atts, "LCID", null);
222 if (lcidStr != null) {
224 lcid = (int) UInt32.Parse (lcidStr);
226 ThrowParseException ("Invalid value for LCID: " + lcid);
229 CultureInfo ci = null;
231 ci = new CultureInfo (lcid);
233 ThrowParseException ("Unsupported LCID: " + lcid);
236 if (ci.IsNeutralCulture) {
237 string suggestedCulture = SuggestCulture (ci.Name);
238 string fmt = "LCID attribute must be set to a non-neutral Culture.";
239 if (suggestedCulture != null) {
240 ThrowParseException (fmt + " Please try one of these: " +
243 ThrowParseException (fmt);
248 culture = GetString (atts, "Culture", null);
249 if (culture != null) {
251 ThrowParseException ("Culture and LCID are mutually exclusive.");
253 CultureInfo ci = null;
256 if (!culture.StartsWith ("auto"))
258 ci = new CultureInfo (culture);
260 ThrowParseException ("Unsupported Culture: " + culture);
263 if (ci != null && ci.IsNeutralCulture) {
264 string suggestedCulture = SuggestCulture (culture);
265 string fmt = "Culture attribute must be set to a non-neutral Culture.";
266 if (suggestedCulture != null)
267 ThrowParseException (fmt +
268 " Please try one of these: " + suggestedCulture);
270 ThrowParseException (fmt);
274 uiculture = GetString (atts, "UICulture", null);
275 if (uiculture != null) {
276 CultureInfo ci = null;
279 if (!uiculture.StartsWith ("auto"))
281 ci = new CultureInfo (uiculture);
283 ThrowParseException ("Unsupported Culture: " + uiculture);
286 if (ci != null && ci.IsNeutralCulture) {
287 string suggestedCulture = SuggestCulture (uiculture);
288 string fmt = "UICulture attribute must be set to a non-neutral Culture.";
289 if (suggestedCulture != null)
290 ThrowParseException (fmt +
291 " Please try one of these: " + suggestedCulture);
293 ThrowParseException (fmt);
297 string tracestr = GetString (atts, "Trace", null);
298 if (tracestr != null) {
300 atts ["Trace"] = tracestr;
301 trace = GetBool (atts, "Trace", false);
304 string tracemodes = GetString (atts, "TraceMode", null);
305 if (tracemodes != null) {
308 tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
313 if (!valid || tracemode == TraceMode.Default)
314 ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
315 "one of the following values: SortByTime, SortByCategory.");
318 errorPage = GetString (atts, "ErrorPage", null);
319 validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
320 clientTarget = GetString (atts, "ClientTarget", null);
321 if (clientTarget != null) {
322 clientTarget = clientTarget.Trim ();
324 ClientTargetSection sec = (ClientTargetSection)WebConfigurationManager.GetSection ("system.web/clientTarget");
325 ClientTarget ct = null;
327 if ((ct = sec.ClientTargets [clientTarget]) == null)
328 clientTarget = clientTarget.ToLower (CultureInfo.InvariantCulture);
330 if (ct == null && (ct = sec.ClientTargets [clientTarget]) == null) {
331 ThrowParseException (String.Format (
332 "ClientTarget '{0}' is an invalid alias. See the " +
333 "documentation for <clientTarget> config. section.",
336 clientTarget = ct.UserAgent;
338 NameValueCollection coll;
339 coll = (NameValueCollection) Context.GetConfig ("system.web/clientTarget");
343 ct = coll [clientTarget];
345 ct = coll [clientTarget.ToLower ()];
349 ThrowParseException (String.Format (
350 "ClientTarget '{0}' is an invalid alias. See the " +
351 "documentation for <clientTarget> config. section.",
354 clientTarget = (string) ct;
358 notBuffer = !GetBool (atts, "Buffer", true);
361 async = GetBool (atts, "Async", false);
362 string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
363 if (asyncTimeoutVal != null) {
365 asyncTimeout = Int32.Parse (asyncTimeoutVal);
366 } catch (Exception) {
367 ThrowParseException ("AsyncTimeout must be an integer value");
371 masterPage = GetString (atts, "MasterPageFile", masterPage);
373 if (!String.IsNullOrEmpty (masterPage)) {
374 if (!HostingEnvironment.VirtualPathProvider.FileExists (masterPage))
375 ThrowParseFileNotFound (masterPage);
376 AddDependency (masterPage);
379 title = GetString(atts, "Title", null);
381 theme = GetString (atts, "Theme", theme);
382 styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
383 enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
384 maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
387 GetString (atts, "EnableViewStateMac", null);
388 GetString (atts, "SmartNavigation", null);
390 base.ProcessMainAttributes (atts);
394 internal override void AddDirective (string directive, Hashtable atts)
396 bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
397 bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
398 StringComparison.OrdinalIgnoreCase) == 0;
400 string typeName = null;
401 string virtualPath = null;
404 if (isMasterType || isPreviousPageType) {
405 typeName = GetString (atts, "TypeName", null);
406 virtualPath = GetString (atts, "VirtualPath", null);
408 if (typeName != null && virtualPath != null)
409 ThrowParseException (
410 String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
411 if (typeName != null) {
412 type = LoadType (typeName);
414 ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
418 previousPageType = type;
419 } else if (!String.IsNullOrEmpty (virtualPath)) {
420 if (!HostingEnvironment.VirtualPathProvider.FileExists (virtualPath))
421 ThrowParseFileNotFound (virtualPath);
423 AddDependency (virtualPath);
425 masterVirtualPath = virtualPath;
427 previousPageVirtualPath = virtualPath;
429 ThrowParseException (String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
432 AddAssembly (type.Assembly, true);
434 base.AddDirective (directive, atts);
438 static string SuggestCulture (string culture)
440 string retval = null;
441 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
442 if (ci.Name.StartsWith (culture))
443 retval += ci.Name + " ";
448 public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
451 return BuildManager.GetCompiledType (virtualPath);
453 PageParser pp = new PageParser (virtualPath, inputFile, context);
454 return pp.CompileIntoType ();
458 protected override Type CompileIntoType ()
460 AspGenerator generator = new AspGenerator (this);
461 return generator.GetCompiledType ();
464 internal bool EnableSessionState {
466 return enableSessionState == PagesEnableSessionState.True ||
467 ReadOnlySessionState;
471 internal bool EnableViewStateMac {
472 get { return enableViewStateMac; }
475 internal bool SmartNavigation {
476 get { return smartNavigation; }
479 internal bool ReadOnlySessionState {
481 return enableSessionState == PagesEnableSessionState.ReadOnly;
485 internal bool HaveTrace {
486 get { return haveTrace; }
489 internal bool Trace {
490 get { return trace; }
493 internal TraceMode TraceMode {
494 get { return tracemode; }
498 internal override string DefaultBaseTypeName {
499 get { return PagesConfig.PageBaseType; }
502 internal override string DefaultBaseTypeName {
503 get { return "System.Web.UI.Page"; }
507 internal override string DefaultDirectiveName {
508 get { return "page"; }
511 internal string ResponseEncoding {
512 get { return responseEncoding; }
515 internal string ContentType {
516 get { return contentType; }
519 internal int CodePage {
520 get { return codepage; }
523 internal string Culture {
524 get { return culture; }
527 internal string UICulture {
528 get { return uiculture; }
535 internal string ErrorPage {
536 get { return errorPage; }
539 internal bool ValidateRequest {
540 get { return validateRequest; }
543 internal string ClientTarget {
544 get { return clientTarget; }
547 internal bool NotBuffer {
548 get { return notBuffer; }
552 internal bool Async {
553 get { return async; }
556 internal int AsyncTimeout {
557 get { return asyncTimeout; }
560 internal string Theme {
561 get { return theme; }
564 internal string StyleSheetTheme {
565 get { return styleSheetTheme; }
568 internal string MasterPageFile {
569 get { return masterPage; }
572 internal Type MasterType {
574 if (masterType == null && !String.IsNullOrEmpty (masterVirtualPath))
575 masterType = BuildManager.GetCompiledType (masterVirtualPath);
581 internal string Title {
582 get { return title; }
585 internal bool EnableEventValidation {
586 get { return enable_event_validation; }
589 internal bool MaintainScrollPositionOnPostBack {
590 get { return maintainScrollPositionOnPostBack; }
593 internal int MaxPageStateFieldLength {
594 get { return maxPageStateFieldLength; }
597 internal string PageParserFilterType {
598 get { return pageParserFilter; }
601 internal Type PreviousPageType {
603 if (previousPageType == null && !String.IsNullOrEmpty (previousPageVirtualPath)) {
604 string mappedPath = MapPath (previousPageVirtualPath);
605 previousPageType = GetCompiledPageType (previousPageVirtualPath, mappedPath, HttpContext.Current);
608 return previousPageType;