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;
65 int asyncTimeout = -1;
70 string styleSheetTheme;
71 bool enable_event_validation;
72 bool maintainScrollPositionOnPostBack;
73 int maxPageStateFieldLength = -1;
74 string pageParserFilter = String.Empty;
75 Type previousPageType;
80 LoadConfigDefaults ();
83 internal PageParser (string virtualPath, string inputFile, HttpContext context)
86 BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
87 InputFile = inputFile;
89 AddApplicationAssembly ();
90 LoadConfigDefaults ();
92 this.VirtualPath = new VirtualPath (virtualPath);
97 internal PageParser (string virtualPath, TextReader reader, HttpContext context)
98 : this (virtualPath, null, reader, context)
102 internal PageParser (string virtualPath, string inputFile, TextReader reader, HttpContext context)
105 BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
107 if (String.IsNullOrEmpty (inputFile)) {
108 HttpRequest req = context != null ? context.Request : null;
110 InputFile = req.MapPath (virtualPath);
112 InputFile = inputFile;
114 AddApplicationAssembly ();
115 LoadConfigDefaults ();
117 this.VirtualPath = new VirtualPath (virtualPath);
122 internal override void LoadConfigDefaults ()
124 base.LoadConfigDefaults ();
126 PagesSection ps = PagesConfig;
128 PagesConfiguration ps = PagesConfig;
131 notBuffer = !ps.Buffer;
132 enableSessionState = ps.EnableSessionState;
133 enableViewStateMac = ps.EnableViewStateMac;
134 smartNavigation = ps.SmartNavigation;
135 validateRequest = ps.ValidateRequest;
137 masterPage = ps.MasterPageFile;
138 if (masterPage.Length == 0)
140 enable_event_validation = ps.EnableEventValidation;
141 maxPageStateFieldLength = ps.MaxPageStateFieldLength;
142 pageParserFilter = ps.PageParserFilterType;
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.GetSection ("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) Context.GetConfig ("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 // Make sure the page exists
371 if (!String.IsNullOrEmpty (masterPage)) {
372 BuildManager.GetCompiledType (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 typeName = GetString (atts, "TypeName", null);
403 virtualPath = GetString (atts, "VirtualPath", null);
405 if (typeName != null && virtualPath != null)
406 ThrowParseException (
407 String.Format ("The '{0}' directive must have exactly one attribute: TypeName or VirtualPath", directive));
408 if (typeName != null) {
409 type = LoadType (typeName);
411 ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
412 } else if (virtualPath != null) {
413 string mappedPath = MapPath (virtualPath);
415 type = masterType = BuildManager.GetCompiledType (virtualPath);
417 type = previousPageType = GetCompiledPageType (virtualPath, mappedPath,
418 HttpContext.Current);
420 ThrowParseException (
421 String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
423 AddAssembly (type.Assembly, true);
425 base.AddDirective (directive, atts);
429 static string SuggestCulture (string culture)
431 string retval = null;
432 foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
433 if (ci.Name.StartsWith (culture))
434 retval += ci.Name + " ";
439 public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
442 return BuildManager.GetCompiledType (virtualPath);
444 PageParser pp = new PageParser (virtualPath, inputFile, context);
445 return pp.CompileIntoType ();
449 protected override Type CompileIntoType ()
451 AspGenerator generator = new AspGenerator (this);
452 return generator.GetCompiledType ();
455 internal bool EnableSessionState {
457 return enableSessionState == PagesEnableSessionState.True ||
458 ReadOnlySessionState;
462 internal bool EnableViewStateMac {
463 get { return enableViewStateMac; }
466 internal bool SmartNavigation {
467 get { return smartNavigation; }
470 internal bool ReadOnlySessionState {
472 return enableSessionState == PagesEnableSessionState.ReadOnly;
476 internal bool HaveTrace {
477 get { return haveTrace; }
480 internal bool Trace {
481 get { return trace; }
484 internal TraceMode TraceMode {
485 get { return tracemode; }
489 internal override string DefaultBaseTypeName {
490 get { return PagesConfig.PageBaseType; }
493 internal override string DefaultBaseTypeName {
494 get { return "System.Web.UI.Page"; }
498 internal override string DefaultDirectiveName {
499 get { return "page"; }
502 internal string ResponseEncoding {
503 get { return responseEncoding; }
506 internal string ContentType {
507 get { return contentType; }
510 internal int CodePage {
511 get { return codepage; }
514 internal string Culture {
515 get { return culture; }
518 internal string UICulture {
519 get { return uiculture; }
526 internal string ErrorPage {
527 get { return errorPage; }
530 internal bool ValidateRequest {
531 get { return validateRequest; }
534 internal string ClientTarget {
535 get { return clientTarget; }
538 internal bool NotBuffer {
539 get { return notBuffer; }
543 internal bool Async {
544 get { return async; }
547 internal int AsyncTimeout {
548 get { return asyncTimeout; }
551 internal string Theme {
552 get { return theme; }
555 internal string StyleSheetTheme {
556 get { return styleSheetTheme; }
559 internal string MasterPageFile {
560 get { return masterPage; }
563 internal Type MasterType {
564 get { return masterType; }
567 internal string Title {
568 get { return title; }
571 internal bool EnableEventValidation {
572 get { return enable_event_validation; }
575 internal bool MaintainScrollPositionOnPostBack {
576 get { return maintainScrollPositionOnPostBack; }
579 internal int MaxPageStateFieldLength {
580 get { return maxPageStateFieldLength; }
583 internal string PageParserFilterType {
584 get { return pageParserFilter; }
587 internal Type PreviousPageType {
588 get { return previousPageType; }