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 (string a in CompilationConfig.Assemblies)
107 AddAssemblyByName (a);
108 if (CompilationConfig.AssembliesInBin)
109 AddAssembliesInBin ();
112 language = CompilationConfig.DefaultLanguage;
115 internal void AddApplicationAssembly ()
117 string location = Context.ApplicationInstance.AssemblyLocation;
118 if (location != typeof (TemplateParser).Assembly.Location) {
119 appAssemblyIndex = assemblies.Add (location);
123 protected abstract Type CompileIntoType ();
125 internal virtual void HandleOptions (object obj)
129 internal static string GetOneKey (Hashtable tbl)
131 foreach (object key in tbl.Keys)
132 return key.ToString ();
137 internal virtual void AddDirective (string directive, Hashtable atts)
139 if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
140 if (mainAttributes != null)
141 ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
143 mainAttributes = atts;
144 ProcessMainAttributes (mainAttributes);
148 int cmp = String.Compare ("Assembly", directive, true);
150 string name = GetString (atts, "Name", null);
151 string src = GetString (atts, "Src", null);
154 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
156 if (name == null && src == null)
157 ThrowParseException ("You gotta specify Src or Name");
159 if (name != null && src != null)
160 ThrowParseException ("Src and Name cannot be used together");
163 AddAssemblyByName (name);
165 GetAssemblyFromSource (src);
171 cmp = String.Compare ("Import", directive, true);
173 string namesp = GetString (atts, "Namespace", null);
175 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
177 if (namesp != null && namesp != "")
182 cmp = String.Compare ("Implements", directive, true);
184 string ifacename = GetString (atts, "Interface", "");
187 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
189 Type iface = LoadType (ifacename);
191 ThrowParseException ("Cannot find type " + ifacename);
193 if (!iface.IsInterface)
194 ThrowParseException (iface + " is not an interface");
196 AddInterface (iface.FullName);
200 cmp = String.Compare ("OutputCache", directive, true);
204 if (atts ["Duration"] == null)
205 ThrowParseException ("The directive is missing a 'duration' attribute.");
206 if (atts ["VaryByParam"] == null)
207 ThrowParseException ("This directive is missing a 'VaryByParam' " +
208 "attribute, which should be set to \"none\", \"*\", " +
209 "or a list of name/value pairs.");
211 foreach (DictionaryEntry entry in atts) {
212 string key = (string) entry.Key;
213 switch (key.ToLower ()) {
215 oc_duration = Int32.Parse ((string) entry.Value);
217 ThrowParseException ("The 'duration' attribute must be set " +
218 "to a positive integer value");
221 oc_param = (string) entry.Value;
222 if (String.Compare (oc_param, "none") == 0)
226 oc_header = (string) entry.Value;
229 oc_custom = (string) entry.Value;
232 if (!(this is PageParser))
236 oc_location = (OutputCacheLocation) Enum.Parse (
237 typeof (OutputCacheLocation), (string) entry.Value, true);
239 ThrowParseException ("The 'location' attribute is case sensitive and " +
240 "must be one of the following values: Any, Client, " +
241 "Downstream, Server, None, ServerAndClient.");
244 case "varybycontrol":
245 if (this is PageParser)
248 oc_controls = (string) entry.Value;
251 if (this is PageParser)
255 oc_shared = Boolean.Parse ((string) entry.Value);
257 ThrowParseException ("The 'shared' attribute is case sensitive" +
258 " and must be set to 'true' or 'false'.");
262 ThrowParseException ("The '" + key + "' attribute is not " +
263 "supported by the 'Outputcache' directive.");
272 ThrowParseException ("Unknown directive: " + directive);
275 internal Type LoadType (string typeName)
277 // First try loaded assemblies, then try assemblies in Bin directory.
279 bool seenBin = false;
280 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
281 foreach (Assembly ass in assemblies) {
282 type = ass.GetType (typeName);
286 if (Path.GetDirectoryName (ass.Location) != PrivateBinPath) {
287 AddAssembly (ass, true);
292 AddDependency (ass.Location);
300 if (!Directory.Exists (PrivateBinPath))
303 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
304 foreach (string s in binDlls) {
305 Assembly binA = Assembly.LoadFrom (s);
306 type = binA.GetType (typeName);
310 AddDependency (binA.Location);
317 void AddAssembliesInBin ()
319 if (!Directory.Exists (PrivateBinPath))
322 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
323 foreach (string s in binDlls) {
328 internal virtual void AddInterface (string iface)
330 if (interfaces == null)
331 interfaces = new ArrayList ();
333 if (!interfaces.Contains (iface))
334 interfaces.Add (iface);
337 internal virtual void AddImport (string namesp)
340 imports = new ArrayList ();
342 if (!imports.Contains (namesp))
343 imports.Add (namesp);
346 internal virtual void AddSourceDependency (string filename)
348 if (dependencies != null && dependencies.Contains (filename)) {
349 ThrowParseException ("Circular file references are not allowed. File: " + filename);
352 AddDependency (filename);
355 internal virtual void AddDependency (string filename)
360 if (dependencies == null)
361 dependencies = new ArrayList ();
363 if (!dependencies.Contains (filename))
364 dependencies.Add (filename);
367 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
369 if (assembly.Location == "")
373 anames = new Hashtable ();
375 string name = assembly.GetName ().Name;
376 string loc = assembly.Location;
378 if (!assemblies.Contains (loc)) {
379 assemblies.Add (loc);
383 anames [loc] = assembly;
385 if (!assemblies.Contains (name)) {
386 assemblies.Add (name);
389 anames [name] = assembly;
393 internal virtual Assembly AddAssemblyByFileName (string filename)
395 Assembly assembly = null;
396 Exception error = null;
399 assembly = Assembly.LoadFrom (filename);
400 } catch (Exception e) { error = e; }
402 if (assembly == null)
403 ThrowParseException ("Assembly " + filename + " not found", error);
405 AddAssembly (assembly, true);
409 internal virtual Assembly AddAssemblyByName (string name)
412 anames = new Hashtable ();
414 if (anames.Contains (name)) {
415 object o = anames [name];
422 Assembly assembly = null;
423 Exception error = null;
424 if (name.IndexOf (',') != -1) {
426 assembly = Assembly.Load (name);
427 } catch (Exception e) { error = e; }
430 if (assembly == null) {
432 assembly = Assembly.LoadWithPartialName (name);
433 } catch (Exception e) { error = e; }
436 if (assembly == null)
437 ThrowParseException ("Assembly " + name + " not found", error);
439 AddAssembly (assembly, true);
443 internal virtual void ProcessMainAttributes (Hashtable atts)
445 atts.Remove ("Description"); // ignored
447 atts.Remove ("CodeBehind"); // ignored
449 atts.Remove ("AspCompat"); // ignored
451 debug = GetBool (atts, "Debug", true);
452 compilerOptions = GetString (atts, "CompilerOptions", "");
453 language = GetString (atts, "Language", CompilationConfig.DefaultLanguage);
454 strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
455 explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
457 string inherits = GetString (atts, "Inherits", null);
459 // In ASP 2, the source file is actually integrated with
460 // the generated file via the use of partial classes. This
461 // means that the code file has to be confirmed, but not
462 // used at this point.
463 src = GetString (atts, "CodeFile", null);
465 if (src != null && inherits != null) {
466 // Make sure the source exists
467 src = UrlUtils.Combine (BaseVirtualDir, src);
468 string realPath = MapPath (src, false);
469 if (!File.Exists (realPath))
470 ThrowParseException ("File " + src + " not found");
472 // Verify that the inherits is a valid identify not a
473 // fully-qualified name.
474 if (!CodeGenerator.IsValidLanguageIndependentIdentifier (inherits))
475 ThrowParseException (String.Format ("'{0}' is not valid for 'inherits'", inherits));
477 // We are going to create a partial class that shares
478 // the same name as the inherits tag, so reset the
479 // name. The base type is changed because it is the
480 // code file's responsibilty to extend the classes
482 partialClassName = inherits;
484 // Add the code file as an option to the
485 // compiler. This lets both files be compiled at once.
486 compilerOptions += " \"" + realPath + "\"";
487 } else if (inherits != null) {
488 // We just set the inherits directly because this is a
489 // Single-Page model.
490 SetBaseType (inherits);
493 string src = GetString (atts, "Src", null);
496 srcAssembly = GetAssemblyFromSource (src);
498 if (inherits != null)
499 SetBaseType (inherits);
501 className = GetString (atts, "ClassName", null);
502 if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className))
503 ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className));
507 ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
510 internal void SetBaseType (string type)
512 if (type == DefaultBaseTypeName)
516 if (srcAssembly != null)
517 parent = srcAssembly.GetType (type);
520 parent = LoadType (type);
523 ThrowParseException ("Cannot find type " + type);
525 if (!DefaultBaseType.IsAssignableFrom (parent))
526 ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
531 Assembly GetAssemblyFromSource (string vpath)
533 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
534 string realPath = MapPath (vpath, false);
535 if (!File.Exists (realPath))
536 ThrowParseException ("File " + vpath + " not found");
538 AddSourceDependency (realPath);
540 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
541 if (result.NativeCompilerReturnValue != 0) {
542 StreamReader reader = new StreamReader (realPath);
543 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
546 AddAssembly (result.CompiledAssembly, true);
547 return result.CompiledAssembly;
550 internal abstract Type DefaultBaseType { get; }
551 internal abstract string DefaultBaseTypeName { get; }
552 internal abstract string DefaultDirectiveName { get; }
554 internal string InputFile
556 get { return inputFile; }
557 set { inputFile = value; }
561 internal bool IsPartial
563 get { return src != null; }
566 internal string PartialClassName
568 get { return partialClassName; }
575 set { text = value; }
578 internal Type BaseType
581 if (baseType == null)
582 baseType = DefaultBaseType;
588 internal string ClassName {
590 if (className != null)
593 className = Path.GetFileName (inputFile).Replace ('.', '_');
594 className = className.Replace ('-', '_');
595 className = className.Replace (' ', '_');
597 if (Char.IsDigit(className[0])) {
598 className = "_" + className;
605 internal string PrivateBinPath {
607 if (privateBinPath != null)
608 return privateBinPath;
610 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
611 privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
613 return privateBinPath;
617 internal ArrayList Scripts {
620 scripts = new ArrayList ();
626 internal ArrayList Imports {
627 get { return imports; }
630 internal ArrayList Assemblies {
632 if (appAssemblyIndex != -1) {
633 object o = assemblies [appAssemblyIndex];
634 assemblies.RemoveAt (appAssemblyIndex);
636 appAssemblyIndex = -1;
643 internal ArrayList Interfaces {
644 get { return interfaces; }
647 internal RootBuilder RootBuilder {
648 get { return rootBuilder; }
649 set { rootBuilder = value; }
652 internal ArrayList Dependencies {
653 get { return dependencies; }
654 set { dependencies = value; }
657 internal string CompilerOptions {
658 get { return compilerOptions; }
661 internal string Language {
662 get { return language; }
665 internal bool StrictOn {
666 get { return strictOn; }
669 internal bool ExplicitOn {
670 get { return explicitOn; }
673 internal bool Debug {
674 get { return debug; }
677 internal bool OutputCache {
678 get { return output_cache; }
681 internal int OutputCacheDuration {
682 get { return oc_duration; }
685 internal string OutputCacheVaryByHeader {
686 get { return oc_header; }
689 internal string OutputCacheVaryByCustom {
690 get { return oc_custom; }
693 internal string OutputCacheVaryByControls {
694 get { return oc_controls; }
697 internal bool OutputCacheShared {
698 get { return oc_shared; }
701 internal OutputCacheLocation OutputCacheLocation {
702 get { return oc_location; }
705 internal string OutputCacheVaryByParam {
706 get { return oc_param; }
710 internal PagesSection PagesConfig {
712 return WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
716 internal PagesConfiguration PagesConfig {
717 get { return PagesConfiguration.GetInstance (Context); }