svn path=/trunk/mcs/; revision=104772
[mono.git] / mcs / class / System.Web / System.Web.UI / PageParser.cs
1 //      
2 // System.Web.UI.PageParser
3 //
4 // Authors:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
9 //
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:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
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.
28 //
29
30 using System.Collections;
31 using System.Collections.Specialized;
32 using System.Globalization;
33 using System.Security.Permissions;
34 using System.Text;
35 using System.Web.Compilation;
36 using System.Web.Configuration;
37 using System.Web.Util;
38 using System.IO;
39
40 namespace System.Web.UI
41 {
42         // CAS - no InheritanceDemand here as the class is sealed
43         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
44         public sealed class PageParser : TemplateControlParser
45         {
46                 PagesEnableSessionState enableSessionState = PagesEnableSessionState.True;
47                 bool enableViewStateMac = true;
48                 bool smartNavigation;
49                 bool haveTrace;
50                 bool trace;
51                 bool notBuffer;
52                 TraceMode tracemode = TraceMode.Default;
53                 string responseEncoding;
54                 string contentType;
55                 int codepage = -1;
56                 int lcid = -1;
57                 string culture;
58                 string uiculture;
59                 string errorPage;
60                 bool validateRequest;
61                 string clientTarget;
62                 Type baseType = typeof (Page);
63
64 #if NET_2_0
65                 bool async;
66                 int asyncTimeout = -1;
67                 string masterPage;
68                 Type masterType;
69                 string title;
70                 string theme;
71                 string styleSheetTheme;
72                 bool enable_event_validation;
73                 bool maintainScrollPositionOnPostBack;
74                 int maxPageStateFieldLength = -1;
75                 string pageParserFilter = String.Empty;
76                 Type previousPageType;
77 #endif
78
79                 public PageParser ()
80                 {
81                         LoadConfigDefaults ();
82                 }
83                 
84                 internal PageParser (string virtualPath, string inputFile, HttpContext context)
85                 {
86                         Context = context;
87                         BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
88                         InputFile = inputFile;
89                         SetBaseType (null);
90                         AddApplicationAssembly ();
91                         LoadConfigDefaults ();
92 #if NET_2_0
93                         this.VirtualPath = new VirtualPath (virtualPath);
94 #endif
95                 }
96
97 #if NET_2_0
98                 internal PageParser (string virtualPath, TextReader reader, HttpContext context)
99                         : this (virtualPath, null, reader, context)
100                 {
101                 }
102                 
103                 internal PageParser (string virtualPath, string inputFile, TextReader reader, HttpContext context)
104                 {
105                         Context = context;
106                         BaseVirtualDir = UrlUtils.GetDirectory (virtualPath);
107                         Reader = reader;
108                         if (String.IsNullOrEmpty (inputFile)) {
109                                 HttpRequest req = context != null ? context.Request : null;
110                                 if (req != null)
111                                         InputFile = req.MapPath (virtualPath);
112                         } else
113                                 InputFile = inputFile;
114                         SetBaseType (null);
115                         AddApplicationAssembly ();
116                         LoadConfigDefaults ();
117 #if NET_2_0
118                         this.VirtualPath = new VirtualPath (virtualPath);
119 #endif
120                 }
121 #endif
122
123                 internal override void LoadConfigDefaults ()
124                 {
125                         base.LoadConfigDefaults ();
126 #if NET_2_0
127                         PagesSection ps = PagesConfig;
128 #else
129                         PagesConfiguration ps = PagesConfig;
130 #endif                  
131
132                         notBuffer = !ps.Buffer;
133                         enableSessionState = ps.EnableSessionState;
134                         enableViewStateMac = ps.EnableViewStateMac;
135                         smartNavigation = ps.SmartNavigation;
136                         validateRequest = ps.ValidateRequest;
137 #if NET_2_0
138                         masterPage = ps.MasterPageFile;
139                         if (masterPage.Length == 0)
140                                 masterPage = null;
141                         
142                         enable_event_validation = ps.EnableEventValidation;
143                         maxPageStateFieldLength = ps.MaxPageStateFieldLength;
144                         pageParserFilter = ps.PageParserFilterType;
145                         theme = ps.Theme;
146                         if (theme.Length == 0)
147                                 theme = null;
148                         styleSheetTheme = ps.StyleSheetTheme;
149                         if (styleSheetTheme.Length == 0)
150                                 styleSheetTheme = null;
151                         maintainScrollPositionOnPostBack = ps.MaintainScrollPositionOnPostBack;
152 #endif
153                 }
154                 
155                 public static IHttpHandler GetCompiledPageInstance (string virtualPath,
156                                                                     string inputFile, 
157                                                                     HttpContext context)
158                 {
159 #if NET_2_0
160                         return BuildManager.CreateInstanceFromVirtualPath (virtualPath, typeof (IHttpHandler)) as IHttpHandler;
161 #else
162                         PageParser pp = new PageParser (virtualPath, inputFile, context);
163                         IHttpHandler h = (IHttpHandler) pp.GetCompiledInstance ();
164                         return h;
165 #endif
166                 }
167                 
168                 internal override void ProcessMainAttributes (Hashtable atts)
169                 {
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;
181                                 else
182                                         ThrowParseException ("Invalid value for enableSessionState: " + enabless);
183                         }
184
185                         string cp = GetString (atts, "CodePage", null);
186                         if (cp != null) {
187                                 if (responseEncoding != null)
188                                         ThrowParseException ("CodePage and ResponseEncoding are " +
189                                                 "mutually exclusive.");
190
191                                 int codepage = 0;
192                                 try {
193                                         codepage = (int) UInt32.Parse (cp);
194                                 } catch {
195                                         ThrowParseException ("Invalid value for CodePage: " + cp);
196                                 }
197
198                                 try {
199                                         Encoding.GetEncoding (codepage);
200                                 } catch {
201                                         ThrowParseException ("Unsupported codepage: " + cp);
202                                 }
203                         }
204                         
205                         responseEncoding = GetString (atts, "ResponseEncoding", null);
206                         if (responseEncoding != null) {
207                                 if (codepage != -1)
208                                         ThrowParseException ("CodePage and ResponseEncoding are " +
209                                                              "mutually exclusive.");
210
211                                 try {
212                                         Encoding.GetEncoding (responseEncoding);
213                                 } catch {
214                                         ThrowParseException ("Unsupported encoding: " + responseEncoding);
215                                 }
216                         }
217                         
218                         contentType = GetString (atts, "ContentType", null);
219
220                         string lcidStr = GetString (atts, "LCID", null);
221                         if (lcidStr != null) {
222                                 try {
223                                         lcid = (int) UInt32.Parse (lcidStr);
224                                 } catch {
225                                         ThrowParseException ("Invalid value for LCID: " + lcid);
226                                 }
227
228                                 CultureInfo ci = null;
229                                 try {
230                                         ci = new CultureInfo (lcid);
231                                 } catch {
232                                         ThrowParseException ("Unsupported LCID: " + lcid);
233                                 }
234
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: " +
240                                                                      suggestedCulture);
241                                         } else {
242                                                 ThrowParseException (fmt);
243                                         }
244                                 }
245                         }
246
247                         culture = GetString (atts, "Culture", null);
248                         if (culture != null) {
249                                 if (lcidStr != null) 
250                                         ThrowParseException ("Culture and LCID are mutually exclusive.");
251                                 
252                                 CultureInfo ci = null;
253                                 try {
254 #if NET_2_0
255                                         if (!culture.StartsWith ("auto"))
256 #endif
257                                                 ci = new CultureInfo (culture);
258                                 } catch {
259                                         ThrowParseException ("Unsupported Culture: " + culture);
260                                 }
261
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);
268                                         else
269                                                 ThrowParseException (fmt);
270                                 }
271                         }
272
273                         uiculture = GetString (atts, "UICulture", null);
274                         if (uiculture != null) {
275                                 CultureInfo ci = null;
276                                 try {
277 #if NET_2_0
278                                         if (!uiculture.StartsWith ("auto"))
279 #endif
280                                                 ci = new CultureInfo (uiculture);
281                                 } catch {
282                                         ThrowParseException ("Unsupported Culture: " + uiculture);
283                                 }
284
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);
291                                         else
292                                                 ThrowParseException (fmt);
293                                 }
294                         }
295
296                         string tracestr = GetString (atts, "Trace", null);
297                         if (tracestr != null) {
298                                 haveTrace = true;
299                                 atts ["Trace"] = tracestr;
300                                 trace = GetBool (atts, "Trace", false);
301                         }
302
303                         string tracemodes = GetString (atts, "TraceMode", null);
304                         if (tracemodes != null) {
305                                 bool valid = true;
306                                 try {
307                                         tracemode = (TraceMode) Enum.Parse (typeof (TraceMode), tracemodes, false);
308                                 } catch {
309                                         valid = false;
310                                 }
311
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.");
315                         }
316
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 ();
322 #if NET_2_0
323                                 ClientTargetSection sec = (ClientTargetSection)WebConfigurationManager.GetSection ("system.web/clientTarget");
324                                 ClientTarget ct = null;
325                                 
326                                 if ((ct = sec.ClientTargets [clientTarget]) == null)
327                                         clientTarget = clientTarget.ToLower (CultureInfo.InvariantCulture);
328                                 
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.",
333                                                         clientTarget));
334                                 }
335                                 clientTarget = ct.UserAgent;
336 #else
337                                 NameValueCollection coll;
338                                 coll = (NameValueCollection) Context.GetConfig ("system.web/clientTarget");
339                                 object ct = null;
340                                 
341                                 if (coll != null) {
342                                         ct = coll [clientTarget];
343                                         if (ct == null)
344                                                 ct = coll [clientTarget.ToLower ()];
345                                 }
346                                 
347                                 if (ct == null) {
348                                         ThrowParseException (String.Format (
349                                                         "ClientTarget '{0}' is an invalid alias. See the " +
350                                                         "documentation for <clientTarget> config. section.",
351                                                         clientTarget));
352                                 }
353                                 clientTarget = (string) ct;
354 #endif
355                         }
356
357                         notBuffer = !GetBool (atts, "Buffer", true);
358                         
359 #if NET_2_0
360                         async = GetBool (atts, "Async", false);
361                         string asyncTimeoutVal = GetString (atts, "AsyncTimeout", null);
362                         if (asyncTimeoutVal != null) {
363                                 try {
364                                         asyncTimeout = Int32.Parse (asyncTimeoutVal);
365                                 } catch (Exception) {
366                                         ThrowParseException ("AsyncTimeout must be an integer value");
367                                 }
368                         }
369                         
370                         masterPage = GetString (atts, "MasterPageFile", masterPage);
371                         
372                         // Make sure the page exists
373                         if (!String.IsNullOrEmpty (masterPage)) {
374                                 BuildManager.GetCompiledType (masterPage);
375                                 AddDependency (masterPage);
376                         }
377                         
378                         title = GetString(atts, "Title", null);
379
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);
384 #endif
385                         // Ignored by now
386                         GetString (atts, "EnableViewStateMac", null);
387                         GetString (atts, "SmartNavigation", null);
388
389                         base.ProcessMainAttributes (atts);
390                 }
391                 
392 #if NET_2_0
393                 internal override void AddDirective (string directive, Hashtable atts)
394                 {                       
395                         bool isMasterType = String.Compare ("MasterType", directive, StringComparison.OrdinalIgnoreCase) == 0;
396                         bool isPreviousPageType = isMasterType ? false : String.Compare ("PreviousPageType", directive,
397                                                                                          StringComparison.OrdinalIgnoreCase) == 0;
398                         
399                         string typeName = null;
400                         string virtualPath = null;
401                         Type type = null;
402                         
403                         if (isMasterType || isPreviousPageType) {
404                                 typeName = GetString (atts, "TypeName", null);
405                                 virtualPath = GetString (atts, "VirtualPath", null);
406
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);
412                                         if (type == null)
413                                                 ThrowParseException (String.Format ("Could not load type '{0}'.", typeName));
414                                 } else if (virtualPath != null) {
415                                         string mappedPath = MapPath (virtualPath);
416                                         if (isMasterType)
417                                                 type = masterType = BuildManager.GetCompiledType (virtualPath);
418                                         else
419                                                 type = previousPageType = GetCompiledPageType (virtualPath, mappedPath,
420                                                                                                HttpContext.Current);
421                                 } else
422                                         ThrowParseException (
423                                                 String.Format ("The {0} directive must have either a TypeName or a VirtualPath attribute.", directive));
424
425                                 AddAssembly (type.Assembly, true);
426                         } else
427                                 base.AddDirective (directive, atts);
428                 }
429 #endif
430                 
431                 static string SuggestCulture (string culture)
432                 {
433                         string retval = null;
434                         foreach (CultureInfo ci in CultureInfo.GetCultures (CultureTypes.SpecificCultures)) {
435                                 if (ci.Name.StartsWith (culture))
436                                         retval += ci.Name + " ";
437                         }
438                         return retval;
439                 }
440
441                 public static Type GetCompiledPageType (string virtualPath, string inputFile, HttpContext context)
442                 {
443 #if NET_2_0
444                         return BuildManager.GetCompiledType (virtualPath);
445 #else
446                         PageParser pp = new PageParser (virtualPath, inputFile, context);
447                         return pp.CompileIntoType ();
448 #endif
449                 }
450                 
451                 protected override Type CompileIntoType ()
452                 {
453                         AspGenerator generator = new AspGenerator (this);
454                         return generator.GetCompiledType ();
455                 }
456
457                 internal bool EnableSessionState {
458                         get {
459                                 return enableSessionState == PagesEnableSessionState.True ||
460                                         ReadOnlySessionState;
461                         }
462                 }
463
464                 internal bool EnableViewStateMac {
465                         get { return enableViewStateMac; }
466                 }
467                 
468                 internal bool SmartNavigation {
469                         get { return smartNavigation; }
470                 }
471                 
472                 internal bool ReadOnlySessionState {
473                         get {
474                                 return enableSessionState == PagesEnableSessionState.ReadOnly;
475                         }
476                 }
477
478                 internal bool HaveTrace {
479                         get { return haveTrace; }
480                 }
481
482                 internal bool Trace {
483                         get { return trace; }
484                 }
485
486                 internal TraceMode TraceMode {
487                         get { return tracemode; }
488                 }               
489
490 #if NET_2_0
491                 internal override string DefaultBaseTypeName {
492                         get { return PagesConfig.PageBaseType; }
493                 }
494 #else
495                 internal override string DefaultBaseTypeName {
496                         get { return "System.Web.UI.Page"; }
497                 }
498 #endif
499                 
500                 internal override string DefaultDirectiveName {
501                         get { return "page"; }
502                 }
503
504                 internal string ResponseEncoding {
505                         get { return responseEncoding; }
506                 }
507
508                 internal string ContentType {
509                         get { return contentType; }
510                 }
511
512                 internal int CodePage {
513                         get { return codepage; }
514                 }
515
516                 internal string Culture {
517                         get { return culture; }
518                 }
519
520                 internal string UICulture {
521                         get { return uiculture; }
522                 }
523
524                 internal int LCID {
525                         get { return lcid; }
526                 }
527
528                 internal string ErrorPage {
529                         get { return errorPage; }
530                 }
531
532                 internal bool ValidateRequest {
533                         get { return validateRequest; }
534                 }
535
536                 internal string ClientTarget {
537                         get { return clientTarget; }
538                 }
539
540                 internal bool NotBuffer {
541                         get { return notBuffer; }
542                 }
543
544 #if NET_2_0
545                 internal bool Async {
546                         get { return async; }
547                 }
548
549                 internal int AsyncTimeout {
550                         get { return asyncTimeout; }
551                 }
552                 
553                 internal string Theme {
554                         get { return theme; }
555                 }
556
557                 internal string StyleSheetTheme {
558                         get { return styleSheetTheme; }
559                 }
560
561                 internal string MasterPageFile {
562                         get { return masterPage; }
563                 }
564                 
565                 internal Type MasterType {
566                         get { return masterType; }
567                 }
568
569                 internal string Title {
570                         get { return title; }
571                 }
572
573                 internal bool EnableEventValidation {
574                         get { return enable_event_validation; }
575                 }
576
577                 internal bool MaintainScrollPositionOnPostBack {
578                         get { return maintainScrollPositionOnPostBack; }
579                 }
580
581                 internal int MaxPageStateFieldLength {
582                         get { return maxPageStateFieldLength; }
583                 }
584
585                 internal string PageParserFilterType {
586                         get { return pageParserFilter; }
587                 }
588
589                 internal Type PreviousPageType {
590                         get { return previousPageType; }
591                 }
592 #endif
593         }
594 }
595