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;
33 using System.Globalization;
35 using System.Reflection;
36 using System.Security.Permissions;
37 using System.Web.Compilation;
38 using System.Web.Configuration;
39 using System.Web.Util;
41 namespace System.Web.UI {
44 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
45 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
46 public abstract class TemplateParser : BaseParser
50 string privateBinPath;
51 Hashtable mainAttributes;
52 ArrayList dependencies;
59 bool baseTypeIsGlobal;
61 RootBuilder rootBuilder;
63 string compilerOptions;
65 bool strictOn = false;
66 bool explicitOn = false;
69 string oc_header, oc_custom, oc_param, oc_controls;
71 OutputCacheLocation oc_location;
72 CultureInfo invariantCulture = CultureInfo.InvariantCulture;
75 string partialClassName;
78 int appAssemblyIndex = -1;
80 internal TemplateParser ()
82 imports = new ArrayList ();
84 AddNamespaces (imports);
86 imports.Add ("System");
87 imports.Add ("System.Collections");
88 imports.Add ("System.Collections.Specialized");
89 imports.Add ("System.Configuration");
90 imports.Add ("System.Text");
91 imports.Add ("System.Text.RegularExpressions");
92 imports.Add ("System.Web");
93 imports.Add ("System.Web.Caching");
94 imports.Add ("System.Web.Security");
95 imports.Add ("System.Web.SessionState");
96 imports.Add ("System.Web.UI");
97 imports.Add ("System.Web.UI.WebControls");
98 imports.Add ("System.Web.UI.HtmlControls");
101 assemblies = new ArrayList ();
103 bool addAssembliesInBin = false;
104 foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
105 if (info.Assembly == "*")
106 addAssembliesInBin = true;
108 AddAssemblyByName (info.Assembly);
110 if (addAssembliesInBin)
111 AddAssembliesInBin ();
113 foreach (NamespaceInfo info in PagesConfig.Namespaces) {
114 imports.Add (info.Namespace);
117 foreach (string a in CompilationConfig.Assemblies)
118 AddAssemblyByName (a);
119 if (CompilationConfig.AssembliesInBin)
120 AddAssembliesInBin ();
123 language = CompilationConfig.DefaultLanguage;
126 internal void AddApplicationAssembly ()
128 if (Context.ApplicationInstance == null)
129 return; // this may happen if we have Global.asax and have
130 // controls registered from Web.Config
131 string location = Context.ApplicationInstance.AssemblyLocation;
132 if (location != typeof (TemplateParser).Assembly.Location) {
133 appAssemblyIndex = assemblies.Add (location);
137 protected abstract Type CompileIntoType ();
140 void AddNamespaces (ArrayList imports)
142 if (BuildManager.HaveResources)
143 imports.Add ("System.Resources");
145 PagesSection pages = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
149 NamespaceCollection namespaces = pages.Namespaces;
150 if (namespaces == null || namespaces.Count == 0)
153 foreach (NamespaceInfo nsi in namespaces)
154 imports.Add (nsi.Namespace);
158 internal void RegisterCustomControl (string tagPrefix, string tagName, string src)
160 string realpath = MapPath (src);
161 if (String.Compare (realpath, inputFile, false, invariantCulture) == 0)
164 if (!File.Exists (realpath))
165 throw new ParseException (Location, "Could not find file \"" + realpath + "\".");
166 string vpath = UrlUtils.Combine (BaseVirtualDir, src);
168 AddDependency (realpath);
170 ArrayList other_deps = new ArrayList ();
171 type = UserControlParser.GetCompiledType (vpath, realpath, other_deps, Context);
172 foreach (string s in other_deps) {
175 } catch (ParseException pe) {
176 if (this is UserControlParser)
177 throw new ParseException (Location, pe.Message, pe);
181 AddAssembly (type.Assembly, true);
182 RootBuilder.Foundry.RegisterFoundry (tagPrefix, tagName, type);
185 internal void RegisterNamespace (string tagPrefix, string ns, string assembly)
188 Assembly ass = AddAssemblyByName (assembly);
189 AddDependency (ass.Location);
190 RootBuilder.Foundry.RegisterFoundry (tagPrefix, ass, ns);
193 internal virtual void HandleOptions (object obj)
197 internal static string GetOneKey (Hashtable tbl)
199 foreach (object key in tbl.Keys)
200 return key.ToString ();
205 internal virtual void AddDirective (string directive, Hashtable atts)
207 if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
208 if (mainAttributes != null)
209 ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
211 mainAttributes = atts;
212 ProcessMainAttributes (mainAttributes);
216 int cmp = String.Compare ("Assembly", directive, true);
218 string name = GetString (atts, "Name", null);
219 string src = GetString (atts, "Src", null);
222 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
224 if (name == null && src == null)
225 ThrowParseException ("You gotta specify Src or Name");
227 if (name != null && src != null)
228 ThrowParseException ("Src and Name cannot be used together");
231 AddAssemblyByName (name);
233 GetAssemblyFromSource (src);
239 cmp = String.Compare ("Import", directive, true);
241 string namesp = GetString (atts, "Namespace", null);
243 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
245 if (namesp != null && namesp != "")
250 cmp = String.Compare ("Implements", directive, true);
252 string ifacename = GetString (atts, "Interface", "");
255 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
257 Type iface = LoadType (ifacename);
259 ThrowParseException ("Cannot find type " + ifacename);
261 if (!iface.IsInterface)
262 ThrowParseException (iface + " is not an interface");
264 AddInterface (iface.FullName);
268 cmp = String.Compare ("OutputCache", directive, true);
270 HttpResponse response = HttpContext.Current.Response;
271 if (response != null)
272 response.Cache.SetValidUntilExpires (true);
276 if (atts ["Duration"] == null)
277 ThrowParseException ("The directive is missing a 'duration' attribute.");
278 if (atts ["VaryByParam"] == null)
279 ThrowParseException ("This directive is missing a 'VaryByParam' " +
280 "attribute, which should be set to \"none\", \"*\", " +
281 "or a list of name/value pairs.");
283 foreach (DictionaryEntry entry in atts) {
284 string key = (string) entry.Key;
285 switch (key.ToLower ()) {
287 oc_duration = Int32.Parse ((string) entry.Value);
289 ThrowParseException ("The 'duration' attribute must be set " +
290 "to a positive integer value");
293 oc_param = (string) entry.Value;
294 if (String.Compare (oc_param, "none") == 0)
298 oc_header = (string) entry.Value;
301 oc_custom = (string) entry.Value;
304 if (!(this is PageParser))
308 oc_location = (OutputCacheLocation) Enum.Parse (
309 typeof (OutputCacheLocation), (string) entry.Value, true);
311 ThrowParseException ("The 'location' attribute is case sensitive and " +
312 "must be one of the following values: Any, Client, " +
313 "Downstream, Server, None, ServerAndClient.");
316 case "varybycontrol":
317 if (this is PageParser)
320 oc_controls = (string) entry.Value;
323 if (this is PageParser)
327 oc_shared = Boolean.Parse ((string) entry.Value);
329 ThrowParseException ("The 'shared' attribute is case sensitive" +
330 " and must be set to 'true' or 'false'.");
334 ThrowParseException ("The '" + key + "' attribute is not " +
335 "supported by the 'Outputcache' directive.");
344 ThrowParseException ("Unknown directive: " + directive);
347 internal Type LoadType (string typeName)
349 // First try loaded assemblies, then try assemblies in Bin directory.
351 bool seenBin = false;
352 Assembly [] assemblies = AppDomain.CurrentDomain.GetAssemblies ();
353 foreach (Assembly ass in assemblies) {
354 type = ass.GetType (typeName);
358 if (Path.GetDirectoryName (ass.Location) != PrivateBinPath) {
359 AddAssembly (ass, true);
364 AddDependency (ass.Location);
372 if (!Directory.Exists (PrivateBinPath))
375 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
376 foreach (string s in binDlls) {
377 Assembly binA = Assembly.LoadFrom (s);
378 type = binA.GetType (typeName);
382 AddDependency (binA.Location);
389 void AddAssembliesInBin ()
391 if (!Directory.Exists (PrivateBinPath))
394 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
395 foreach (string s in binDlls)
399 internal virtual void AddInterface (string iface)
401 if (interfaces == null)
402 interfaces = new ArrayList ();
404 if (!interfaces.Contains (iface))
405 interfaces.Add (iface);
408 internal virtual void AddImport (string namesp)
411 imports = new ArrayList ();
413 if (!imports.Contains (namesp))
414 imports.Add (namesp);
417 internal virtual void AddSourceDependency (string filename)
419 if (dependencies != null && dependencies.Contains (filename)) {
420 ThrowParseException ("Circular file references are not allowed. File: " + filename);
423 AddDependency (filename);
426 internal virtual void AddDependency (string filename)
431 if (dependencies == null)
432 dependencies = new ArrayList ();
434 if (!dependencies.Contains (filename))
435 dependencies.Add (filename);
438 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
440 if (assembly.Location == "")
444 anames = new Hashtable ();
446 string name = assembly.GetName ().Name;
447 string loc = assembly.Location;
449 if (!assemblies.Contains (loc)) {
450 assemblies.Add (loc);
454 anames [loc] = assembly;
456 if (!assemblies.Contains (name)) {
457 assemblies.Add (name);
460 anames [name] = assembly;
464 internal virtual Assembly AddAssemblyByFileName (string filename)
466 Assembly assembly = null;
467 Exception error = null;
470 assembly = Assembly.LoadFrom (filename);
471 } catch (Exception e) { error = e; }
473 if (assembly == null)
474 ThrowParseException ("Assembly " + filename + " not found", error);
476 AddAssembly (assembly, true);
480 internal virtual Assembly AddAssemblyByName (string name)
483 anames = new Hashtable ();
485 if (anames.Contains (name)) {
486 object o = anames [name];
493 Assembly assembly = null;
494 Exception error = null;
495 if (name.IndexOf (',') != -1) {
497 assembly = Assembly.Load (name);
498 } catch (Exception e) { error = e; }
501 if (assembly == null) {
503 assembly = Assembly.LoadWithPartialName (name);
504 } catch (Exception e) { error = e; }
507 if (assembly == null)
508 ThrowParseException ("Assembly " + name + " not found", error);
510 AddAssembly (assembly, true);
514 internal virtual void ProcessMainAttributes (Hashtable atts)
516 atts.Remove ("Description"); // ignored
518 atts.Remove ("CodeBehind"); // ignored
520 atts.Remove ("AspCompat"); // ignored
522 debug = GetBool (atts, "Debug", true);
523 compilerOptions = GetString (atts, "CompilerOptions", "");
524 language = GetString (atts, "Language", CompilationConfig.DefaultLanguage);
525 strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
526 explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
528 string inherits = GetString (atts, "Inherits", null);
530 // In ASP 2, the source file is actually integrated with
531 // the generated file via the use of partial classes. This
532 // means that the code file has to be confirmed, but not
533 // used at this point.
534 src = GetString (atts, "CodeFile", null);
536 if (src != null && inherits != null) {
537 // Make sure the source exists
538 src = UrlUtils.Combine (BaseVirtualDir, src);
539 string realPath = MapPath (src, false);
540 if (!File.Exists (realPath))
541 ThrowParseException ("File " + src + " not found");
543 // We are going to create a partial class that shares
544 // the same name as the inherits tag, so reset the
545 // name. The base type is changed because it is the
546 // code file's responsibilty to extend the classes
548 partialClassName = inherits;
550 // Add the code file as an option to the
551 // compiler. This lets both files be compiled at once.
552 compilerOptions += " \"" + realPath + "\"";
553 } else if (inherits != null) {
554 // We just set the inherits directly because this is a
555 // Single-Page model.
556 SetBaseType (inherits);
559 string src = GetString (atts, "Src", null);
562 srcAssembly = GetAssemblyFromSource (src);
564 if (inherits != null)
565 SetBaseType (inherits);
567 className = GetString (atts, "ClassName", null);
568 if (className != null && !CodeGenerator.IsValidLanguageIndependentIdentifier (className))
569 ThrowParseException (String.Format ("'{0}' is not valid for 'className'", className));
573 ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
576 internal void SetBaseType (string type)
578 if (type == DefaultBaseTypeName)
582 if (srcAssembly != null)
583 parent = srcAssembly.GetType (type);
586 parent = LoadType (type);
589 ThrowParseException ("Cannot find type " + type);
591 if (!DefaultBaseType.IsAssignableFrom (parent))
592 ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
595 if (parent.FullName.IndexOf ('.') == -1)
596 baseTypeIsGlobal = true;
599 Assembly GetAssemblyFromSource (string vpath)
601 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
602 string realPath = MapPath (vpath, false);
603 if (!File.Exists (realPath))
604 ThrowParseException ("File " + vpath + " not found");
606 AddSourceDependency (realPath);
608 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
609 if (result.NativeCompilerReturnValue != 0) {
610 StreamReader reader = new StreamReader (realPath);
611 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
614 AddAssembly (result.CompiledAssembly, true);
615 return result.CompiledAssembly;
618 internal abstract Type DefaultBaseType { get; }
619 internal abstract string DefaultBaseTypeName { get; }
620 internal abstract string DefaultDirectiveName { get; }
622 internal string InputFile
624 get { return inputFile; }
625 set { inputFile = value; }
629 internal bool IsPartial
631 get { return src != null; }
634 internal string PartialClassName
636 get { return partialClassName; }
643 set { text = value; }
646 internal Type BaseType
649 if (baseType == null)
650 baseType = DefaultBaseType;
656 internal bool BaseTypeIsGlobal {
657 get { return baseTypeIsGlobal; }
660 internal string ClassName {
662 if (className != null)
665 className = Path.GetFileName (inputFile).Replace ('.', '_');
666 className = className.Replace ('-', '_');
667 className = className.Replace (' ', '_');
669 if (Char.IsDigit(className[0])) {
670 className = "_" + className;
677 internal string PrivateBinPath {
679 if (privateBinPath != null)
680 return privateBinPath;
682 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
683 privateBinPath = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
685 return privateBinPath;
689 internal ArrayList Scripts {
692 scripts = new ArrayList ();
698 internal ArrayList Imports {
699 get { return imports; }
702 internal ArrayList Assemblies {
704 if (appAssemblyIndex != -1) {
705 object o = assemblies [appAssemblyIndex];
706 assemblies.RemoveAt (appAssemblyIndex);
708 appAssemblyIndex = -1;
715 internal ArrayList Interfaces {
716 get { return interfaces; }
719 internal RootBuilder RootBuilder {
720 get { return rootBuilder; }
721 set { rootBuilder = value; }
724 internal ArrayList Dependencies {
725 get { return dependencies; }
726 set { dependencies = value; }
729 internal string CompilerOptions {
730 get { return compilerOptions; }
733 internal string Language {
734 get { return language; }
737 internal bool StrictOn {
738 get { return strictOn; }
741 internal bool ExplicitOn {
742 get { return explicitOn; }
745 internal bool Debug {
746 get { return debug; }
749 internal bool OutputCache {
750 get { return output_cache; }
753 internal int OutputCacheDuration {
754 get { return oc_duration; }
757 internal string OutputCacheVaryByHeader {
758 get { return oc_header; }
761 internal string OutputCacheVaryByCustom {
762 get { return oc_custom; }
765 internal string OutputCacheVaryByControls {
766 get { return oc_controls; }
769 internal bool OutputCacheShared {
770 get { return oc_shared; }
773 internal OutputCacheLocation OutputCacheLocation {
774 get { return oc_location; }
777 internal string OutputCacheVaryByParam {
778 get { return oc_param; }
782 internal PagesSection PagesConfig {
784 return WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
788 internal PagesConfiguration PagesConfig {
789 get { return PagesConfiguration.GetInstance (Context); }