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.Util;
40 namespace System.Web.UI
42 // CAS - no InheritanceDemand here as the class is sealed
43 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
44 public sealed class PageParser : TemplateControlParser
46 PagesEnableSessionState enableSessionState = PagesEnableSessionState.True;
47 bool enableViewStateMac = true;
52 TraceMode tracemode = TraceMode.Default;
53 string responseEncoding;
62 Type baseType = typeof (Page);
66 int asyncTimeout = -1;
71 string styleSheetTheme;
72 bool enable_event_validation;
73 bool maintainScrollPositionOnPostBack;
74 int maxPageStateFieldLength = -1;
75 string pageParserFilter = String.Empty;
76 Type previousPageType;
81 LoadConfigDefaults ();
84 internal PageParser (string virtualPath, string inputFile, HttpContext context)
87 BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
88 InputFile = inputFile;
90 AddApplicationAssembly ();
91 LoadConfigDefaults ();
93 this.VirtualPath = new VirtualPath (virtualPath);
98 internal PageParser (string virtualPath, TextReader reader, HttpContext context)
99 : this (virtualPath, null, reader, context)
103 internal PageParser (string virtualPath, string inputFile, TextReader reader, HttpContext context)
106 BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
108 if (String.IsNullOrEmpty (inputFile)) {
109 HttpRequest req = context != null ? context.Request : null;
111 InputFile = req.MapPath (virtualPath);
113 InputFile = inputFile;
115 AddApplicationAssembly ();
116 LoadConfigDefaults ();
118 this.VirtualPath = new VirtualPath (virtualPath);
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)
142 enable_event_validation = ps.EnableEventValidation;
143 maxPageStateFieldLength = ps.MaxPageStateFieldLength;
144 pageParserFilter = ps.PageParserFilterType;
146 if (theme.Length == 0)
148 styleSheetTheme = ps.StyleSheetTheme;
149 if (styleSheetTheme.Length == 0)
150 styleSheetTheme = null;
151 maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
155 public static IHttpHandler GetCompiledPageInstance (string virtualPath,
160 return BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (IHttpHandler)) as IHttpHandler;
162 PageParser pp = new PageParser (virtualPath, inputFile, context);
163 IHttpHandler h = (IHttpHandler) pp.GetCompiledInstance ();
168 internal override void ProcessMainAttributes (Hashtable atts)
170 // note: the 'enableSessionState' configuration property is
171 // processed in a case-sensitive manner while the page-level
172 // attribute is processed case-insensitive
173 string enabless = GetString (atts, "EnableSessionState", null);
174 if (enabless != null) {
175 if (String.Compare (enabless, "readonly", true) == 0)
176 enableSessionState = PagesEnableSessionState.ReadOnly;
177 else if (String.Compare (enabless, "true", true) == 0)
178 enableSessionState = PagesEnableSessionState.True;
179 else if (String.Compare (enabless, "false", true) == 0)
180 enableSessionState = PagesEnableSessionState.False;
182 ThrowParseException ("Invalid value for enableSessionState: " + enabless);
185 string cp = GetString (atts, "CodePage", null);
187 if (responseEncoding != null)
188 ThrowParseException ("CodePage and ResponseEncoding are " +
189 "mutually exclusive.");
193 codepage = (int) UInt32.Parse (cp);
195 ThrowParseException ("Invalid value for CodePage: " + cp);
199 Encoding.GetEncoding (codepage);
201 ThrowParseException ("Unsupported codepage: " + cp);
205 responseEncoding = GetString (atts, "ResponseEncoding", null);
206 if (responseEncoding != null) {
208 ThrowParseException ("CodePage and ResponseEncoding are " +
209 "mutually exclusive.");
212 Encoding.GetEncoding (responseEncoding);
214 ThrowParseException ("Unsupported encoding: " + responseEncoding);
218 contentType = GetString (atts, "ContentType", null);
220 string lcidStr = GetString (atts, "LCID", null);
221 if (lcidStr != null) {
223 lcid = (int) UInt32.Parse (lcidStr);
225 ThrowParseException ("Invalid value for LCID: " + lcid);
228 CultureInfo ci = null;
230 ci = new CultureInfo (lcid);
232 ThrowParseException ("Unsupported LCID: " + lcid);
235 if (ci.IsNeutralCulture) {
236 string suggestedCulture = SuggestCulture (ci.Name);
237 string fmt = "LCID attribute must be set to a non-neutral Culture.";
238 if (suggestedCulture != null) {
239 ThrowParseException (fmt + " Please try one of these: " +
242 ThrowParseException (fmt);
247 culture = GetString (atts, "Culture", null);
248 if (culture != null) {
250 ThrowParseException ("Culture and LCID are mutually exclusive.");
252 CultureInfo ci = null;
255 if (!culture.StartsWith ("auto"))
257 ci = new CultureInfo (culture);
259 ThrowParseException ("Unsupported Culture: " + culture);
262 if (ci != null && ci.IsNeutralCulture) {
263 string suggestedCulture = SuggestCulture (culture);
264 string fmt = "Culture attribute must be set to a non-neutral Culture.";
265 if (suggestedCulture != null)
266 ThrowParseException (fmt +
267 " Please try one of these: " + suggestedCulture);
269 ThrowParseException (fmt);
273 uiculture = GetString (atts, "UICulture", null);
274 if (uiculture != null) {
275 CultureInfo ci = null;
278 if (!uiculture.StartsWith ("auto"))
280 ci = new CultureInfo (uiculture);
282 ThrowParseException ("Unsupported Culture: " + uiculture);
285 if (ci != null && ci.IsNeutralCulture) {
286 string suggestedCulture = SuggestCulture (uiculture);
287 string fmt = "UICulture attribute must be set to a non-neutral Culture.";
288 if (suggestedCulture != null)
289 ThrowParseException (fmt +
290 " Please try one of these: " + suggestedCulture);
292 ThrowParseException (fmt);
296 string tracestr = GetString (atts, "Trace", null);
297 if (tracestr != null) {
299 atts ["Trace"] = tracestr;
300 trace = GetBool (atts, "Trace", false);
303 string tracemodes = GetString (atts, "TraceMode", null);
304 if (tracemodes != null) {
307 tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
312 if (!valid || tracemode == TraceMode.Default)
313 ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
314 "one of the following values: SortByTime, SortByCategory.");
317 errorPage = GetString (atts, "ErrorPage", null);
318 validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
319 clientTarget = GetString (atts, "ClientTarget", null);
320 if (clientTarget != null) {
321 clientTarget = clientTarget.Trim ();
323 ClientTargetSection sec = (ClientTargetSection)WebConfigurationManager.GetSection ("system.web/clientTarget");
324 ClientTarget ct = null;
326 if ((ct = sec.ClientTargets [clientTarget]) == null)
327 clientTarget = clientTarget.ToLower (CultureInfo.InvariantCulture);
329 if (ct == null && (ct = sec.ClientTargets [clientTarget]) == null) {
330 ThrowParseException (String.Format (
331 "ClientTarget '{0}' is an invalid alias. See the " +
332 "documentation for <clientTarget> config. section.",
335 clientTarget = ct.UserAgent;
337 NameValueCollection coll;
338 coll = (NameValueCollection) Context.GetConfig ("system.web/clientTarget");
342 ct = coll [clientTarget];
344 ct = coll [clientTarget.ToLower ()];
348 ThrowParseException (String.Format (
349 "ClientTarget '{0}' is an invalid alias. See the " +
350 "documentation for <clientTarget> config. section.",
353 clientTarget = (string) ct;
357 notBuffer = !GetBool (atts, "Buffer", true);
360 async = GetBool (atts, "Async", false);
361 string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
362 if (asyncTimeoutVal != null) {
364 asyncTimeout = Int32.Parse (asyncTimeoutVal);
365 } catch (Exception) {
366 ThrowParseException ("AsyncTimeout must be an integer value");
370 masterPage = GetString (atts, "MasterPageFile", masterPage);
372 // Make sure the page exists
373 if (!String.IsNullOrEmpty (masterPage)) {
374 BuildManager.GetCompiledType (masterPage);
375 AddDependency (masterPage);
378 title = GetString(atts, "Title", null);
380 theme = GetString (atts, "Theme", theme);
381 styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
382 enable_event_validation = GetBool (atts, "EnableEventValidation", true);
383 maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
386 GetString (atts, "EnableViewStateMac", null);
387 GetString (atts, "SmartNavigation", null);
389 base.ProcessMainAttributes (atts);
393 internal override void AddDirective (string directive, Hashtable atts)
395 bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
396 bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
397 StringComparison.OrdinalIgnoreCase) == 0;
399 string typeName = null;
400 string virtualPath = null;
403 if (isMasterType || isPreviousPageType) {
404 typeName = GetString (atts, "TypeName", null);
405 virtualPath = GetString (atts, "VirtualPath", null);
407 if (typeName != null && virtualPath != null)
408 ThrowParseException (
409 String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
410 if (typeName != null) {
411 type = LoadType (typeName);
413 ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
414 } else if (virtualPath != null) {
415 string mappedPath = MapPath (virtualPath);
417 type = masterType = BuildManager.GetCompiledType (virtualPath);
419 type = previousPageType = GetCompiledPageType (virtualPath, mappedPath,
420 HttpContext.Current);
422 ThrowParseException (
423 String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
425 AddAssembly (type.Assembly, true);
427 base.AddDirective (directive, atts);
431 static string SuggestCulture (string culture)
433 string retval = null;
434 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
435 if (ci.Name.StartsWith (culture))
436 retval += ci.Name + " ";
441 public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
444 return BuildManager.GetCompiledType (virtualPath);
446 PageParser pp = new PageParser (virtualPath, inputFile, context);
447 return pp.CompileIntoType ();
451 protected override Type CompileIntoType ()
453 AspGenerator generator = new AspGenerator (this);
454 return generator.GetCompiledType ();
457 internal bool EnableSessionState {
459 return enableSessionState == PagesEnableSessionState.True ||
460 ReadOnlySessionState;
464 internal bool EnableViewStateMac {
465 get { return enableViewStateMac; }
468 internal bool SmartNavigation {
469 get { return smartNavigation; }
472 internal bool ReadOnlySessionState {
474 return enableSessionState == PagesEnableSessionState.ReadOnly;
478 internal bool HaveTrace {
479 get { return haveTrace; }
482 internal bool Trace {
483 get { return trace; }
486 internal TraceMode TraceMode {
487 get { return tracemode; }
491 internal override string DefaultBaseTypeName {
492 get { return PagesConfig.PageBaseType; }
495 internal override string DefaultBaseTypeName {
496 get { return "System.Web.UI.Page"; }
500 internal override string DefaultDirectiveName {
501 get { return "page"; }
504 internal string ResponseEncoding {
505 get { return responseEncoding; }
508 internal string ContentType {
509 get { return contentType; }
512 internal int CodePage {
513 get { return codepage; }
516 internal string Culture {
517 get { return culture; }
520 internal string UICulture {
521 get { return uiculture; }
528 internal string ErrorPage {
529 get { return errorPage; }
532 internal bool ValidateRequest {
533 get { return validateRequest; }
536 internal string ClientTarget {
537 get { return clientTarget; }
540 internal bool NotBuffer {
541 get { return notBuffer; }
545 internal bool Async {
546 get { return async; }
549 internal int AsyncTimeout {
550 get { return asyncTimeout; }
553 internal string Theme {
554 get { return theme; }
557 internal string StyleSheetTheme {
558 get { return styleSheetTheme; }
561 internal string MasterPageFile {
562 get { return masterPage; }
565 internal Type MasterType {
566 get { return masterType; }
569 internal string Title {
570 get { return title; }
573 internal bool EnableEventValidation {
574 get { return enable_event_validation; }
577 internal bool MaintainScrollPositionOnPostBack {
578 get { return maintainScrollPositionOnPostBack; }
581 internal int MaxPageStateFieldLength {
582 get { return maxPageStateFieldLength; }
585 internal string PageParserFilterType {
586 get { return pageParserFilter; }
589 internal Type PreviousPageType {
590 get { return previousPageType; }