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 internal TemplateParser ()
79 imports = new ArrayList ();
80 imports.Add ("System");
81 imports.Add ("System.Collections");
82 imports.Add ("System.Collections.Specialized");
83 imports.Add ("System.Configuration");
84 imports.Add ("System.Text");
85 imports.Add ("System.Text.RegularExpressions");
86 imports.Add ("System.Web");
87 imports.Add ("System.Web.Caching");
88 imports.Add ("System.Web.Security");
89 imports.Add ("System.Web.SessionState");
90 imports.Add ("System.Web.UI");
91 imports.Add ("System.Web.UI.WebControls");
92 imports.Add ("System.Web.UI.HtmlControls");
94 assemblies = new ArrayList ();
96 bool addAssembliesInBin = false;
97 foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
98 if (info.Assembly == "*")
99 addAssembliesInBin = true;
101 AddAssemblyByName (info.Assembly);
103 if (addAssembliesInBin)
104 AddAssembliesInBin ();
106 foreach (NamespaceInfo info in PagesConfig.Namespaces) {
107 imports.Add (info.Namespace);
110 foreach (string a in CompilationConfig.Assemblies)
111 AddAssemblyByName (a);
112 if (CompilationConfig.AssembliesInBin)
113 AddAssembliesInBin ();
116 language = CompilationConfig.DefaultLanguage;
119 internal void AddApplicationAssembly ()
121 string location = Context.ApplicationInstance.AssemblyLocation;
122 if (location != typeof (TemplateParser).Assembly.Location) {
123 appAssemblyIndex = assemblies.Add (location);
127 protected abstract Type CompileIntoType ();
129 internal virtual void HandleOptions (object obj)
133 internal static string GetOneKey (Hashtable tbl)
135 foreach (object key in tbl.Keys)
136 return key.ToString ();
141 internal virtual void AddDirective (string directive, Hashtable atts)
143 if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
144 if (mainAttributes != null)
145 ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
147 mainAttributes = atts;
148 ProcessMainAttributes (mainAttributes);
152 int cmp = String.Compare ("Assembly", directive, true);
154 string name = GetString (atts, "Name", null);
155 string src = GetString (atts, "Src", null);
158 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
160 if (name == null && src == null)
161 ThrowParseException ("You gotta specify Src or Name");
163 if (name != null && src != null)
164 ThrowParseException ("Src and Name cannot be used together");
167 AddAssemblyByName (name);
169 GetAssemblyFromSource (src);
175 cmp = String.Compare ("Import", directive, true);
177 string namesp = GetString (atts, "Namespace", null);
179 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
181 if (namesp != null && namesp != "")
186 cmp = String.Compare ("Implements", directive, true);
188 string ifacename = GetString (atts, "Interface", "");
191 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
193 Type iface = LoadType (ifacename);
195 ThrowParseException ("Cannot find type " + ifacename);
197 if (!iface.IsInterface)
198 ThrowParseException (iface + " is not an interface");
200 AddInterface (iface.FullName);
204 cmp = String.Compare ("OutputCache", directive, true);
208 if (atts ["Duration"] == null)
209 ThrowParseException ("The directive is missing a 'duration' attribute.");
210 if (atts ["VaryByParam"] == null)
211 ThrowParseException ("This directive is missing a 'VaryByParam' " +
212 "attribute, which should be set to \"none\", \"*\", " +
213 "or a list of name/value pairs.");
215 foreach (DictionaryEntry entry in atts) {
216 string key = (string) entry.Key;
217 switch (key.ToLower ()) {
219 oc_duration = Int32.Parse ((string) entry.Value);
221 ThrowParseException ("The 'duration' attribute must be set " +
222 "to a positive integer value");
225 oc_param = (string) entry.Value;
226 if (String.Compare (oc_param, "none") == 0)
230 oc_header = (string) entry.Value;
233 oc_custom = (string) entry.Value;
236 if (!(this is PageParser))
240 oc_location = (OutputCacheLocation) Enum.Parse (
241 typeof (OutputCacheLocation), (string) entry.Value, true);
243 ThrowParseException ("The 'location' attribute is case sensitive and " +
244 "must be one of the following values: Any, Client, " +
245 "Downstream, Server, None, ServerAndClient.");
248 case "varybycontrol":
249 if (this is PageParser)
252 oc_controls = (string) entry.Value;
255 if (this is PageParser)
259 oc_shared = Boolean.Parse ((string) entry.Value);
261 ThrowParseException ("The 'shared' attribute is case sensitive" +
262 " and must be set to 'true' or 'false'.");
266 ThrowParseException ("The '" + key + "' attribute is not " +
267 "supported by the 'Outputcache' directive.");
276 ThrowParseException ("Unknown directive: " + directive);
279 internal Type LoadType (string typeName)
281 // First try loaded assemblies, then try assemblies in Bin directory.
283 bool seenBin = false;
284 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
285 foreach (Assembly ass in assemblies) {
286 type = ass.GetType (typeName);
290 if (Path.GetDirectoryName (ass.Location) != PrivateBinPath) {
291 AddAssembly (ass, true);
296 AddDependency (ass.Location);
304 if (!Directory.Exists (PrivateBinPath))
307 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
308 foreach (string s in binDlls) {
309 Assembly binA = Assembly.LoadFrom (s);
310 type = binA.GetType (typeName);
314 AddDependency (binA.Location);
321 void AddAssembliesInBin ()
323 if (!Directory.Exists (PrivateBinPath))
326 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
327 foreach (string s in binDlls) {
332 internal virtual void AddInterface (string iface)
334 if (interfaces == null)
335 interfaces = new ArrayList ();
337 if (!interfaces.Contains (iface))
338 interfaces.Add (iface);
341 internal virtual void AddImport (string namesp)
344 imports = new ArrayList ();
346 if (!imports.Contains (namesp))
347 imports.Add (namesp);
350 internal virtual void AddSourceDependency (string filename)
352 if (dependencies != null && dependencies.Contains (filename)) {
353 ThrowParseException ("Circular file references are not allowed. File: " + filename);
356 AddDependency (filename);
359 internal virtual void AddDependency (string filename)
364 if (dependencies == null)
365 dependencies = new ArrayList ();
367 if (!dependencies.Contains (filename))
368 dependencies.Add (filename);
371 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
373 if (assembly.Location == "")
377 anames = new Hashtable ();
379 string name = assembly.GetName ().Name;
380 string loc = assembly.Location;
382 if (!assemblies.Contains (loc)) {
383 assemblies.Add (loc);
387 anames [loc] = assembly;
389 if (!assemblies.Contains (name)) {
390 assemblies.Add (name);
393 anames [name] = assembly;
397 internal virtual Assembly AddAssemblyByFileName (string filename)
399 Assembly assembly = null;
400 Exception error = null;
403 assembly = Assembly.LoadFrom (filename);
404 } catch (Exception e) { error = e; }
406 if (assembly == null)
407 ThrowParseException ("Assembly " + filename + " not found", error);
409 AddAssembly (assembly, true);
413 internal virtual Assembly AddAssemblyByName (string name)
416 anames = new Hashtable ();
418 if (anames.Contains (name)) {
419 object o = anames [name];
426 Assembly assembly = null;
427 Exception error = null;
428 if (name.IndexOf (',') != -1) {
430 assembly = Assembly.Load (name);
431 } catch (Exception e) { error = e; }
434 if (assembly == null) {
436 assembly = Assembly.LoadWithPartialName (name);
437 } catch (Exception e) { error = e; }
440 if (assembly == null)
441 ThrowParseException ("Assembly " + name + " not found", error);
443 AddAssembly (assembly, true);
447 internal virtual void ProcessMainAttributes (Hashtable atts)
449 atts.Remove ("Description"); // ignored
451 atts.Remove ("CodeBehind"); // ignored
453 atts.Remove ("AspCompat"); // ignored
455 debug = GetBool (atts, "Debug", true);
456 compilerOptions = GetString (atts, "CompilerOptions", "");
457 language = GetString (atts, "Language", CompilationConfig.DefaultLanguage);
458 strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
459 explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
461 string inherits = GetString (atts, "Inherits", null);
463 // In ASP 2, the source file is actually integrated with
464 // the generated file via the use of partial classes. This
465 // means that the code file has to be confirmed, but not
466 // used at this point.
467 src = GetString (atts, "CodeFile", null);
469 if (src != null && inherits != null) {
470 // Make sure the source exists
471 src = UrlUtils.Combine (BaseVirtualDir, src);
472 string realPath = MapPath (src, false);
473 if (!File.Exists (realPath))
474 ThrowParseException ("File " + src + " not found");
476 // Verify that the inherits is a valid identify not a
477 // fully-qualified name.
478 if (!CodeGenerator.IsValidLanguageIndependentIdentifier (inherits))
479 ThrowParseException (String.Format ("'{0}' is not valid for 'inherits'", inherits));
481 // We are going to create a partial class that shares
482 // the same name as the inherits tag, so reset the
483 // name. The base type is changed because it is the
484 // code file's responsibilty to extend the classes
486 partialClassName = inherits;
488 // Add the code file as an option to the
489 // compiler. This lets both files be compiled at once.
490 compilerOptions += " \"" + realPath + "\"";
491 } else if (inherits != null) {
492 // We just set the inherits directly because this is a
493 // Single-Page model.
494 SetBaseType (inherits);
497 string src = GetString (atts, "Src", null);
500 srcAssembly = GetAssemblyFromSource (src);
502 if (inherits != null)
503 SetBaseType (inherits);
505 className = GetString (atts, "ClassName", null);
506 if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className))
507 ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className));
511 ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
514 internal void SetBaseType (string type)
516 if (type == DefaultBaseTypeName)
520 if (srcAssembly != null)
521 parent = srcAssembly.GetType (type);
524 parent = LoadType (type);
527 ThrowParseException ("Cannot find type " + type);
529 if (!DefaultBaseType.IsAssignableFrom (parent))
530 ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
535 Assembly GetAssemblyFromSource (string vpath)
537 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
538 string realPath = MapPath (vpath, false);
539 if (!File.Exists (realPath))
540 ThrowParseException ("File " + vpath + " not found");
542 AddSourceDependency (realPath);
544 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
545 if (result.NativeCompilerReturnValue != 0) {
546 StreamReader reader = new StreamReader (realPath);
547 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
550 AddAssembly (result.CompiledAssembly, true);
551 return result.CompiledAssembly;
554 internal abstract Type DefaultBaseType { get; }
555 internal abstract string DefaultBaseTypeName { get; }
556 internal abstract string DefaultDirectiveName { get; }
558 internal string InputFile
560 get { return inputFile; }
561 set { inputFile = value; }
565 internal bool IsPartial
567 get { return src != null; }
570 internal string PartialClassName
572 get { return partialClassName; }
579 set { text = value; }
582 internal Type BaseType
585 if (baseType == null)
586 baseType = DefaultBaseType;
592 internal string ClassName {
594 if (className != null)
597 className = Path.GetFileName (inputFile).Replace ('.', '_');
598 className = className.Replace ('-', '_');
599 className = className.Replace (' ', '_');
601 if (Char.IsDigit(className[0])) {
602 className = "_" + className;
609 internal string PrivateBinPath {
611 if (privateBinPath != null)
612 return privateBinPath;
614 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
615 privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
617 return privateBinPath;
621 internal ArrayList Scripts {
624 scripts = new ArrayList ();
630 internal ArrayList Imports {
631 get { return imports; }
634 internal ArrayList Assemblies {
636 if (appAssemblyIndex != -1) {
637 object o = assemblies [appAssemblyIndex];
638 assemblies.RemoveAt (appAssemblyIndex);
640 appAssemblyIndex = -1;
647 internal ArrayList Interfaces {
648 get { return interfaces; }
651 internal RootBuilder RootBuilder {
652 get { return rootBuilder; }
653 set { rootBuilder = value; }
656 internal ArrayList Dependencies {
657 get { return dependencies; }
658 set { dependencies = value; }
661 internal string CompilerOptions {
662 get { return compilerOptions; }
665 internal string Language {
666 get { return language; }
669 internal bool StrictOn {
670 get { return strictOn; }
673 internal bool ExplicitOn {
674 get { return explicitOn; }
677 internal bool Debug {
678 get { return debug; }
681 internal bool OutputCache {
682 get { return output_cache; }
685 internal int OutputCacheDuration {
686 get { return oc_duration; }
689 internal string OutputCacheVaryByHeader {
690 get { return oc_header; }
693 internal string OutputCacheVaryByCustom {
694 get { return oc_custom; }
697 internal string OutputCacheVaryByControls {
698 get { return oc_controls; }
701 internal bool OutputCacheShared {
702 get { return oc_shared; }
705 internal OutputCacheLocation OutputCacheLocation {
706 get { return oc_location; }
709 internal string OutputCacheVaryByParam {
710 get { return oc_param; }
714 internal PagesSection PagesConfig {
716 return WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
720 internal PagesConfiguration PagesConfig {
721 get { return PagesConfiguration.GetInstance (Context); }