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 string oc_content_encodings;
81 OutputCacheLocation oc_location;
82 CultureInfo invariantCulture = CultureInfo.InvariantCulture;
85 string partialClassName;
86 string codeFileBaseClass;
87 string metaResourceKey;
88 Type codeFileBaseClassType;
89 List <UnknownAttributeDescriptor> unknownMainAttributes;
92 int appAssemblyIndex = -1;
94 internal TemplateParser ()
96 imports = new ArrayList ();
98 AddNamespaces (imports);
100 imports.Add ("System");
101 imports.Add ("System.Collections");
102 imports.Add ("System.Collections.Specialized");
103 imports.Add ("System.Configuration");
104 imports.Add ("System.Text");
105 imports.Add ("System.Text.RegularExpressions");
106 imports.Add ("System.Web");
107 imports.Add ("System.Web.Caching");
108 imports.Add ("System.Web.Security");
109 imports.Add ("System.Web.SessionState");
110 imports.Add ("System.Web.UI");
111 imports.Add ("System.Web.UI.WebControls");
112 imports.Add ("System.Web.UI.HtmlControls");
115 assemblies = new ArrayList ();
117 bool addAssembliesInBin = false;
118 foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
119 if (info.Assembly == "*")
120 addAssembliesInBin = true;
122 AddAssemblyByName (info.Assembly);
124 if (addAssembliesInBin)
125 AddAssembliesInBin ();
127 foreach (NamespaceInfo info in PagesConfig.Namespaces) {
128 imports.Add (info.Namespace);
131 foreach (string a in CompilationConfig.Assemblies)
132 AddAssemblyByName (a);
133 if (CompilationConfig.AssembliesInBin)
134 AddAssembliesInBin ();
137 language = CompilationConfig.DefaultLanguage;
138 implicitLanguage = true;
141 internal void AddApplicationAssembly ()
143 if (Context.ApplicationInstance == null)
144 return; // this may happen if we have Global.asax and have
145 // controls registered from Web.Config
146 string location = Context.ApplicationInstance.AssemblyLocation;
147 if (location != typeof (TemplateParser).Assembly.Location) {
148 appAssemblyIndex = assemblies.Add (location);
152 protected abstract Type CompileIntoType ();
155 void AddNamespaces (ArrayList imports)
157 if (BuildManager.HaveResources)
158 imports.Add ("System.Resources");
160 PagesSection pages = WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
164 NamespaceCollection namespaces = pages.Namespaces;
165 if (namespaces == null || namespaces.Count == 0)
168 foreach (NamespaceInfo nsi in namespaces)
169 imports.Add (nsi.Namespace);
173 internal void RegisterCustomControl (string tagPrefix, string tagName, string src)
175 string realpath = MapPath (src);
176 if (String.Compare (realpath, inputFile, false, invariantCulture) == 0)
179 if (!File.Exists (realpath))
180 throw new ParseException (Location, "Could not find file \"" + realpath + "\".");
181 string vpath = VirtualPathUtility.Combine (BaseVirtualDir, src);
183 AddDependency (realpath);
185 ArrayList other_deps = new ArrayList ();
186 type = UserControlParser.GetCompiledType (vpath, realpath, other_deps, Context);
187 foreach (string s in other_deps) {
190 } catch (ParseException pe) {
191 if (this is UserControlParser)
192 throw new ParseException (Location, pe.Message, pe);
196 AddAssembly (type.Assembly, true);
197 RootBuilder.Foundry.RegisterFoundry (tagPrefix, tagName, type);
200 internal void RegisterNamespace (string tagPrefix, string ns, string assembly)
205 if (assembly != null && assembly.Length > 0) {
206 ass = AddAssemblyByName (assembly);
207 AddDependency (ass.Location);
210 RootBuilder.Foundry.RegisterFoundry (tagPrefix, ass, ns);
213 internal virtual void HandleOptions (object obj)
217 internal static string GetOneKey (Hashtable tbl)
219 foreach (object key in tbl.Keys)
220 return key.ToString ();
225 internal virtual void AddDirective (string directive, Hashtable atts)
227 if (String.Compare (directive, DefaultDirectiveName, true) == 0) {
228 if (mainAttributes != null)
229 ThrowParseException ("Only 1 " + DefaultDirectiveName + " is allowed");
231 mainAttributes = atts;
232 ProcessMainAttributes (mainAttributes);
236 int cmp = String.Compare ("Assembly", directive, true);
238 string name = GetString (atts, "Name", null);
239 string src = GetString (atts, "Src", null);
242 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
244 if (name == null && src == null)
245 ThrowParseException ("You gotta specify Src or Name");
247 if (name != null && src != null)
248 ThrowParseException ("Src and Name cannot be used together");
251 AddAssemblyByName (name);
253 GetAssemblyFromSource (src);
259 cmp = String.Compare ("Import", directive, true);
261 string namesp = GetString (atts, "Namespace", null);
263 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
265 if (namesp != null && namesp != "")
270 cmp = String.Compare ("Implements", directive, true);
272 string ifacename = GetString (atts, "Interface", "");
275 ThrowParseException ("Attribute " + GetOneKey (atts) + " unknown.");
277 Type iface = LoadType (ifacename);
279 ThrowParseException ("Cannot find type " + ifacename);
281 if (!iface.IsInterface)
282 ThrowParseException (iface + " is not an interface");
284 AddInterface (iface.FullName);
288 cmp = String.Compare ("OutputCache", directive, true);
290 HttpResponse response = HttpContext.Current.Response;
291 if (response != null)
292 response.Cache.SetValidUntilExpires (true);
296 if (atts ["Duration"] == null)
297 ThrowParseException ("The directive is missing a 'duration' attribute.");
298 if (atts ["VaryByParam"] == null && atts ["VaryByControl"] == null)
299 ThrowParseException ("This directive is missing 'VaryByParam' " +
300 "or 'VaryByControl' attribute, which should be set to \"none\", \"*\", " +
301 "or a list of name/value pairs.");
303 foreach (DictionaryEntry entry in atts) {
304 string key = (string) entry.Key;
305 switch (key.ToLower ()) {
307 oc_duration = Int32.Parse ((string) entry.Value);
309 ThrowParseException ("The 'duration' attribute must be set " +
310 "to a positive integer value");
313 case "varybycontentencodings":
314 oc_content_encodings = (string) entry.Value;
318 oc_param = (string) entry.Value;
319 if (String.Compare (oc_param, "none") == 0)
323 oc_header = (string) entry.Value;
326 oc_custom = (string) entry.Value;
329 if (!(this is PageParser))
333 oc_location = (OutputCacheLocation) Enum.Parse (
334 typeof (OutputCacheLocation), (string) entry.Value, true);
336 ThrowParseException ("The 'location' attribute is case sensitive and " +
337 "must be one of the following values: Any, Client, " +
338 "Downstream, Server, None, ServerAndClient.");
341 case "varybycontrol":
343 if (this is PageParser)
346 oc_controls = (string) entry.Value;
349 if (this is PageParser)
353 oc_shared = Boolean.Parse ((string) entry.Value);
355 ThrowParseException ("The 'shared' attribute is case sensitive" +
356 " and must be set to 'true' or 'false'.");
360 ThrowParseException ("The '" + key + "' attribute is not " +
361 "supported by the 'Outputcache' directive.");
370 ThrowParseException ("Unknown directive: " + directive);
373 internal Type LoadType (string typeName)
375 Type type = HttpApplication.LoadType (typeName);
378 Assembly asm = type.Assembly;
379 string location = asm.Location;
381 AddDependency (location);
382 string dirname = Path.GetDirectoryName (location);
383 bool doAddAssembly = true;
384 foreach (string dir in HttpApplication.BinDirectories) {
385 if (dirname == dir) {
386 doAddAssembly = false;
392 AddAssembly (asm, true);
397 void AddAssembliesInBin ()
399 foreach (string s in HttpApplication.BinDirectoryAssemblies)
403 internal virtual void AddInterface (string iface)
405 if (interfaces == null)
406 interfaces = new ArrayList ();
408 if (!interfaces.Contains (iface))
409 interfaces.Add (iface);
412 internal virtual void AddImport (string namesp)
415 imports = new ArrayList ();
417 if (!imports.Contains (namesp))
418 imports.Add (namesp);
421 internal virtual void AddSourceDependency (string filename)
423 if (dependencies != null && dependencies.Contains (filename)) {
424 ThrowParseException ("Circular file references are not allowed. File: " + filename);
427 AddDependency (filename);
430 internal virtual void AddDependency (string filename)
435 if (dependencies == null)
436 dependencies = new ArrayList ();
438 if (!dependencies.Contains (filename))
439 dependencies.Add (filename);
442 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
444 if (assembly.Location == "")
448 anames = new Hashtable ();
450 string name = assembly.GetName ().Name;
451 string loc = assembly.Location;
453 if (!assemblies.Contains (loc)) {
454 assemblies.Add (loc);
458 anames [loc] = assembly;
460 if (!assemblies.Contains (name)) {
461 assemblies.Add (name);
464 anames [name] = assembly;
468 internal virtual Assembly AddAssemblyByFileName (string filename)
470 Assembly assembly = null;
471 Exception error = null;
474 assembly = Assembly.LoadFrom (filename);
475 } catch (Exception e) { error = e; }
477 if (assembly == null)
478 ThrowParseException ("Assembly " + filename + " not found", error);
480 AddAssembly (assembly, true);
484 internal virtual Assembly AddAssemblyByName (string name)
487 anames = new Hashtable ();
489 if (anames.Contains (name)) {
490 object o = anames [name];
497 Assembly assembly = null;
498 Exception error = null;
500 assembly = Assembly.Load (name);
501 } catch (Exception e) { error = e; }
503 if (assembly == null) {
505 assembly = Assembly.LoadWithPartialName (name);
506 } catch (Exception e) { error = e; }
509 if (assembly == null)
510 ThrowParseException ("Assembly " + name + " not found", error);
512 AddAssembly (assembly, true);
516 internal virtual void ProcessMainAttributes (Hashtable atts)
518 atts.Remove ("Description"); // ignored
520 atts.Remove ("CodeBehind"); // ignored
522 atts.Remove ("AspCompat"); // ignored
524 debug = GetBool (atts, "Debug", true);
525 compilerOptions = GetString (atts, "CompilerOptions", "");
526 language = GetString (atts, "Language", "");
527 if (language.Length != 0)
528 implicitLanguage = false;
530 language = CompilationConfig.DefaultLanguage;
532 strictOn = GetBool (atts, "Strict", CompilationConfig.Strict);
533 explicitOn = GetBool (atts, "Explicit", CompilationConfig.Explicit);
534 linePragmasOn = GetBool (atts, "LinePragmas", false);
536 string inherits = GetString (atts, "Inherits", null);
538 // In ASP 2, the source file is actually integrated with
539 // the generated file via the use of partial classes. This
540 // means that the code file has to be confirmed, but not
541 // used at this point.
542 src = GetString (atts, "CodeFile", null);
543 codeFileBaseClass = GetString (atts, "CodeFileBaseClass", null);
545 if (src == null && codeFileBaseClass != null)
546 ThrowParseException ("The 'CodeFileBaseClass' attribute cannot be used without a 'CodeFile' attribute");
548 if (src != null && inherits != null) {
549 // Make sure the source exists
550 src = UrlUtils.Combine (BaseVirtualDir, src);
551 string realPath = MapPath (src, false);
552 if (!File.Exists (realPath))
553 ThrowParseException ("File " + src + " not found");
555 // We are going to create a partial class that shares
556 // the same name as the inherits tag, so reset the
557 // name. The base type is changed because it is the
558 // code file's responsibilty to extend the classes
560 partialClassName = inherits;
562 // Add the code file as an option to the
563 // compiler. This lets both files be compiled at once.
564 compilerOptions += " \"" + realPath + "\"";
566 if (codeFileBaseClass != null) {
568 codeFileBaseClassType = LoadType (codeFileBaseClass);
569 } catch (Exception) {
572 if (codeFileBaseClassType == null)
573 ThrowParseException ("Could not load type '{0}'", codeFileBaseClass);
575 } else if (inherits != null) {
576 // We just set the inherits directly because this is a
577 // Single-Page model.
578 SetBaseType (inherits);
581 string src = GetString (atts, "Src", null);
584 srcAssembly = GetAssemblyFromSource (src);
586 if (inherits != null)
587 SetBaseType (inherits);
590 AddDependency (MapPath (src, false));
592 className = GetString (atts, "ClassName", null);
593 if (className != null) {
595 string [] identifiers = className.Split ('.');
596 for (int i = 0; i < identifiers.Length; i++)
597 if (!CodeGenerator.IsValidLanguageIndependentIdentifier (identifiers [i]))
598 ThrowParseException (String.Format ("'{0}' is not a valid "
599 + "value for attribute 'classname'.", className));
601 if (!CodeGenerator.IsValidLanguageIndependentIdentifier (className))
602 ThrowParseException (String.Format ("'{0}' is not a valid "
603 + "value for attribute 'classname'.", className));
608 if (this is TemplateControlParser)
609 metaResourceKey = GetString (atts, "meta:resourcekey", null);
611 if (inherits != null && (this is PageParser || this is UserControlParser) && atts.Count > 0) {
612 if (unknownMainAttributes == null)
613 unknownMainAttributes = new List <UnknownAttributeDescriptor> ();
616 foreach (DictionaryEntry de in atts) {
617 key = de.Key as string;
618 val = de.Value as string;
620 if (String.IsNullOrEmpty (key) || String.IsNullOrEmpty (val))
622 CheckUnknownAttribute (key, val, inherits);
628 ThrowParseException ("Unknown attribute: " + GetOneKey (atts));
632 void CheckUnknownAttribute (string name, string val, string inherits)
634 MemberInfo mi = null;
635 bool missing = false;
636 string memberName = name.Trim ().ToLower (CultureInfo.InvariantCulture);
637 Type parent = codeFileBaseClassType;
643 MemberInfo[] infos = parent.GetMember (memberName,
644 MemberTypes.Field | MemberTypes.Property,
645 BindingFlags.Public | BindingFlags.Instance |
646 BindingFlags.IgnoreCase | BindingFlags.Static);
647 if (infos.Length != 0) {
648 // prefer public properties to public methods (it's what MS.NET does)
649 foreach (MemberInfo tmp in infos) {
650 if (tmp is PropertyInfo) {
659 } catch (Exception) {
663 ThrowParseException (
664 "Error parsing attribute '{0}': Type '{1}' does not have a public property named '{0}'",
665 memberName, inherits);
667 Type memberType = null;
668 if (mi is PropertyInfo) {
669 PropertyInfo pi = mi as PropertyInfo;
672 ThrowParseException (
673 "Error parsing attribute '{0}': The '{0}' property is read-only and cannot be set.",
675 memberType = pi.PropertyType;
676 } else if (mi is FieldInfo) {
677 memberType = ((FieldInfo)mi).FieldType;
679 ThrowParseException ("Could not determine member the kind of '{0}' in base type '{1}",
680 memberName, inherits);
681 TypeConverter converter = TypeDescriptor.GetConverter (memberType);
682 bool convertible = true;
685 if (converter == null || !converter.CanConvertFrom (typeof (string)))
690 value = converter.ConvertFromInvariantString (val);
691 } catch (Exception) {
697 ThrowParseException ("Error parsing attribute '{0}': Cannot create an object of type '{1}' from its string representation '{2}' for the '{3}' property.",
698 memberName, memberType, val, mi.Name);
700 UnknownAttributeDescriptor desc = new UnknownAttributeDescriptor (mi, value);
701 unknownMainAttributes.Add (desc);
705 internal void SetBaseType (string type)
707 if (type == DefaultBaseTypeName)
711 if (srcAssembly != null)
712 parent = srcAssembly.GetType (type);
715 parent = LoadType (type);
718 ThrowParseException ("Cannot find type " + type);
720 if (!DefaultBaseType.IsAssignableFrom (parent))
721 ThrowParseException ("The parent type does not derive from " + DefaultBaseType);
724 if (parent.FullName.IndexOf ('.') == -1)
725 baseTypeIsGlobal = true;
728 internal void SetLanguage (string language)
730 this.language = language;
731 implicitLanguage = false;
734 Assembly GetAssemblyFromSource (string vpath)
736 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
737 string realPath = MapPath (vpath, false);
738 if (!File.Exists (realPath))
739 ThrowParseException ("File " + vpath + " not found");
741 AddSourceDependency (realPath);
743 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
744 if (result.NativeCompilerReturnValue != 0) {
745 StreamReader reader = new StreamReader (realPath);
746 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
749 AddAssembly (result.CompiledAssembly, true);
750 return result.CompiledAssembly;
753 internal abstract Type DefaultBaseType { get; }
754 internal abstract string DefaultBaseTypeName { get; }
755 internal abstract string DefaultDirectiveName { get; }
757 internal string InputFile
759 get { return inputFile; }
760 set { inputFile = value; }
764 internal bool IsPartial {
765 get { return src != null; }
768 internal string PartialClassName {
769 get { return partialClassName; }
772 internal string CodeFileBaseClass {
773 get { return codeFileBaseClass; }
776 internal string MetaResourceKey {
777 get { return metaResourceKey; }
780 internal Type CodeFileBaseClassType
782 get { return codeFileBaseClassType; }
785 internal List <UnknownAttributeDescriptor> UnknownMainAttributes
787 get { return unknownMainAttributes; }
794 set { text = value; }
797 internal Type BaseType
800 if (baseType == null)
801 baseType = DefaultBaseType;
807 internal bool BaseTypeIsGlobal {
808 get { return baseTypeIsGlobal; }
811 internal string ClassName {
813 if (className != null)
817 string physPath = HttpContext.Current.Request.PhysicalApplicationPath;
819 if (StrUtils.StartsWith (inputFile, physPath)) {
820 className = inputFile.Substring (physPath.Length).ToLower (CultureInfo.InvariantCulture);
821 className = className.Replace ('.', '_');
822 className = className.Replace ('/', '_').Replace ('\\', '_');
825 className = Path.GetFileName (inputFile).Replace ('.', '_');
826 className = className.Replace ('-', '_');
827 className = className.Replace (' ', '_');
829 if (Char.IsDigit(className[0])) {
830 className = "_" + className;
837 internal ArrayList Scripts {
840 scripts = new ArrayList ();
846 internal ArrayList Imports {
847 get { return imports; }
850 internal ArrayList Assemblies {
852 if (appAssemblyIndex != -1) {
853 object o = assemblies [appAssemblyIndex];
854 assemblies.RemoveAt (appAssemblyIndex);
856 appAssemblyIndex = -1;
863 internal ArrayList Interfaces {
864 get { return interfaces; }
867 internal RootBuilder RootBuilder {
868 get { return rootBuilder; }
869 set { rootBuilder = value; }
872 internal ArrayList Dependencies {
873 get { return dependencies; }
874 set { dependencies = value; }
877 internal string CompilerOptions {
878 get { return compilerOptions; }
881 internal string Language {
882 get { return language; }
885 internal bool ImplicitLanguage {
886 get { return implicitLanguage; }
889 internal bool StrictOn {
890 get { return strictOn; }
893 internal bool ExplicitOn {
894 get { return explicitOn; }
897 internal bool Debug {
898 get { return debug; }
901 internal bool OutputCache {
902 get { return output_cache; }
905 internal int OutputCacheDuration {
906 get { return oc_duration; }
910 internal string OutputCacheVaryByContentEncodings {
911 get { return oc_content_encodings; }
915 internal string OutputCacheVaryByHeader {
916 get { return oc_header; }
919 internal string OutputCacheVaryByCustom {
920 get { return oc_custom; }
923 internal string OutputCacheVaryByControls {
924 get { return oc_controls; }
927 internal bool OutputCacheShared {
928 get { return oc_shared; }
931 internal OutputCacheLocation OutputCacheLocation {
932 get { return oc_location; }
935 internal string OutputCacheVaryByParam {
936 get { return oc_param; }
940 internal PagesSection PagesConfig {
942 return WebConfigurationManager.GetSection ("system.web/pages") as PagesSection;
946 internal PagesConfiguration PagesConfig {
947 get { return PagesConfiguration.GetInstance (Context); }