2 // System.Web.UI.SimpleWebHandlerParser
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
8 // Copyright (C) 2005 Novell, Inc (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 using System.CodeDom.Compiler;
31 using System.Collections;
33 using System.Reflection;
34 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 SimpleWebHandlerParser
56 ArrayList dependencies;
58 string privateBinPath;
62 CompilationConfiguration compilationConfig;
66 int appAssemblyIndex = -1;
69 protected SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath)
71 cachedType = CachingCompiler.GetTypeFromCache (physicalPath);
72 if (cachedType != null)
73 return; // We don't need anything else.
75 this.context = context;
76 this.vPath = virtualPath;
77 this.physPath = physicalPath;
78 AddDependency (physicalPath);
80 assemblies = new ArrayList ();
81 string location = Context.ApplicationInstance.AssemblyLocation;
82 if (location != typeof (TemplateParser).Assembly.Location)
83 appAssemblyIndex = assemblies.Add (location);
86 bool addAssembliesInBin = false;
87 foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
88 if (info.Assembly == "*")
89 addAssembliesInBin = true;
91 AddAssemblyByName (info.Assembly, null);
93 if (addAssembliesInBin)
94 AddAssembliesInBin ();
96 assemblies.AddRange (CompilationConfig.Assemblies);
97 if (CompilationConfig.AssembliesInBin)
98 AddAssembliesInBin ();
101 language = CompilationConfig.DefaultLanguage;
103 GetDirectivesAndContent ();
106 internal SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath, TextReader reader)
107 : this (context, virtualPath, physicalPath)
109 this.reader = reader;
113 protected Type GetCompiledTypeFromCache ()
118 void GetDirectivesAndContent ()
120 StreamReader reader = new StreamReader (File.OpenRead (physPath));
122 bool directiveFound = false;
123 StringBuilder content = new StringBuilder ();
125 while ((line = reader.ReadLine ()) != null && cachedType == null) {
126 string trimmed = line.Trim ();
127 if (!directiveFound && trimmed == String.Empty)
130 if (trimmed.StartsWith ("<")) {
131 ParseDirective (trimmed);
132 directiveFound = true;
134 cachedType = CachingCompiler.GetTypeFromCache (physPath);
135 if (cachedType != null)
142 content.Append (line + "\n");
143 content.Append (reader.ReadToEnd ());
148 throw new ParseException (null, "No @" + DefaultDirectiveName +
151 if (cachedType == null)
152 this.program = content.ToString ();
155 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
157 if (tagtype != System.Web.Compilation.TagType.Directive)
158 throw new ParseException (location, "Unexpected tag");
160 if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
161 AddDefaultDirective (location, attributes);
162 } else if (String.Compare (tagid, "Assembly", true) == 0) {
163 AddAssemblyDirective (location, attributes);
165 throw new ParseException (location, "Unexpected directive: " + tagid);
169 void TextParsed (ILocation location, string text)
171 if (text.Trim () != "")
172 throw new ParseException (location, "Text not allowed here");
175 void ParseError (ILocation location, string message)
177 throw new ParseException (location, message);
180 static string GetAndRemove (Hashtable table, string key)
182 string o = table [key] as string;
187 void ParseDirective (string line)
189 AspParser parser = new AspParser (physPath, new StringReader (line));
190 parser.Error += new ParseErrorHandler (ParseError);
191 parser.TagParsed += new TagParsedHandler (TagParsed);
192 parser.TextParsed += new TextParsedHandler (TextParsed);
197 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
200 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
203 Hashtable attributes = attrs.GetDictionary (null);
204 className = GetAndRemove (attributes, "class");
205 if (className == null)
206 throw new ParseException (null, "No Class attribute found.");
208 string d = GetAndRemove (attributes, "debug");
210 debug = (String.Compare (d, "true", true) == 0);
211 if (debug == false && String.Compare (d, "false", true) != 0)
212 throw new ParseException (null, "Invalid value for Debug attribute");
215 language = GetAndRemove (attributes, "language");
216 if (language == null)
217 language = CompilationConfig.DefaultLanguage;
219 GetAndRemove (attributes, "codebehind");
220 if (attributes.Count > 0)
221 throw new ParseException (location, "Unrecognized attribute in " +
222 DefaultDirectiveName + " directive");
225 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
227 Hashtable tbl = attrs.GetDictionary (null);
228 string name = GetAndRemove (tbl, "Name");
229 string src = GetAndRemove (tbl, "Src");
230 if (name == null && src == null)
231 throw new ParseException (location, "You gotta specify Src or Name");
233 if (name != null && src != null)
234 throw new ParseException (location, "Src and Name cannot be used together");
237 AddAssemblyByName (name, location);
239 GetAssemblyFromSource (src, location);
243 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
246 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
249 anames = new Hashtable ();
251 string name = assembly.GetName ().Name;
252 string loc = assembly.Location;
254 if (!assemblies.Contains (loc)) {
255 assemblies.Add (loc);
259 anames [loc] = assembly;
261 if (!assemblies.Contains (name)) {
262 assemblies.Add (name);
265 anames [name] = assembly;
269 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
272 anames = new Hashtable ();
274 if (anames.Contains (name)) {
275 object o = anames [name];
282 Assembly assembly = LoadAssemblyFromBin (name);
283 if (assembly != null) {
284 AddAssembly (assembly, true);
289 assembly = Assembly.LoadWithPartialName (name);
290 } catch (Exception e) {
291 throw new ParseException (location, "Assembly " + name + " not found", e);
294 AddAssembly (assembly, true);
298 void AddAssembliesInBin ()
300 if (!Directory.Exists (PrivateBinPath))
303 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
304 foreach (string dll in binDlls) {
306 Assembly assembly = Assembly.LoadFrom (dll);
307 AddAssembly (assembly, true);
308 } catch (Exception e) {
309 throw new Exception ("Error while loading " + dll, e);
314 Assembly LoadAssemblyFromBin (string name)
317 if (!Directory.Exists (PrivateBinPath))
320 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
321 foreach (string dll in binDlls) {
322 string fn = Path.GetFileName (dll);
323 fn = Path.ChangeExtension (fn, null);
327 assembly = Assembly.LoadFrom (dll);
334 Assembly GetAssemblyFromSource (string vpath, ILocation location)
336 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
337 string realPath = context.Request.MapPath (vpath);
338 if (!File.Exists (realPath))
339 throw new ParseException (location, "File " + vpath + " not found");
341 AddDependency (realPath);
343 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
344 if (result.NativeCompilerReturnValue != 0) {
345 StreamReader reader = new StreamReader (realPath);
346 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
349 AddAssembly (result.CompiledAssembly, true);
350 return result.CompiledAssembly;
353 internal Type GetTypeFromBin (string typeName)
355 if (!Directory.Exists (PrivateBinPath))
356 throw new HttpException (String.Format ("Type {0} not found.", typeName));
358 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
360 foreach (string dll in binDlls) {
361 Assembly assembly = Assembly.LoadFrom (dll);
362 Type type = assembly.GetType (typeName, false);
365 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
372 throw new HttpException (String.Format ("Type {0} not found.", typeName));
377 internal virtual void AddDependency (string filename)
379 if (dependencies == null)
380 dependencies = new ArrayList ();
382 if (!dependencies.Contains (filename))
383 dependencies.Add (filename);
387 protected abstract string DefaultDirectiveName { get; }
389 internal HttpContext Context {
390 get { return context; }
393 internal string VirtualPath {
394 get { return vPath; }
397 internal string PhysicalPath {
398 get { return physPath; }
401 internal string ClassName {
402 get { return className; }
405 internal bool Debug {
406 get { return debug; }
409 internal string Language {
410 get { return language; }
413 internal string Program {
414 get { return program; }
417 internal ArrayList Assemblies {
419 if (appAssemblyIndex != -1) {
420 object o = assemblies [appAssemblyIndex];
421 assemblies.RemoveAt (appAssemblyIndex);
423 appAssemblyIndex = -1;
430 internal ArrayList Dependencies {
431 get { return dependencies; }
434 internal string PrivateBinPath {
436 if (privateBinPath != null)
437 return privateBinPath;
439 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
440 privateBinPath = setup.PrivateBinPath;
442 if (!Path.IsPathRooted (privateBinPath)) {
443 string appbase = setup.ApplicationBase;
444 if (appbase.StartsWith ("file://")) {
445 appbase = appbase.Substring (7);
446 if (Path.DirectorySeparatorChar != '/')
447 appbase = appbase.Replace ('/', Path.DirectorySeparatorChar);
449 privateBinPath = Path.Combine (appbase, privateBinPath);
452 return privateBinPath;
456 internal string BaseDir {
459 baseDir = context.Request.MapPath (BaseVirtualDir);
465 internal virtual string BaseVirtualDir {
467 if (baseVDir == null)
468 baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
475 CompilationSection CompilationConfig {
477 return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
481 internal TextReader Reader {
482 get { return reader; }
483 set { reader = value; }
486 internal CompilationConfiguration CompilationConfig {
488 if (compilationConfig == null)
489 compilationConfig = CompilationConfiguration.GetInstance (context);
491 return compilationConfig;