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 Type previousPageType;
77 string previousPageVirtualPath;
82 LoadConfigDefaults ();
85 internal PageParser (string virtualPath, string inputFile, HttpContext context)
88 this.VirtualPath = new VirtualPath (virtualPath);
92 BaseVirtualDir = VirtualPathUtility.GetDirectory (virtualPath, false);
93 InputFile = inputFile;
95 AddApplicationAssembly ();
96 LoadConfigDefaults ();
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)
107 this.VirtualPath = new VirtualPath (virtualPath);
109 BaseVirtualDir = VirtualPathUtility.GetDirectory (virtualPath, false);
111 if (String.IsNullOrEmpty (inputFile)) {
112 HttpRequest req = context != null ? context.Request : null;
114 InputFile = req.MapPath (virtualPath);
116 InputFile = inputFile;
118 AddApplicationAssembly ();
119 LoadConfigDefaults ();
123 internal override void LoadConfigDefaults ()
125 base.LoadConfigDefaults ();
127 PagesSection ps = PagesConfig;
129 PagesConfiguration ps = PagesConfig;
132 notBuffer = !ps.Buffer;
133 enableSessionState = ps.EnableSessionState;
134 enableViewStateMac = ps.EnableViewStateMac;
135 smartNavigation = ps.SmartNavigation;
136 validateRequest = ps.ValidateRequest;
138 masterPage = ps.MasterPageFile;
139 if (masterPage.Length == 0)
141 enable_event_validation = ps.EnableEventValidation;
142 maxPageStateFieldLength = ps.MaxPageStateFieldLength;
144 if (theme.Length == 0)
146 styleSheetTheme = ps.StyleSheetTheme;
147 if (styleSheetTheme.Length == 0)
148 styleSheetTheme = null;
149 maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
153 public static IHttpHandler GetCompiledPageInstance (string virtualPath,
158 return BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (IHttpHandler)) as IHttpHandler;
160 PageParser pp = new PageParser (virtualPath, inputFile, context);
161 IHttpHandler h = (IHttpHandler) pp.GetCompiledInstance ();
166 internal override void ProcessMainAttributes (Hashtable atts)
168 // note: the 'enableSessionState' configuration property is
169 // processed in a case-sensitive manner while the page-level
170 // attribute is processed case-insensitive
171 string enabless = GetString (atts, "EnableSessionState", null);
172 if (enabless != null) {
173 if (String.Compare (enabless, "readonly", true) == 0)
174 enableSessionState = PagesEnableSessionState.ReadOnly;
175 else if (String.Compare (enabless, "true", true) == 0)
176 enableSessionState = PagesEnableSessionState.True;
177 else if (String.Compare (enabless, "false", true) == 0)
178 enableSessionState = PagesEnableSessionState.False;
180 ThrowParseException ("Invalid value for enableSessionState: " + enabless);
183 string cp = GetString (atts, "CodePage", null);
185 if (responseEncoding != null)
186 ThrowParseException ("CodePage and ResponseEncoding are " +
187 "mutually exclusive.");
191 codepage = (int) UInt32.Parse (cp);
193 ThrowParseException ("Invalid value for CodePage: " + cp);
197 Encoding.GetEncoding (codepage);
199 ThrowParseException ("Unsupported codepage: " + cp);
203 responseEncoding = GetString (atts, "ResponseEncoding", null);
204 if (responseEncoding != null) {
206 ThrowParseException ("CodePage and ResponseEncoding are " +
207 "mutually exclusive.");
210 Encoding.GetEncoding (responseEncoding);
212 ThrowParseException ("Unsupported encoding: " + responseEncoding);
216 contentType = GetString (atts, "ContentType", null);
218 string lcidStr = GetString (atts, "LCID", null);
219 if (lcidStr != null) {
221 lcid = (int) UInt32.Parse (lcidStr);
223 ThrowParseException ("Invalid value for LCID: " + lcid);
226 CultureInfo ci = null;
228 ci = new CultureInfo (lcid);
230 ThrowParseException ("Unsupported LCID: " + lcid);
233 if (ci.IsNeutralCulture) {
234 string suggestedCulture = SuggestCulture (ci.Name);
235 string fmt = "LCID attribute must be set to a non-neutral Culture.";
236 if (suggestedCulture != null) {
237 ThrowParseException (fmt + " Please try one of these: " +
240 ThrowParseException (fmt);
245 culture = GetString (atts, "Culture", null);
246 if (culture != null) {
248 ThrowParseException ("Culture and LCID are mutually exclusive.");
250 CultureInfo ci = null;
253 if (!culture.StartsWith ("auto"))
255 ci = new CultureInfo (culture);
257 ThrowParseException ("Unsupported Culture: " + culture);
260 if (ci != null && ci.IsNeutralCulture) {
261 string suggestedCulture = SuggestCulture (culture);
262 string fmt = "Culture 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 uiculture = GetString (atts, "UICulture", null);
272 if (uiculture != null) {
273 CultureInfo ci = null;
276 if (!uiculture.StartsWith ("auto"))
278 ci = new CultureInfo (uiculture);
280 ThrowParseException ("Unsupported Culture: " + uiculture);
283 if (ci != null && ci.IsNeutralCulture) {
284 string suggestedCulture = SuggestCulture (uiculture);
285 string fmt = "UICulture attribute must be set to a non-neutral Culture.";
286 if (suggestedCulture != null)
287 ThrowParseException (fmt +
288 " Please try one of these: " + suggestedCulture);
290 ThrowParseException (fmt);
294 string tracestr = GetString (atts, "Trace", null);
295 if (tracestr != null) {
297 atts ["Trace"] = tracestr;
298 trace = GetBool (atts, "Trace", false);
301 string tracemodes = GetString (atts, "TraceMode", null);
302 if (tracemodes != null) {
305 tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
310 if (!valid || tracemode == TraceMode.Default)
311 ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
312 "one of the following values: SortByTime, SortByCategory.");
315 errorPage = GetString (atts, "ErrorPage", null);
316 validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
317 clientTarget = GetString (atts, "ClientTarget", null);
318 if (clientTarget != null) {
319 clientTarget = clientTarget.Trim ();
321 ClientTargetSection sec = (ClientTargetSection)WebConfigurationManager.GetWebApplicationSection ("system.web/clientTarget");
322 ClientTarget ct = null;
324 if ((ct = sec.ClientTargets [clientTarget]) == null)
325 clientTarget = clientTarget.ToLower (CultureInfo.InvariantCulture);
327 if (ct == null && (ct = sec.ClientTargets [clientTarget]) == null) {
328 ThrowParseException (String.Format (
329 "ClientTarget '{0}' is an invalid alias. See the " +
330 "documentation for <clientTarget> config. section.",
333 clientTarget = ct.UserAgent;
335 NameValueCollection coll;
336 coll = (NameValueCollection) HttpContext.GetAppConfig ("system.web/clientTarget");
340 ct = coll [clientTarget];
342 ct = coll [clientTarget.ToLower ()];
346 ThrowParseException (String.Format (
347 "ClientTarget '{0}' is an invalid alias. See the " +
348 "documentation for <clientTarget> config. section.",
351 clientTarget = (string) ct;
355 notBuffer = !GetBool (atts, "Buffer", true);
358 async = GetBool (atts, "Async", false);
359 string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
360 if (asyncTimeoutVal != null) {
362 asyncTimeout = Int32.Parse (asyncTimeoutVal);
363 } catch (Exception) {
364 ThrowParseException ("AsyncTimeout must be an integer value");
368 masterPage = GetString (atts, "MasterPageFile", masterPage);
370 if (!String.IsNullOrEmpty (masterPage)) {
371 if (!HostingEnvironment.VirtualPathProvider.FileExists (masterPage))
372 ThrowParseFileNotFound (masterPage);
373 AddDependency (masterPage);
376 title = GetString(atts, "Title", null);
378 theme = GetString (atts, "Theme", theme);
379 styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
380 enable_event_validation = GetBool (atts, "EnableEventValidation", enable_event_validation);
381 maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
384 GetString (atts, "EnableViewStateMac", null);
385 GetString (atts, "SmartNavigation", null);
387 base.ProcessMainAttributes (atts);
391 internal override void AddDirective (string directive, Hashtable atts)
393 bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
394 bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
395 StringComparison.OrdinalIgnoreCase) == 0;
397 string typeName = null;
398 string virtualPath = null;
401 if (isMasterType || isPreviousPageType) {
402 PageParserFilter pfilter = PageParserFilter;
404 pfilter.PreprocessDirective (directive.ToLower (CultureInfo.InvariantCulture), atts);
406 typeName = GetString (atts, "TypeName", null);
407 virtualPath = GetString (atts, "VirtualPath", null);
409 if (typeName != null && virtualPath != null)
410 ThrowParseException (
411 String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
412 if (typeName != null) {
413 type = LoadType (typeName);
415 ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
419 previousPageType = type;
420 } else if (!String.IsNullOrEmpty (virtualPath)) {
421 if (!HostingEnvironment.VirtualPathProvider.FileExists (virtualPath))
422 ThrowParseFileNotFound (virtualPath);
424 AddDependency (virtualPath);
426 masterVirtualPath = virtualPath;
428 previousPageVirtualPath = virtualPath;
430 ThrowParseException (String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
433 AddAssembly (type.Assembly, true);
435 base.AddDirective (directive, atts);
439 static string SuggestCulture (string culture)
441 string retval = null;
442 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
443 if (ci.Name.StartsWith (culture))
444 retval += ci.Name + " ";
449 public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
452 return BuildManager.GetCompiledType (virtualPath);
454 PageParser pp = new PageParser (virtualPath, inputFile, context);
455 return pp.CompileIntoType ();
459 protected override Type CompileIntoType ()
461 AspGenerator generator = new AspGenerator (this);
462 return generator.GetCompiledType ();
465 internal bool EnableSessionState {
467 return enableSessionState == PagesEnableSessionState.True ||
468 ReadOnlySessionState;
472 internal bool EnableViewStateMac {
473 get { return enableViewStateMac; }
476 internal bool SmartNavigation {
477 get { return smartNavigation; }
480 internal bool ReadOnlySessionState {
482 return enableSessionState == PagesEnableSessionState.ReadOnly;
486 internal bool HaveTrace {
487 get { return haveTrace; }
490 internal bool Trace {
491 get { return trace; }
494 internal TraceMode TraceMode {
495 get { return tracemode; }
499 internal override string DefaultBaseTypeName {
500 get { return PagesConfig.PageBaseType; }
503 internal override string DefaultBaseTypeName {
504 get { return "System.Web.UI.Page"; }
508 internal override string DefaultDirectiveName {
509 get { return "page"; }
512 internal string ResponseEncoding {
513 get { return responseEncoding; }
516 internal string ContentType {
517 get { return contentType; }
520 internal int CodePage {
521 get { return codepage; }
524 internal string Culture {
525 get { return culture; }
528 internal string UICulture {
529 get { return uiculture; }
536 internal string ErrorPage {
537 get { return errorPage; }
540 internal bool ValidateRequest {
541 get { return validateRequest; }
544 internal string ClientTarget {
545 get { return clientTarget; }
548 internal bool NotBuffer {
549 get { return notBuffer; }
553 internal bool Async {
554 get { return async; }
557 internal int AsyncTimeout {
558 get { return asyncTimeout; }
561 internal string Theme {
562 get { return theme; }
565 internal string StyleSheetTheme {
566 get { return styleSheetTheme; }
569 internal string MasterPageFile {
570 get { return masterPage; }
573 internal Type MasterType {
575 if (masterType == null && !String.IsNullOrEmpty (masterVirtualPath))
576 masterType = BuildManager.GetCompiledType (masterVirtualPath);
582 internal string Title {
583 get { return title; }
586 internal bool EnableEventValidation {
587 get { return enable_event_validation; }
590 internal bool MaintainScrollPositionOnPostBack {
591 get { return maintainScrollPositionOnPostBack; }
594 internal int MaxPageStateFieldLength {
595 get { return maxPageStateFieldLength; }
598 internal Type PreviousPageType {
600 if (previousPageType == null && !String.IsNullOrEmpty (previousPageVirtualPath)) {
601 string mappedPath = MapPath (previousPageVirtualPath);
602 previousPageType = GetCompiledPageType (previousPageVirtualPath, mappedPath, HttpContext.Current);
605 return previousPageType;