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.ComponentModel;
34 using System.Globalization;
36 using System.Reflection;
37 using System.Security.Permissions;
38 using System.Web.Compilation;
39 using System.Web.Configuration;
40 using System.Web.Util;
43 using System.Collections.Generic;
46 namespace System.Web.UI {
49 [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
50 [AspNetHostingPermission (SecurityAction.InheritanceDemand, Level = AspNetHostingPermissionLevel.Minimal)]
51 public abstract class TemplateParser : BaseParser
55 string privateBinPath;
56 Hashtable mainAttributes;
57 ArrayList dependencies;
64 bool baseTypeIsGlobal;
66 RootBuilder rootBuilder;
68 string compilerOptions;
70 bool implicitLanguage;
71 bool strictOn = false;
72 bool explicitOn = false;
73 bool linePragmasOn = false;
76 string oc_header, oc_custom, oc_param, oc_controls;
78 OutputCacheLocation oc_location;
79 CultureInfo invariantCulture = CultureInfo.InvariantCulture;
82 string partialClassName;
83 string codeFileBaseClass;
84 string metaResourceKey;
85 Type codeFileBaseClassType;
86 List <UnknownAttributeDescriptor> unknownMainAttributes;
89 int appAssemblyIndex = -1;
91 internal TemplateParser ()
93 imports = new ArrayList ();
95 AddNamespaces (imports);
97 imports.Add ("System");
98 imports.Add ("System.Collections");
99 imports.Add ("System.Collections.Specialized");
100 imports.Add ("System.Configuration");
101 imports.Add ("System.Text");
102 imports.Add ("System.Text.RegularExpressions");
103 imports.Add ("System.Web");
104 imports.Add ("System.Web.Caching");
105 imports.Add ("System.Web.Security");
106 imports.Add ("System.Web.SessionState");
107 imports.Add ("System.Web.UI");
108 imports.Add ("System.Web.UI.WebControls");
109 imports.Add ("System.Web.UI.HtmlControls");
112 assemblies = new ArrayList ();
114 bool addAssembliesInBin = false;
115 foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
116 if (info.Assembly == "*")
117 addAssembliesInBin = true;
119 AddAssemblyByName (info.Assembly);
121 if (addAssembliesInBin)
122 AddAssembliesInBin ();
124 foreach (NamespaceInfo info in PagesConfig.Namespaces) {
125 imports.Add (info.Namespace);
128 foreach (string a in CompilationConfig.Assemblies)
129 AddAssemblyByName (a);
130 if (CompilationConfig.AssembliesInBin)
131 AddAssembliesInBin ();
134 language = CompilationConfig.DefaultLanguage;
135 implicitLanguage = true;
138 internal void AddApplicationAssembly ()
140 if (Context.ApplicationInstance == null)
141 return; // this may happen if we have Global.asax and have
142 // controls registered from Web.Config
143 string location = Context.ApplicationInstance.AssemblyLocation;
144 if (location != typeof (TemplateParser).Assembly.Location) {
145 appAssemblyIndex = assemblies.Add (location);
149 protected abstract Type CompileIntoType ();
152 void AddNamespaces (ArrayList imports)
154 if (BuildManager.HaveResources)
155 imports.Add ("System.Resources");
157 PagesSection pages = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
161 NamespaceCollection namespaces = pages.Namespaces;
162 if (namespaces == null || namespaces.Count == 0)
165 foreach (NamespaceInfo nsi in namespaces)
166 imports.Add (nsi.Namespace);
170 internal void RegisterCustomControl (string tagPrefix, string tagName, string src)
172 string realpath = MapPath (src);
173 if (String.Compare (realpath, inputFile, false, invariantCulture) == 0)
176 if (!File.Exists (realpath))
177 throw new ParseException (Location, "Could not find file \"" + realpath + "\".");
178 string vpath = VirtualPathUtility.Combine (BaseVirtualDir, src);
180 AddDependency (realpath);
182 ArrayList other_deps = new ArrayList ();
183 type = UserControlParser.GetCompiledType (vpath, realpath, other_deps, Context);
184 foreach (string s in other_deps) {
187 } catch (ParseException pe) {
188 if (this is UserControlParser)
189 throw new ParseException (Location, pe.Message, pe);
193 AddAssembly (type.Assembly, true);
194 RootBuilder.Foundry.RegisterFoundry (tagPrefix, tagName, type);
197 internal void RegisterNamespace (string tagPrefix, string ns, string assembly)
202 if (assembly != null && assembly.Length > 0) {
203 ass = AddAssemblyByName (assembly);
204 AddDependency (ass.Location);
207 RootBuilder.Foundry.RegisterFoundry (tagPrefix, ass, ns);
210 internal virtual void HandleOptions (object obj)
214 internal static string GetOneKey (Hashtable tbl)
216 foreach (object key in tbl.Keys)
217 return key.ToString ();
222 internal virtual void AddDirective (string directive, Hashtable atts)
224 if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
225 if (mainAttributes != null)
226 ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
228 mainAttributes = atts;
229 ProcessMainAttributes (mainAttributes);
233 int cmp = String.Compare ("Assembly", directive, true);
235 string name = GetString (atts, "Name", null);
236 string src = GetString (atts, "Src", null);
239 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
241 if (name == null && src == null)
242 ThrowParseException ("You gotta specify Src or Name");
244 if (name != null && src != null)
245 ThrowParseException ("Src and Name cannot be used together");
248 AddAssemblyByName (name);
250 GetAssemblyFromSource (src);
256 cmp = String.Compare ("Import", directive, true);
258 string namesp = GetString (atts, "Namespace", null);
260 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
262 if (namesp != null && namesp != "")
267 cmp = String.Compare ("Implements", directive, true);
269 string ifacename = GetString (atts, "Interface", "");
272 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
274 Type iface = LoadType (ifacename);
276 ThrowParseException ("Cannot find type " + ifacename);
278 if (!iface.IsInterface)
279 ThrowParseException (iface + " is not an interface");
281 AddInterface (iface.FullName);
285 cmp = String.Compare ("OutputCache", directive, true);
287 HttpResponse response = HttpContext.Current.Response;
288 if (response != null)
289 response.Cache.SetValidUntilExpires (true);
293 if (atts ["Duration"] == null)
294 ThrowParseException ("The directive is missing a 'duration' attribute.");
295 if (atts ["VaryByParam"] == null && atts ["VaryByControl"] == null)
296 ThrowParseException ("This directive is missing 'VaryByParam' " +
297 "or 'VaryByControl' attribute, which should be set to \"none\", \"*\", " +
298 "or a list of name/value pairs.");
300 foreach (DictionaryEntry entry in atts) {
301 string key = (string) entry.Key;
302 switch (key.ToLower ()) {
304 oc_duration = Int32.Parse ((string) entry.Value);
306 ThrowParseException ("The 'duration' attribute must be set " +
307 "to a positive integer value");
310 oc_param = (string) entry.Value;
311 if (String.Compare (oc_param, "none") == 0)
315 oc_header = (string) entry.Value;
318 oc_custom = (string) entry.Value;
321 if (!(this is PageParser))
325 oc_location = (OutputCacheLocation) Enum.Parse (
326 typeof (OutputCacheLocation), (string) entry.Value, true);
328 ThrowParseException ("The 'location' attribute is case sensitive and " +
329 "must be one of the following values: Any, Client, " +
330 "Downstream, Server, None, ServerAndClient.");
333 case "varybycontrol":
335 if (this is PageParser)
338 oc_controls = (string) entry.Value;
341 if (this is PageParser)
345 oc_shared = Boolean.Parse ((string) entry.Value);
347 ThrowParseException ("The 'shared' attribute is case sensitive" +
348 " and must be set to 'true' or 'false'.");
352 ThrowParseException ("The '" + key + "' attribute is not " +
353 "supported by the 'Outputcache' directive.");
362 ThrowParseException ("Unknown directive: " + directive);
365 internal Type LoadType (string typeName)
367 Type type = HttpApplication.LoadType (typeName);
370 Assembly asm = type.Assembly;
371 string location = asm.Location;
373 AddDependency (location);
374 string dirname = Path.GetDirectoryName (location);
375 bool doAddAssembly = true;
376 foreach (string dir in HttpApplication.BinDirectories) {
377 if (dirname == dir) {
378 doAddAssembly = false;
384 AddAssembly (asm, true);
389 void AddAssembliesInBin ()
391 foreach (string s in HttpApplication.BinDirectoryAssemblies)
395 internal virtual void AddInterface (string iface)
397 if (interfaces == null)
398 interfaces = new ArrayList ();
400 if (!interfaces.Contains (iface))
401 interfaces.Add (iface);
404 internal virtual void AddImport (string namesp)
407 imports = new ArrayList ();
409 if (!imports.Contains (namesp))
410 imports.Add (namesp);
413 internal virtual void AddSourceDependency (string filename)
415 if (dependencies != null && dependencies.Contains (filename)) {
416 ThrowParseException ("Circular file references are not allowed. File: " + filename);
419 AddDependency (filename);
422 internal virtual void AddDependency (string filename)
427 if (dependencies == null)
428 dependencies = new ArrayList ();
430 if (!dependencies.Contains (filename))
431 dependencies.Add (filename);
434 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
436 if (assembly.Location == "")
440 anames = new Hashtable ();
442 string name = assembly.GetName ().Name;
443 string loc = assembly.Location;
445 if (!assemblies.Contains (loc)) {
446 assemblies.Add (loc);
450 anames [loc] = assembly;
452 if (!assemblies.Contains (name)) {
453 assemblies.Add (name);
456 anames [name] = assembly;
460 internal virtual Assembly AddAssemblyByFileName (string filename)
462 Assembly assembly = null;
463 Exception error = null;
466 assembly = Assembly.LoadFrom (filename);
467 } catch (Exception e) { error = e; }
469 if (assembly == null)
470 ThrowParseException ("Assembly " + filename + " not found", error);
472 AddAssembly (assembly, true);
476 internal virtual Assembly AddAssemblyByName (string name)
479 anames = new Hashtable ();
481 if (anames.Contains (name)) {
482 object o = anames [name];
489 Assembly assembly = null;
490 Exception error = null;
492 assembly = Assembly.Load (name);
493 } catch (Exception e) { error = e; }
495 if (assembly == null) {
497 assembly = Assembly.LoadWithPartialName (name);
498 } catch (Exception e) { error = e; }
501 if (assembly == null)
502 ThrowParseException ("Assembly " + name + " not found", error);
504 AddAssembly (assembly, true);
508 internal virtual void ProcessMainAttributes (Hashtable atts)
510 atts.Remove ("Description"); // ignored
512 atts.Remove ("CodeBehind"); // ignored
514 atts.Remove ("AspCompat"); // ignored
516 debug = GetBool (atts, "Debug", true);
517 compilerOptions = GetString (atts, "CompilerOptions", "");
518 language = GetString (atts, "Language", "");
519 if (language.Length != 0)
520 implicitLanguage = false;
522 language = CompilationConfig.DefaultLanguage;
524 strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
525 explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
526 linePragmasOn = GetBool (atts, "LinePragmas", false);
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);
535 codeFileBaseClass = GetString (atts, "CodeFileBaseClass", null);
537 if (src == null && codeFileBaseClass != null)
538 ThrowParseException ("The 'CodeFileBaseClass' attribute cannot be used without a 'CodeFile' attribute");
540 if (src != null && inherits != null) {
541 // Make sure the source exists
542 src = UrlUtils.Combine (BaseVirtualDir, src);
543 string realPath = MapPath (src, false);
544 if (!File.Exists (realPath))
545 ThrowParseException ("File " + src + " not found");
547 // We are going to create a partial class that shares
548 // the same name as the inherits tag, so reset the
549 // name. The base type is changed because it is the
550 // code file's responsibilty to extend the classes
552 partialClassName = inherits;
554 // Add the code file as an option to the
555 // compiler. This lets both files be compiled at once.
556 compilerOptions += " \"" + realPath + "\"";
558 if (codeFileBaseClass != null) {
560 codeFileBaseClassType = LoadType (codeFileBaseClass);
561 } catch (Exception) {
564 if (codeFileBaseClassType == null)
565 ThrowParseException ("Could not load type '{0}'", codeFileBaseClass);
567 } else if (inherits != null) {
568 // We just set the inherits directly because this is a
569 // Single-Page model.
570 SetBaseType (inherits);
573 string src = GetString (atts, "Src", null);
576 srcAssembly = GetAssemblyFromSource (src);
578 if (inherits != null)
579 SetBaseType (inherits);
582 AddDependency (MapPath (src, false));
584 className = GetString (atts, "ClassName", null);
585 if (className != null) {
587 string [] identifiers = className.Split ('.');
588 for (int i = 0; i < identifiers.Length; i++)
589 if (!CodeGenerator.IsValidLanguageIndependentIdentifier (identifiers [i]))
590 ThrowParseException (String.Format ("'{0}' is not a valid "
591 + "value for attribute 'classname'.", className));
593 if (!CodeGenerator.IsValidLanguageIndependentIdentifier (className))
594 ThrowParseException (String.Format ("'{0}' is not a valid "
595 + "value for attribute 'classname'.", className));
600 if (this is TemplateControlParser)
601 metaResourceKey = GetString (atts, "meta:resourcekey", null);
603 if (inherits != null && (this is PageParser || this is UserControlParser) && atts.Count > 0) {
604 if (unknownMainAttributes == null)
605 unknownMainAttributes = new List <UnknownAttributeDescriptor> ();
608 foreach (DictionaryEntry de in atts) {
609 key = de.Key as string;
610 val = de.Value as string;
612 if (String.IsNullOrEmpty (key) || String.IsNullOrEmpty (val))
614 CheckUnknownAttribute (key, val, inherits);
620 ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
624 void CheckUnknownAttribute (string name, string val, string inherits)
626 MemberInfo mi = null;
627 bool missing = false;
628 string memberName = name.Trim ().ToLower (CultureInfo.InvariantCulture);
629 Type parent = codeFileBaseClassType;
635 MemberInfo[] infos = parent.GetMember (memberName,
636 MemberTypes.Field | MemberTypes.Property,
637 BindingFlags.Public | BindingFlags.Instance |
638 BindingFlags.IgnoreCase | BindingFlags.Static);
639 if (infos.Length != 0) {
640 // prefer public properties to public methods (it's what MS.NET does)
641 foreach (MemberInfo tmp in infos) {
642 if (tmp is PropertyInfo) {
651 } catch (Exception) {
655 ThrowParseException (
656 "Error parsing attribute '{0}': Type '{1}' does not have a public property named '{0}'",
657 memberName, inherits);
659 Type memberType = null;
660 if (mi is PropertyInfo) {
661 PropertyInfo pi = mi as PropertyInfo;
664 ThrowParseException (
665 "Error parsing attribute '{0}': The '{0}' property is read-only and cannot be set.",
667 memberType = pi.PropertyType;
668 } else if (mi is FieldInfo) {
669 memberType = ((FieldInfo)mi).FieldType;
671 ThrowParseException ("Could not determine member the kind of '{0}' in base type '{1}",
672 memberName, inherits);
673 TypeConverter converter = TypeDescriptor.GetConverter (memberType);
674 bool convertible = true;
677 if (converter == null || !converter.CanConvertFrom (typeof (string)))
682 value = converter.ConvertFromInvariantString (val);
683 } catch (Exception) {
689 ThrowParseException ("Error parsing attribute '{0}': Cannot create an object of type '{1}' from its string representation '{2}' for the '{3}' property.",
690 memberName, memberType, val, mi.Name);
692 UnknownAttributeDescriptor desc = new UnknownAttributeDescriptor (mi, value);
693 unknownMainAttributes.Add (desc);
697 internal void SetBaseType (string type)
699 if (type == DefaultBaseTypeName)
703 if (srcAssembly != null)
704 parent = srcAssembly.GetType (type);
707 parent = LoadType (type);
710 ThrowParseException ("Cannot find type " + type);
712 if (!DefaultBaseType.IsAssignableFrom (parent))
713 ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
716 if (parent.FullName.IndexOf ('.') == -1)
717 baseTypeIsGlobal = true;
720 internal void SetLanguage (string language)
722 this.language = language;
723 implicitLanguage = false;
726 Assembly GetAssemblyFromSource (string vpath)
728 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
729 string realPath = MapPath (vpath, false);
730 if (!File.Exists (realPath))
731 ThrowParseException ("File " + vpath + " not found");
733 AddSourceDependency (realPath);
735 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
736 if (result.NativeCompilerReturnValue != 0) {
737 StreamReader reader = new StreamReader (realPath);
738 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
741 AddAssembly (result.CompiledAssembly, true);
742 return result.CompiledAssembly;
745 internal abstract Type DefaultBaseType { get; }
746 internal abstract string DefaultBaseTypeName { get; }
747 internal abstract string DefaultDirectiveName { get; }
749 internal string InputFile
751 get { return inputFile; }
752 set { inputFile = value; }
756 internal bool IsPartial {
757 get { return src != null; }
760 internal string PartialClassName {
761 get { return partialClassName; }
764 internal string CodeFileBaseClass {
765 get { return codeFileBaseClass; }
768 internal string MetaResourceKey {
769 get { return metaResourceKey; }
772 internal Type CodeFileBaseClassType
774 get { return codeFileBaseClassType; }
777 internal List <UnknownAttributeDescriptor> UnknownMainAttributes
779 get { return unknownMainAttributes; }
786 set { text = value; }
789 internal Type BaseType
792 if (baseType == null)
793 baseType = DefaultBaseType;
799 internal bool BaseTypeIsGlobal {
800 get { return baseTypeIsGlobal; }
803 internal string ClassName {
805 if (className != null)
809 string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
811 if (StrUtils.StartsWith (inputFile, physPath)) {
812 className = inputFile.Substring (physPath.Length).ToLower (CultureInfo.InvariantCulture);
813 className = className.Replace ('.', '_');
814 className = className.Replace ('/', '_').Replace ('\\', '_');
817 className = Path.GetFileName (inputFile).Replace ('.', '_');
818 className = className.Replace ('-', '_');
819 className = className.Replace (' ', '_');
821 if (Char.IsDigit(className[0])) {
822 className = "_" + className;
829 internal ArrayList Scripts {
832 scripts = new ArrayList ();
838 internal ArrayList Imports {
839 get { return imports; }
842 internal ArrayList Assemblies {
844 if (appAssemblyIndex != -1) {
845 object o = assemblies [appAssemblyIndex];
846 assemblies.RemoveAt (appAssemblyIndex);
848 appAssemblyIndex = -1;
855 internal ArrayList Interfaces {
856 get { return interfaces; }
859 internal RootBuilder RootBuilder {
860 get { return rootBuilder; }
861 set { rootBuilder = value; }
864 internal ArrayList Dependencies {
865 get { return dependencies; }
866 set { dependencies = value; }
869 internal string CompilerOptions {
870 get { return compilerOptions; }
873 internal string Language {
874 get { return language; }
877 internal bool ImplicitLanguage {
878 get { return implicitLanguage; }
881 internal bool StrictOn {
882 get { return strictOn; }
885 internal bool ExplicitOn {
886 get { return explicitOn; }
889 internal bool Debug {
890 get { return debug; }
893 internal bool OutputCache {
894 get { return output_cache; }
897 internal int OutputCacheDuration {
898 get { return oc_duration; }
901 internal string OutputCacheVaryByHeader {
902 get { return oc_header; }
905 internal string OutputCacheVaryByCustom {
906 get { return oc_custom; }
909 internal string OutputCacheVaryByControls {
910 get { return oc_controls; }
913 internal bool OutputCacheShared {
914 get { return oc_shared; }
917 internal OutputCacheLocation OutputCacheLocation {
918 get { return oc_location; }
921 internal string OutputCacheVaryByParam {
922 get { return oc_param; }
926 internal PagesSection PagesConfig {
928 return WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
932 internal PagesConfiguration PagesConfig {
933 get { return PagesConfiguration.GetInstance (Context); }