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 AddAssemblyByName (string name)
396 anames = new Hashtable ();
398 if (anames.Contains (name)) {
399 object o = anames [name];
406 Assembly assembly = null;
407 Exception error = null;
408 if (name.IndexOf (',') != -1) {
410 assembly = Assembly.Load (name);
411 } catch (Exception e) { error = e; }
414 if (assembly == null) {
416 assembly = Assembly.LoadWithPartialName (name);
417 } catch (Exception e) { error = e; }
420 if (assembly == null)
421 ThrowParseException ("Assembly " + name + " not found", error);
423 AddAssembly (assembly, true);
427 internal virtual void ProcessMainAttributes (Hashtable atts)
429 atts.Remove ("Description"); // ignored
431 atts.Remove ("CodeBehind"); // ignored
433 atts.Remove ("AspCompat"); // ignored
435 debug = GetBool (atts, "Debug", true);
436 compilerOptions = GetString (atts, "CompilerOptions", "");
437 language = GetString (atts, "Language", CompilationConfig.DefaultLanguage);
438 strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
439 explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
441 string inherits = GetString (atts, "Inherits", null);
443 // In ASP 2, the source file is actually integrated with
444 // the generated file via the use of partial classes. This
445 // means that the code file has to be confirmed, but not
446 // used at this point.
447 src = GetString (atts, "CodeFile", null);
449 if (src != null && inherits != null) {
450 // Make sure the source exists
451 src = UrlUtils.Combine (BaseVirtualDir, src);
452 string realPath = MapPath (src, false);
453 if (!File.Exists (realPath))
454 ThrowParseException ("File " + src + " not found");
456 // Verify that the inherits is a valid identify not a
457 // fully-qualified name.
458 if (!CodeGenerator.IsValidLanguageIndependentIdentifier (inherits))
459 ThrowParseException (String.Format ("'{0}' is not valid for 'inherits'", inherits));
461 // We are going to create a partial class that shares
462 // the same name as the inherits tag, so reset the
463 // name. The base type is changed because it is the
464 // code file's responsibilty to extend the classes
466 partialClassName = inherits;
468 // Add the code file as an option to the
469 // compiler. This lets both files be compiled at once.
470 compilerOptions += " " + realPath;
471 } else if (inherits != null) {
472 // We just set the inherits directly because this is a
473 // Single-Page model.
474 SetBaseType (inherits);
477 string src = GetString (atts, "Src", null);
480 srcAssembly = GetAssemblyFromSource (src);
482 if (inherits != null)
483 SetBaseType (inherits);
485 className = GetString (atts, "ClassName", null);
486 if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className))
487 ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className));
491 ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
494 internal void SetBaseType (string type)
496 if (type == DefaultBaseTypeName)
500 if (srcAssembly != null)
501 parent = srcAssembly.GetType (type);
504 parent = LoadType (type);
507 ThrowParseException ("Cannot find type " + type);
509 if (!DefaultBaseType.IsAssignableFrom (parent))
510 ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
515 Assembly GetAssemblyFromSource (string vpath)
517 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
518 string realPath = MapPath (vpath, false);
519 if (!File.Exists (realPath))
520 ThrowParseException ("File " + vpath + " not found");
522 AddSourceDependency (realPath);
524 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
525 if (result.NativeCompilerReturnValue != 0) {
526 StreamReader reader = new StreamReader (realPath);
527 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
530 AddAssembly (result.CompiledAssembly, true);
531 return result.CompiledAssembly;
534 internal abstract Type DefaultBaseType { get; }
535 internal abstract string DefaultBaseTypeName { get; }
536 internal abstract string DefaultDirectiveName { get; }
538 internal string InputFile
540 get { return inputFile; }
541 set { inputFile = value; }
545 internal bool IsPartial
547 get { return src != null; }
550 internal string PartialClassName
552 get { return partialClassName; }
559 set { text = value; }
562 internal Type BaseType
565 if (baseType == null)
566 baseType = DefaultBaseType;
572 internal string ClassName {
574 if (className != null)
577 className = Path.GetFileName (inputFile).Replace ('.', '_');
578 className = className.Replace ('-', '_');
579 className = className.Replace (' ', '_');
581 if (Char.IsDigit(className[0])) {
582 className = "_" + className;
589 internal string PrivateBinPath {
591 if (privateBinPath != null)
592 return privateBinPath;
594 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
595 privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
597 return privateBinPath;
601 internal ArrayList Scripts {
604 scripts = new ArrayList ();
610 internal ArrayList Imports {
611 get { return imports; }
614 internal ArrayList Assemblies {
616 if (appAssemblyIndex != -1) {
617 object o = assemblies [appAssemblyIndex];
618 assemblies.RemoveAt (appAssemblyIndex);
620 appAssemblyIndex = -1;
627 internal ArrayList Interfaces {
628 get { return interfaces; }
631 internal RootBuilder RootBuilder {
632 get { return rootBuilder; }
633 set { rootBuilder = value; }
636 internal ArrayList Dependencies {
637 get { return dependencies; }
638 set { dependencies = value; }
641 internal string CompilerOptions {
642 get { return compilerOptions; }
645 internal string Language {
646 get { return language; }
649 internal bool StrictOn {
650 get { return strictOn; }
653 internal bool ExplicitOn {
654 get { return explicitOn; }
657 internal bool Debug {
658 get { return debug; }
661 internal bool OutputCache {
662 get { return output_cache; }
665 internal int OutputCacheDuration {
666 get { return oc_duration; }
669 internal string OutputCacheVaryByHeader {
670 get { return oc_header; }
673 internal string OutputCacheVaryByCustom {
674 get { return oc_custom; }
677 internal string OutputCacheVaryByControls {
678 get { return oc_controls; }
681 internal bool OutputCacheShared {
682 get { return oc_shared; }
685 internal OutputCacheLocation OutputCacheLocation {
686 get { return oc_location; }
689 internal string OutputCacheVaryByParam {
690 get { return oc_param; }
693 #if CONFIGURATION_2_0
694 internal PagesSection PagesConfig {
696 return WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
700 internal PagesConfiguration PagesConfig {
701 get { return PagesConfiguration.GetInstance (Context); }