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;
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 LoadPagesConfigDefaults ();
84 internal PageParser (string virtualPath, string inputFile, HttpContext context)
87 BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
88 InputFile = inputFile;
89 SetBaseType (PagesConfig.PageBaseType);
90 AddApplicationAssembly ();
91 LoadPagesConfigDefaults ();
95 internal PageParser (string virtualPath, TextReader reader, HttpContext context)
98 BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
100 SetBaseType (PagesConfig.PageBaseType);
101 AddApplicationAssembly ();
102 LoadPagesConfigDefaults ();
106 internal override void LoadPagesConfigDefaults ()
108 base.LoadPagesConfigDefaults ();
110 PagesSection ps = PagesConfig;
112 PagesConfiguration ps = PagesConfig;
115 notBuffer = !ps.Buffer;
116 enableSessionState = ps.EnableSessionState;
117 enableViewStateMac = ps.EnableViewStateMac;
118 smartNavigation = ps.SmartNavigation;
119 validateRequest = ps.ValidateRequest;
121 masterPage = ps.MasterPageFile;
122 if (masterPage.Length == 0)
125 enable_event_validation = ps.EnableEventValidation;
126 maxPageStateFieldLength = ps.MaxPageStateFieldLength;
127 pageParserFilter = ps.PageParserFilterType;
129 if (theme.Length == 0)
131 styleSheetTheme = ps.StyleSheetTheme;
132 if (styleSheetTheme.Length == 0)
133 styleSheetTheme = null;
134 maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
138 public static IHttpHandler GetCompiledPageInstance (string virtualPath,
142 PageParser pp = new PageParser (virtualPath, inputFile, context);
143 IHttpHandler h = (IHttpHandler) pp.GetCompiledInstance ();
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) == 0)
155 enableSessionState = PagesEnableSessionState.ReadOnly;
156 else if (String.Compare (enabless, "true", true) == 0)
157 enableSessionState = PagesEnableSessionState.True;
158 else if (String.Compare (enabless, "false", true) == 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;
234 if (!culture.StartsWith ("auto"))
236 ci = new CultureInfo (culture);
238 ThrowParseException ("Unsupported Culture: " + culture);
241 if (ci != null && ci.IsNeutralCulture) {
242 string suggestedCulture = SuggestCulture (culture);
243 string fmt = "Culture attribute must be set to a non-neutral Culture.";
244 if (suggestedCulture != null)
245 ThrowParseException (fmt +
246 " Please try one of these: " + suggestedCulture);
248 ThrowParseException (fmt);
252 uiculture = GetString (atts, "UICulture", null);
253 if (uiculture != null) {
254 CultureInfo ci = null;
257 if (!uiculture.StartsWith ("auto"))
259 ci = new CultureInfo (uiculture);
261 ThrowParseException ("Unsupported Culture: " + uiculture);
264 if (ci != null && ci.IsNeutralCulture) {
265 string suggestedCulture = SuggestCulture (uiculture);
266 string fmt = "UICulture attribute must be set to a non-neutral Culture.";
267 if (suggestedCulture != null)
268 ThrowParseException (fmt +
269 " Please try one of these: " + suggestedCulture);
271 ThrowParseException (fmt);
275 string tracestr = GetString (atts, "Trace", null);
276 if (tracestr != null) {
278 atts ["Trace"] = tracestr;
279 trace = GetBool (atts, "Trace", false);
282 string tracemodes = GetString (atts, "TraceMode", null);
283 if (tracemodes != null) {
286 tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
291 if (!valid || tracemode == TraceMode.Default)
292 ThrowParseException ("The 'tracemode' attribute is case sensitive and must be " +
293 "one of the following values: SortByTime, SortByCategory.");
296 errorPage = GetString (atts, "ErrorPage", null);
297 validateRequest = GetBool (atts, "ValidateRequest", validateRequest);
298 clientTarget = GetString (atts, "ClientTarget", null);
299 if (clientTarget != null) {
300 clientTarget = clientTarget.Trim ();
302 ClientTargetSection sec = (ClientTargetSection)WebConfigurationManager.GetSection ("system.web/clientTarget");
303 ClientTarget ct = null;
305 if ((ct = sec.ClientTargets [clientTarget]) == null)
306 clientTarget = clientTarget.ToLower (CultureInfo.InvariantCulture);
308 if (ct == null && (ct = sec.ClientTargets [clientTarget]) == null) {
309 ThrowParseException (String.Format (
310 "ClientTarget '{0}' is an invalid alias. See the " +
311 "documentation for <clientTarget> config. section.",
314 clientTarget = ct.UserAgent;
316 NameValueCollection coll;
317 coll = (NameValueCollection) Context.GetConfig ("system.web/clientTarget");
321 ct = coll [clientTarget];
323 ct = coll [clientTarget.ToLower ()];
327 ThrowParseException (String.Format (
328 "ClientTarget '{0}' is an invalid alias. See the " +
329 "documentation for <clientTarget> config. section.",
332 clientTarget = (string) ct;
336 notBuffer = !GetBool (atts, "Buffer", true);
339 async = GetBool (atts, "Async", false);
340 string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
341 if (asyncTimeoutVal != null) {
343 asyncTimeout = Int32.Parse (asyncTimeoutVal);
344 } catch (Exception) {
345 ThrowParseException ("AsyncTimeout must be an integer value");
349 masterPage = GetString (atts, "MasterPageFile", masterPage);
351 // Make sure the page exists
352 if (!String.IsNullOrEmpty (masterPage)) {
353 string path = MapPath (masterPage);
354 MasterPageParser.GetCompiledMasterType (masterPage, path, HttpContext.Current);
355 AddDependency (path);
358 title = GetString(atts, "Title", null);
360 theme = GetString (atts, "Theme", theme);
361 styleSheetTheme = GetString (atts, "StyleSheetTheme", styleSheetTheme);
362 enable_event_validation = GetBool (atts, "EnableEventValidation", true);
363 maintainScrollPositionOnPostBack = GetBool (atts, "MaintainScrollPositionOnPostBack", maintainScrollPositionOnPostBack);
366 GetString (atts, "EnableViewStateMac", null);
367 GetString (atts, "SmartNavigation", null);
369 base.ProcessMainAttributes (atts);
373 internal override void AddDirective (string directive, Hashtable atts)
375 bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
376 bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
377 StringComparison.OrdinalIgnoreCase) == 0;
379 string typeName = null;
380 string virtualPath = null;
383 if (isMasterType || isPreviousPageType) {
384 typeName = GetString (atts, "TypeName", null);
385 virtualPath = GetString (atts, "VirtualPath", null);
387 if (typeName != null && virtualPath != null)
388 ThrowParseException (
389 String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
390 if (typeName != null) {
391 type = LoadType (typeName);
393 ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
394 } else if (virtualPath != null) {
395 string mappedPath = MapPath (virtualPath);
397 type = masterType = MasterPageParser.GetCompiledMasterType (virtualPath,
399 HttpContext.Current);
401 type = previousPageType = GetCompiledPageType (virtualPath, mappedPath,
402 HttpContext.Current);
404 ThrowParseException (
405 String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
407 AddAssembly (type.Assembly, true);
409 base.AddDirective (directive, atts);
413 static string SuggestCulture (string culture)
415 string retval = null;
416 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
417 if (ci.Name.StartsWith (culture))
418 retval += ci.Name + " ";
423 public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
425 PageParser pp = new PageParser (virtualPath, inputFile, context);
426 return pp.CompileIntoType ();
429 protected override Type CompileIntoType ()
431 AspGenerator generator = new AspGenerator (this);
432 return generator.GetCompiledType ();
435 internal bool EnableSessionState {
437 return enableSessionState == PagesEnableSessionState.True ||
438 ReadOnlySessionState;
442 internal bool EnableViewStateMac {
443 get { return enableViewStateMac; }
446 internal bool SmartNavigation {
447 get { return smartNavigation; }
450 internal bool ReadOnlySessionState {
452 return enableSessionState == PagesEnableSessionState.ReadOnly;
456 internal bool HaveTrace {
457 get { return haveTrace; }
460 internal bool Trace {
461 get { return trace; }
464 internal TraceMode TraceMode {
465 get { return tracemode; }
468 internal override Type DefaultBaseType {
469 get { return baseType; }
472 internal override string DefaultBaseTypeName {
473 get { return "System.Web.UI.Page"; }
476 internal override string DefaultDirectiveName {
477 get { return "page"; }
480 internal string ResponseEncoding {
481 get { return responseEncoding; }
484 internal string ContentType {
485 get { return contentType; }
488 internal int CodePage {
489 get { return codepage; }
492 internal string Culture {
493 get { return culture; }
496 internal string UICulture {
497 get { return uiculture; }
504 internal string ErrorPage {
505 get { return errorPage; }
508 internal bool ValidateRequest {
509 get { return validateRequest; }
512 internal string ClientTarget {
513 get { return clientTarget; }
516 internal bool NotBuffer {
517 get { return notBuffer; }
521 internal bool Async {
522 get { return async; }
525 internal int AsyncTimeout {
526 get { return asyncTimeout; }
529 internal string Theme {
530 get { return theme; }
533 internal string StyleSheetTheme {
534 get { return styleSheetTheme; }
537 internal string MasterPageFile {
538 get { return masterPage; }
541 internal Type MasterType {
542 get { return masterType; }
545 internal string Title {
546 get { return title; }
549 internal bool EnableEventValidation {
550 get { return enable_event_validation; }
553 internal bool MaintainScrollPositionOnPostBack {
554 get { return maintainScrollPositionOnPostBack; }
557 internal int MaxPageStateFieldLength {
558 get { return maxPageStateFieldLength; }
561 internal string PageParserFilterType {
562 get { return pageParserFilter; }
565 internal Type PreviousPageType {
566 get { return previousPageType; }