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 // context is obsolete in 2.0+ - MSDN recommends passing null, so we need to
76 // take that into account
78 this.context = context;
80 this.context = HttpContext.Current;
82 this.vPath = virtualPath;
83 AddDependency (virtualPath);
85 // physicalPath is obsolete in 2.0+ - same note what for context applies here
86 if (physicalPath != null && physicalPath.Length > 0)
87 this.physPath = physicalPath;
89 HttpRequest req = this.context != null ? context.Request : null;
91 this.physPath = req.MapPath (virtualPath);
94 assemblies = new ArrayList ();
95 string location = Context.ApplicationInstance.AssemblyLocation;
96 if (location != typeof (TemplateParser).Assembly.Location)
97 appAssemblyIndex = assemblies.Add (location);
100 bool addAssembliesInBin = false;
101 foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
102 if (info.Assembly == "*")
103 addAssembliesInBin = true;
105 AddAssemblyByName (info.Assembly, null);
107 if (addAssembliesInBin)
108 AddAssembliesInBin ();
110 assemblies.AddRange (CompilationConfig.Assemblies);
111 if (CompilationConfig.AssembliesInBin)
112 AddAssembliesInBin ();
115 language = CompilationConfig.DefaultLanguage;
117 GetDirectivesAndContent ();
120 internal SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath, TextReader reader)
121 : this (context, virtualPath, physicalPath)
123 this.reader = reader;
127 protected Type GetCompiledTypeFromCache ()
132 void GetDirectivesAndContent ()
135 bool directiveFound = false;
136 bool inDirective = false;
137 StringBuilder directive = null;
138 StringBuilder content = new StringBuilder ();
139 int idxStart, idxEnd, length;
141 using (StreamReader reader = new StreamReader (File.OpenRead (physPath), WebEncoding.FileEncoding)) {
142 while ((line = reader.ReadLine ()) != null && cachedType == null) {
143 length = line.Length;
145 content.Append ("\n");
149 idxStart = line.IndexOf ("<%");
151 idxEnd = line.IndexOf ("%>");
153 content.Append (line.Substring (0, idxStart));
155 if (directive == null)
156 directive = new StringBuilder ();
158 directive.Length = 0;
161 directiveFound = true;
163 directive.Append (line.Substring (idxStart, idxEnd - idxStart + 2));
164 if (idxEnd < length - 2)
165 content.Append (line.Substring (idxEnd + 2, length - idxEnd - 2));
168 directiveFound = false;
169 directive.Append (line.Substring (idxStart));
175 int idx = line.IndexOf ("%>");
177 directive.Append (line.Substring (0, idx + 2));
179 content.Append (line.Substring (idx + 2) + "\n");
181 directiveFound = true;
183 directive.Append (line);
188 if (directiveFound) {
189 ParseDirective (directive.ToString ());
190 directiveFound = false;
192 cachedType = CachingCompiler.GetTypeFromCache (physPath);
193 if (cachedType != null)
200 content.Append (line + "\n");
206 throw new ParseException (null, "No @" + DefaultDirectiveName +
209 if (cachedType == null)
210 this.program = content.ToString ();
213 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
215 if (tagtype != System.Web.Compilation.TagType.Directive)
216 throw new ParseException (location, "Unexpected tag");
218 if (tagid == null || tagid.Length == 0 || String.Compare (tagid, DefaultDirectiveName, true) == 0) {
219 AddDefaultDirective (location, attributes);
220 } else if (String.Compare (tagid, "Assembly", true) == 0) {
221 AddAssemblyDirective (location, attributes);
223 throw new ParseException (location, "Unexpected directive: " + tagid);
227 void TextParsed (ILocation location, string text)
229 if (text.Trim () != "")
230 throw new ParseException (location, "Text not allowed here");
233 void ParseError (ILocation location, string message)
235 throw new ParseException (location, message);
238 static string GetAndRemove (Hashtable table, string key)
240 string o = table [key] as string;
245 void ParseDirective (string line)
247 AspParser parser = new AspParser (physPath, new StringReader (line));
248 parser.Error += new ParseErrorHandler (ParseError);
249 parser.TagParsed += new TagParsedHandler (TagParsed);
250 parser.TextParsed += new TextParsedHandler (TextParsed);
255 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
258 CompilationSection compConfig;
260 CompilationConfiguration compConfig;
262 compConfig = CompilationConfig;
265 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
268 Hashtable attributes = attrs.GetDictionary (null);
269 className = GetAndRemove (attributes, "class");
270 if (className == null)
271 throw new ParseException (null, "No Class attribute found.");
273 string d = GetAndRemove (attributes, "debug");
275 debug = (String.Compare (d, "true", true) == 0);
276 if (debug == false && String.Compare (d, "false", true) != 0)
277 throw new ParseException (null, "Invalid value for Debug attribute");
279 debug = compConfig.Debug;
281 language = GetAndRemove (attributes, "language");
282 if (language == null)
283 language = compConfig.DefaultLanguage;
285 GetAndRemove (attributes, "codebehind");
286 if (attributes.Count > 0)
287 throw new ParseException (location, "Unrecognized attribute in " +
288 DefaultDirectiveName + " directive");
291 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
293 Hashtable tbl = attrs.GetDictionary (null);
294 string name = GetAndRemove (tbl, "Name");
295 string src = GetAndRemove (tbl, "Src");
296 if (name == null && src == null)
297 throw new ParseException (location, "You gotta specify Src or Name");
299 if (name != null && src != null)
300 throw new ParseException (location, "Src and Name cannot be used together");
303 AddAssemblyByName (name, location);
305 GetAssemblyFromSource (src, location);
309 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
312 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
314 if (assembly == null)
315 throw new ArgumentNullException ("assembly");
318 anames = new Hashtable ();
320 string name = assembly.GetName ().Name;
321 string loc = assembly.Location;
323 if (!assemblies.Contains (loc)) {
324 assemblies.Add (loc);
328 anames [loc] = assembly;
330 if (!assemblies.Contains (name)) {
331 assemblies.Add (name);
334 anames [name] = assembly;
338 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
341 anames = new Hashtable ();
343 if (anames.Contains (name)) {
344 object o = anames [name];
351 Assembly assembly = LoadAssemblyFromBin (name);
352 if (assembly != null) {
353 AddAssembly (assembly, true);
359 assembly = Assembly.LoadWithPartialName (name);
360 } catch (Exception e) {
365 if (assembly == null)
366 throw new ParseException (location, String.Format ("Assembly '{0}' not found", name), ex);
368 AddAssembly (assembly, true);
372 void AddAssembliesInBin ()
374 foreach (string s in HttpApplication.BinDirectoryAssemblies) {
376 Assembly assembly = Assembly.LoadFrom (s);
377 AddAssembly (assembly, true);
378 } catch (Exception e) {
379 throw new Exception ("Error while loading " + s, e);
384 Assembly LoadAssemblyFromBin (string name)
386 Assembly assembly = null;
387 foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
388 string fn = Path.GetFileName (dll);
389 fn = Path.ChangeExtension (fn, null);
393 assembly = Assembly.LoadFrom (dll);
400 Assembly GetAssemblyFromSource (string vpath, ILocation location)
402 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
403 string realPath = context.Request.MapPath (vpath);
404 if (!File.Exists (realPath))
405 throw new ParseException (location, "File " + vpath + " not found");
407 AddDependency (vpath);
409 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
410 if (result.NativeCompilerReturnValue != 0) {
411 StreamReader reader = new StreamReader (realPath);
412 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
415 AddAssembly (result.CompiledAssembly, true);
416 return result.CompiledAssembly;
419 internal Type GetTypeFromBin (string tname)
421 if (tname == null || tname.Length == 0)
422 throw new ArgumentNullException ("tname");
427 int comma = tname.IndexOf (',');
430 typeName = tname.Substring (0, comma).Trim ();
431 assemblyName = tname.Substring (comma + 1).Trim ();
438 Assembly assembly = null;
439 if (assemblyName != null) {
440 assembly = Assembly.Load (assemblyName);
441 if (assembly != null)
442 type = assembly.GetType (typeName, false);
448 IList toplevelAssemblies = BuildManager.TopLevelAssemblies;
449 if (toplevelAssemblies != null && toplevelAssemblies.Count > 0) {
450 foreach (Assembly asm in toplevelAssemblies) {
451 type = asm.GetType (typeName, false);
454 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
461 foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
462 assembly = Assembly.LoadFrom (dll);
463 type = assembly.GetType (typeName, false);
466 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
474 throw new HttpException (String.Format ("Type {0} not found.", typeName));
479 internal virtual void AddDependency (string filename)
481 if (dependencies == null)
482 dependencies = new ArrayList ();
484 if (!dependencies.Contains (filename))
485 dependencies.Add (filename);
489 protected abstract string DefaultDirectiveName { get; }
491 internal HttpContext Context {
492 get { return context; }
495 internal string VirtualPath {
496 get { return vPath; }
499 internal string PhysicalPath {
500 get { return physPath; }
503 internal string ClassName {
504 get { return className; }
507 internal bool Debug {
508 get { return debug; }
511 internal string Language {
512 get { return language; }
515 internal string Program {
524 internal ArrayList Assemblies {
526 if (appAssemblyIndex != -1) {
527 object o = assemblies [appAssemblyIndex];
528 assemblies.RemoveAt (appAssemblyIndex);
530 appAssemblyIndex = -1;
537 internal ArrayList Dependencies {
538 get { return dependencies; }
541 internal string BaseDir {
544 baseDir = context.Request.MapPath (BaseVirtualDir);
550 internal virtual string BaseVirtualDir {
552 if (baseVDir == null)
553 baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
560 CompilationSection CompilationConfig {
562 return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
566 internal TextReader Reader {
567 get { return reader; }
568 set { reader = value; }
571 internal CompilationConfiguration CompilationConfig {
573 if (compilationConfig == null)
574 compilationConfig = CompilationConfiguration.GetInstance (context);
576 return compilationConfig;