2 // System.Web.UI.TemplateParser
5 // Duncan Mak (duncan@ximian.com)
6 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
8 // (C) 2002,2003 Ximian, Inc. (http://www.ximian.com)
9 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.CodeDom.Compiler;
32 using System.Collections;
34 using System.Reflection;
35 using System.Security.Permissions;
36 using System.Web.Compilation;
37 using System.Web.Configuration;
38 using System.Web.Util;
40 namespace System.Web.UI {
43 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
44 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
45 public abstract class TemplateParser : BaseParser
49 string privateBinPath;
50 Hashtable mainAttributes;
51 ArrayList dependencies;
59 RootBuilder rootBuilder;
61 string compilerOptions;
63 bool strictOn = false;
64 bool explicitOn = false;
67 string oc_header, oc_custom, oc_param, oc_controls;
69 OutputCacheLocation oc_location;
72 string partialClassName;
75 int appAssemblyIndex = -1;
77 [MonoTODO ("deal with AddAssembliesInBin in the 2.0 case")]
78 internal TemplateParser ()
80 imports = new ArrayList ();
81 imports.Add ("System");
82 imports.Add ("System.Collections");
83 imports.Add ("System.Collections.Specialized");
84 imports.Add ("System.Configuration");
85 imports.Add ("System.Text");
86 imports.Add ("System.Text.RegularExpressions");
87 imports.Add ("System.Web");
88 imports.Add ("System.Web.Caching");
89 imports.Add ("System.Web.Security");
90 imports.Add ("System.Web.SessionState");
91 imports.Add ("System.Web.UI");
92 imports.Add ("System.Web.UI.WebControls");
93 imports.Add ("System.Web.UI.HtmlControls");
95 assemblies = new ArrayList ();
97 foreach (AssemblyInfo info in CompilationConfig.Assemblies)
98 AddAssemblyByName (info.Assembly);
100 foreach (string a in CompilationConfig.Assemblies)
101 AddAssemblyByName (a);
102 if (CompilationConfig.AssembliesInBin)
103 AddAssembliesInBin ();
106 language = CompilationConfig.DefaultLanguage;
109 internal void AddApplicationAssembly ()
111 string location = Context.ApplicationInstance.AssemblyLocation;
112 if (location != typeof (TemplateParser).Assembly.Location) {
113 appAssemblyIndex = assemblies.Add (location);
117 protected abstract Type CompileIntoType ();
119 internal virtual void HandleOptions (object obj)
123 internal static string GetOneKey (Hashtable tbl)
125 foreach (object key in tbl.Keys)
126 return key.ToString ();
131 internal virtual void AddDirective (string directive, Hashtable atts)
133 if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
134 if (mainAttributes != null)
135 ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
137 mainAttributes = atts;
138 ProcessMainAttributes (mainAttributes);
142 int cmp = String.Compare ("Assembly", directive, true);
144 string name = GetString (atts, "Name", null);
145 string src = GetString (atts, "Src", null);
148 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
150 if (name == null && src == null)
151 ThrowParseException ("You gotta specify Src or Name");
153 if (name != null && src != null)
154 ThrowParseException ("Src and Name cannot be used together");
157 AddAssemblyByName (name);
159 GetAssemblyFromSource (src);
165 cmp = String.Compare ("Import", directive, true);
167 string namesp = GetString (atts, "Namespace", null);
169 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
171 if (namesp != null && namesp != "")
176 cmp = String.Compare ("Implements", directive, true);
178 string ifacename = GetString (atts, "Interface", "");
181 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
183 Type iface = LoadType (ifacename);
185 ThrowParseException ("Cannot find type " + ifacename);
187 if (!iface.IsInterface)
188 ThrowParseException (iface + " is not an interface");
190 AddInterface (iface.FullName);
194 cmp = String.Compare ("OutputCache", directive, true);
198 if (atts ["Duration"] == null)
199 ThrowParseException ("The directive is missing a 'duration' attribute.");
200 if (atts ["VaryByParam"] == null)
201 ThrowParseException ("This directive is missing a 'VaryByParam' " +
202 "attribute, which should be set to \"none\", \"*\", " +
203 "or a list of name/value pairs.");
205 foreach (DictionaryEntry entry in atts) {
206 string key = (string) entry.Key;
207 switch (key.ToLower ()) {
209 oc_duration = Int32.Parse ((string) entry.Value);
211 ThrowParseException ("The 'duration' attribute must be set " +
212 "to a positive integer value");
215 oc_param = (string) entry.Value;
216 if (String.Compare (oc_param, "none") == 0)
220 oc_header = (string) entry.Value;
223 oc_custom = (string) entry.Value;
226 if (!(this is PageParser))
230 oc_location = (OutputCacheLocation) Enum.Parse (
231 typeof (OutputCacheLocation), (string) entry.Value, true);
233 ThrowParseException ("The 'location' attribute is case sensitive and " +
234 "must be one of the following values: Any, Client, " +
235 "Downstream, Server, None, ServerAndClient.");
238 case "varybycontrol":
239 if (this is PageParser)
242 oc_controls = (string) entry.Value;
245 if (this is PageParser)
249 oc_shared = Boolean.Parse ((string) entry.Value);
251 ThrowParseException ("The 'shared' attribute is case sensitive" +
252 " and must be set to 'true' or 'false'.");
256 ThrowParseException ("The '" + key + "' attribute is not " +
257 "supported by the 'Outputcache' directive.");
266 ThrowParseException ("Unknown directive: " + directive);
269 internal Type LoadType (string typeName)
271 // First try loaded assemblies, then try assemblies in Bin directory.
273 bool seenBin = false;
274 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
275 foreach (Assembly ass in assemblies) {
276 type = ass.GetType (typeName);
280 if (Path.GetDirectoryName (ass.Location) != PrivateBinPath) {
281 AddAssembly (ass, true);
286 AddDependency (ass.Location);
294 if (!Directory.Exists (PrivateBinPath))
297 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
298 foreach (string s in binDlls) {
299 Assembly binA = Assembly.LoadFrom (s);
300 type = binA.GetType (typeName);
304 AddDependency (binA.Location);
311 void AddAssembliesInBin ()
313 if (!Directory.Exists (PrivateBinPath))
316 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
317 foreach (string s in binDlls) {
322 internal virtual void AddInterface (string iface)
324 if (interfaces == null)
325 interfaces = new ArrayList ();
327 if (!interfaces.Contains (iface))
328 interfaces.Add (iface);
331 internal virtual void AddImport (string namesp)
334 imports = new ArrayList ();
336 if (!imports.Contains (namesp))
337 imports.Add (namesp);
340 internal virtual void AddSourceDependency (string filename)
342 if (dependencies != null && dependencies.Contains (filename)) {
343 ThrowParseException ("Circular file references are not allowed. File: " + filename);
346 AddDependency (filename);
349 internal virtual void AddDependency (string filename)
354 if (dependencies == null)
355 dependencies = new ArrayList ();
357 if (!dependencies.Contains (filename))
358 dependencies.Add (filename);
361 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
363 if (assembly.Location == "")
367 anames = new Hashtable ();
369 string name = assembly.GetName ().Name;
370 string loc = assembly.Location;
372 if (!assemblies.Contains (loc)) {
373 assemblies.Add (loc);
377 anames [loc] = assembly;
379 if (!assemblies.Contains (name)) {
380 assemblies.Add (name);
383 anames [name] = assembly;
387 internal virtual Assembly AddAssemblyByName (string name)
390 anames = new Hashtable ();
392 if (anames.Contains (name)) {
393 object o = anames [name];
400 Assembly assembly = null;
401 Exception error = null;
402 if (name.IndexOf (',') != -1) {
404 assembly = Assembly.Load (name);
405 } catch (Exception e) { error = e; }
408 if (assembly == null) {
410 assembly = Assembly.LoadWithPartialName (name);
411 } catch (Exception e) { error = e; }
414 if (assembly == null)
415 ThrowParseException ("Assembly " + name + " not found", error);
417 AddAssembly (assembly, true);
421 internal virtual void ProcessMainAttributes (Hashtable atts)
423 atts.Remove ("Description"); // ignored
425 atts.Remove ("CodeBehind"); // ignored
427 atts.Remove ("AspCompat"); // ignored
429 debug = GetBool (atts, "Debug", true);
430 compilerOptions = GetString (atts, "CompilerOptions", "");
431 language = GetString (atts, "Language", CompilationConfig.DefaultLanguage);
432 strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
433 explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
435 string inherits = GetString (atts, "Inherits", null);
437 // In ASP 2, the source file is actually integrated with
438 // the generated file via the use of partial classes. This
439 // means that the code file has to be confirmed, but not
440 // used at this point.
441 src = GetString (atts, "CodeFile", null);
443 if (src != null && inherits != null) {
444 // Make sure the source exists
445 src = UrlUtils.Combine (BaseVirtualDir, src);
446 string realPath = MapPath (src, false);
447 if (!File.Exists (realPath))
448 ThrowParseException ("File " + src + " not found");
450 // Verify that the inherits is a valid identify not a
451 // fully-qualified name.
452 if (!CodeGenerator.IsValidLanguageIndependentIdentifier (inherits))
453 ThrowParseException (String.Format ("'{0}' is not valid for 'inherits'", inherits));
455 // We are going to create a partial class that shares
456 // the same name as the inherits tag, so reset the
457 // name. The base type is changed because it is the
458 // code file's responsibilty to extend the classes
460 partialClassName = inherits;
462 // Add the code file as an option to the
463 // compiler. This lets both files be compiled at once.
464 compilerOptions += " " + realPath;
465 } else if (inherits != null) {
466 // We just set the inherits directly because this is a
467 // Single-Page model.
468 SetBaseType (inherits);
471 string src = GetString (atts, "Src", null);
474 srcAssembly = GetAssemblyFromSource (src);
476 if (inherits != null)
477 SetBaseType (inherits);
479 className = GetString (atts, "ClassName", null);
480 if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className))
481 ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className));
485 ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
488 internal void SetBaseType (string type)
490 if (type == DefaultBaseTypeName)
494 if (srcAssembly != null)
495 parent = srcAssembly.GetType (type);
498 parent = LoadType (type);
501 ThrowParseException ("Cannot find type " + type);
503 if (!DefaultBaseType.IsAssignableFrom (parent))
504 ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
509 Assembly GetAssemblyFromSource (string vpath)
511 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
512 string realPath = MapPath (vpath, false);
513 if (!File.Exists (realPath))
514 ThrowParseException ("File " + vpath + " not found");
516 AddSourceDependency (realPath);
518 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
519 if (result.NativeCompilerReturnValue != 0) {
520 StreamReader reader = new StreamReader (realPath);
521 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
524 AddAssembly (result.CompiledAssembly, true);
525 return result.CompiledAssembly;
528 internal abstract Type DefaultBaseType { get; }
529 internal abstract string DefaultBaseTypeName { get; }
530 internal abstract string DefaultDirectiveName { get; }
532 internal string InputFile
534 get { return inputFile; }
535 set { inputFile = value; }
539 internal bool IsPartial
541 get { return src != null; }
544 internal string PartialClassName
546 get { return partialClassName; }
553 set { text = value; }
556 internal Type BaseType
559 if (baseType == null)
560 baseType = DefaultBaseType;
566 internal string ClassName {
568 if (className != null)
571 className = Path.GetFileName (inputFile).Replace ('.', '_');
572 className = className.Replace ('-', '_');
573 className = className.Replace (' ', '_');
575 if (Char.IsDigit(className[0])) {
576 className = "_" + className;
583 internal string PrivateBinPath {
585 if (privateBinPath != null)
586 return privateBinPath;
588 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
589 privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
591 return privateBinPath;
595 internal ArrayList Scripts {
598 scripts = new ArrayList ();
604 internal ArrayList Imports {
605 get { return imports; }
608 internal ArrayList Assemblies {
610 if (appAssemblyIndex != -1) {
611 object o = assemblies [appAssemblyIndex];
612 assemblies.RemoveAt (appAssemblyIndex);
614 appAssemblyIndex = -1;
621 internal ArrayList Interfaces {
622 get { return interfaces; }
625 internal RootBuilder RootBuilder {
626 get { return rootBuilder; }
627 set { rootBuilder = value; }
630 internal ArrayList Dependencies {
631 get { return dependencies; }
632 set { dependencies = value; }
635 internal string CompilerOptions {
636 get { return compilerOptions; }
639 internal string Language {
640 get { return language; }
643 internal bool StrictOn {
644 get { return strictOn; }
647 internal bool ExplicitOn {
648 get { return explicitOn; }
651 internal bool Debug {
652 get { return debug; }
655 internal bool OutputCache {
656 get { return output_cache; }
659 internal int OutputCacheDuration {
660 get { return oc_duration; }
663 internal string OutputCacheVaryByHeader {
664 get { return oc_header; }
667 internal string OutputCacheVaryByCustom {
668 get { return oc_custom; }
671 internal string OutputCacheVaryByControls {
672 get { return oc_controls; }
675 internal bool OutputCacheShared {
676 get { return oc_shared; }
679 internal OutputCacheLocation OutputCacheLocation {
680 get { return oc_location; }
683 internal string OutputCacheVaryByParam {
684 get { return oc_param; }
687 #if CONFIGURATION_2_0
688 internal PagesSection PagesConfig {
690 return WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
694 internal PagesConfiguration PagesConfig {
695 get { return PagesConfiguration.GetInstance (Context); }