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 ()
121 bool directiveFound = false;
122 StringBuilder content = new StringBuilder ();
123 using (StreamReader reader = new StreamReader (File.OpenRead (physPath))) {
124 while ((line = reader.ReadLine ()) != null && cachedType == null) {
125 string trimmed = line.Trim ();
126 if (!directiveFound && trimmed == String.Empty)
129 if (trimmed.StartsWith ("<")) {
130 ParseDirective (trimmed);
131 directiveFound = true;
133 cachedType = CachingCompiler.GetTypeFromCache (physPath);
134 if (cachedType != null)
141 content.Append (line + "\n");
142 content.Append (reader.ReadToEnd ());
147 throw new ParseException (null, "No @" + DefaultDirectiveName +
150 if (cachedType == null)
151 this.program = content.ToString ();
154 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
156 if (tagtype != System.Web.Compilation.TagType.Directive)
157 throw new ParseException (location, "Unexpected tag");
159 if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
160 AddDefaultDirective (location, attributes);
161 } else if (String.Compare (tagid, "Assembly", true) == 0) {
162 AddAssemblyDirective (location, attributes);
164 throw new ParseException (location, "Unexpected directive: " + tagid);
168 void TextParsed (ILocation location, string text)
170 if (text.Trim () != "")
171 throw new ParseException (location, "Text not allowed here");
174 void ParseError (ILocation location, string message)
176 throw new ParseException (location, message);
179 static string GetAndRemove (Hashtable table, string key)
181 string o = table [key] as string;
186 void ParseDirective (string line)
188 AspParser parser = new AspParser (physPath, new StringReader (line));
189 parser.Error += new ParseErrorHandler (ParseError);
190 parser.TagParsed += new TagParsedHandler (TagParsed);
191 parser.TextParsed += new TextParsedHandler (TextParsed);
196 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
199 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
202 Hashtable attributes = attrs.GetDictionary (null);
203 className = GetAndRemove (attributes, "class");
204 if (className == null)
205 throw new ParseException (null, "No Class attribute found.");
207 string d = GetAndRemove (attributes, "debug");
209 debug = (String.Compare (d, "true", true) == 0);
210 if (debug == false && String.Compare (d, "false", true) != 0)
211 throw new ParseException (null, "Invalid value for Debug attribute");
214 language = GetAndRemove (attributes, "language");
215 if (language == null)
216 language = CompilationConfig.DefaultLanguage;
218 GetAndRemove (attributes, "codebehind");
219 if (attributes.Count > 0)
220 throw new ParseException (location, "Unrecognized attribute in " +
221 DefaultDirectiveName + " directive");
224 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
226 Hashtable tbl = attrs.GetDictionary (null);
227 string name = GetAndRemove (tbl, "Name");
228 string src = GetAndRemove (tbl, "Src");
229 if (name == null && src == null)
230 throw new ParseException (location, "You gotta specify Src or Name");
232 if (name != null && src != null)
233 throw new ParseException (location, "Src and Name cannot be used together");
236 AddAssemblyByName (name, location);
238 GetAssemblyFromSource (src, location);
242 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
245 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
248 anames = new Hashtable ();
250 string name = assembly.GetName ().Name;
251 string loc = assembly.Location;
253 if (!assemblies.Contains (loc)) {
254 assemblies.Add (loc);
258 anames [loc] = assembly;
260 if (!assemblies.Contains (name)) {
261 assemblies.Add (name);
264 anames [name] = assembly;
268 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
271 anames = new Hashtable ();
273 if (anames.Contains (name)) {
274 object o = anames [name];
281 Assembly assembly = LoadAssemblyFromBin (name);
282 if (assembly != null) {
283 AddAssembly (assembly, true);
288 assembly = Assembly.LoadWithPartialName (name);
289 } catch (Exception e) {
290 throw new ParseException (location, "Assembly " + name + " not found", e);
293 AddAssembly (assembly, true);
297 void AddAssembliesInBin ()
299 if (!Directory.Exists (PrivateBinPath))
302 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
303 foreach (string dll in binDlls) {
305 Assembly assembly = Assembly.LoadFrom (dll);
306 AddAssembly (assembly, true);
307 } catch (Exception e) {
308 throw new Exception ("Error while loading " + dll, e);
313 Assembly LoadAssemblyFromBin (string name)
316 if (!Directory.Exists (PrivateBinPath))
319 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
320 foreach (string dll in binDlls) {
321 string fn = Path.GetFileName (dll);
322 fn = Path.ChangeExtension (fn, null);
326 assembly = Assembly.LoadFrom (dll);
333 Assembly GetAssemblyFromSource (string vpath, ILocation location)
335 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
336 string realPath = context.Request.MapPath (vpath);
337 if (!File.Exists (realPath))
338 throw new ParseException (location, "File " + vpath + " not found");
340 AddDependency (realPath);
342 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
343 if (result.NativeCompilerReturnValue != 0) {
344 StreamReader reader = new StreamReader (realPath);
345 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
348 AddAssembly (result.CompiledAssembly, true);
349 return result.CompiledAssembly;
352 internal Type GetTypeFromBin (string typeName)
356 IList toplevelAssemblies = BuildManager.TopLevelAssemblies;
357 if (toplevelAssemblies != null && toplevelAssemblies.Count > 0) {
358 foreach (Assembly asm in toplevelAssemblies) {
359 Type type = asm.GetType (typeName, false);
362 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
368 if (!Directory.Exists (PrivateBinPath))
370 throw new HttpException (String.Format ("Type {0} not found.", typeName));
374 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
375 foreach (string dll in binDlls) {
376 Assembly assembly = Assembly.LoadFrom (dll);
377 Type type = assembly.GetType (typeName, false);
380 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
387 throw new HttpException (String.Format ("Type {0} not found.", typeName));
392 internal virtual void AddDependency (string filename)
394 if (dependencies == null)
395 dependencies = new ArrayList ();
397 if (!dependencies.Contains (filename))
398 dependencies.Add (filename);
402 protected abstract string DefaultDirectiveName { get; }
404 internal HttpContext Context {
405 get { return context; }
408 internal string VirtualPath {
409 get { return vPath; }
412 internal string PhysicalPath {
413 get { return physPath; }
416 internal string ClassName {
417 get { return className; }
420 internal bool Debug {
421 get { return debug; }
424 internal string Language {
425 get { return language; }
428 internal string Program {
429 get { return program; }
432 internal ArrayList Assemblies {
434 if (appAssemblyIndex != -1) {
435 object o = assemblies [appAssemblyIndex];
436 assemblies.RemoveAt (appAssemblyIndex);
438 appAssemblyIndex = -1;
445 internal ArrayList Dependencies {
446 get { return dependencies; }
449 internal string PrivateBinPath {
451 if (privateBinPath != null)
452 return privateBinPath;
454 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
455 privateBinPath = setup.PrivateBinPath;
457 if (!Path.IsPathRooted (privateBinPath)) {
458 string appbase = setup.ApplicationBase;
459 if (appbase.StartsWith ("file://")) {
460 appbase = appbase.Substring (7);
461 if (Path.DirectorySeparatorChar != '/')
462 appbase = appbase.Replace ('/', Path.DirectorySeparatorChar);
464 privateBinPath = Path.Combine (appbase, privateBinPath);
467 return privateBinPath;
471 internal string BaseDir {
474 baseDir = context.Request.MapPath (BaseVirtualDir);
480 internal virtual string BaseVirtualDir {
482 if (baseVDir == null)
483 baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
490 CompilationSection CompilationConfig {
492 return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
496 internal TextReader Reader {
497 get { return reader; }
498 set { reader = value; }
501 internal CompilationConfiguration CompilationConfig {
503 if (compilationConfig == null)
504 compilationConfig = CompilationConfiguration.GetInstance (context);
506 return compilationConfig;