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)
70 : this (context, virtualPath, physicalPath, null)
73 internal SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath, TextReader reader)
76 cachedType = CachingCompiler.GetTypeFromCache (physicalPath);
77 if (cachedType != null)
78 return; // We don't need anything else.
80 // context is obsolete in 2.0+ - MSDN recommends passing null, so we need to
81 // take that into account
83 this.context = context;
85 this.context = HttpContext.Current;
87 this.vPath = virtualPath;
88 AddDependency (virtualPath);
90 // physicalPath is obsolete in 2.0+ - same note what for context applies here
91 if (physicalPath != null && physicalPath.Length > 0)
92 this.physPath = physicalPath;
94 HttpRequest req = this.context != null ? context.Request : null;
96 this.physPath = req.MapPath (virtualPath);
99 assemblies = new ArrayList ();
100 string location = Context.ApplicationInstance.AssemblyLocation;
101 if (location != typeof (TemplateParser).Assembly.Location)
102 appAssemblyIndex = assemblies.Add (location);
105 bool addAssembliesInBin = false;
106 foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
107 if (info.Assembly == "*")
108 addAssembliesInBin = true;
110 AddAssemblyByName (info.Assembly, null);
112 if (addAssembliesInBin)
113 AddAssembliesInBin ();
115 assemblies.AddRange (CompilationConfig.Assemblies);
116 if (CompilationConfig.AssembliesInBin)
117 AddAssembliesInBin ();
120 language = CompilationConfig.DefaultLanguage;
122 GetDirectivesAndContent ();
125 protected Type GetCompiledTypeFromCache ()
130 void GetDirectivesAndContent ()
133 bool directiveFound = false;
134 bool inDirective = false;
135 StringBuilder directive = null;
136 StringBuilder content = new StringBuilder ();
137 int idxStart, idxEnd, length;
142 sr = reader as StreamReader;
145 sr = new StreamReader (File.OpenRead (physPath), WebEncoding.FileEncoding);
148 while ((line = sr.ReadLine ()) != null && cachedType == null) {
149 length = line.Length;
151 content.Append ("\n");
155 idxStart = line.IndexOf ("<%");
157 idxEnd = line.IndexOf ("%>");
159 content.Append (line.Substring (0, idxStart));
161 if (directive == null)
162 directive = new StringBuilder ();
164 directive.Length = 0;
167 directiveFound = true;
169 directive.Append (line.Substring (idxStart, idxEnd - idxStart + 2));
170 if (idxEnd < length - 2)
171 content.Append (line.Substring (idxEnd + 2, length - idxEnd - 2));
174 directiveFound = false;
175 directive.Append (line.Substring (idxStart));
181 int idx = line.IndexOf ("%>");
183 directive.Append (line.Substring (0, idx + 2));
185 content.Append (line.Substring (idx + 2) + "\n");
187 directiveFound = true;
189 directive.Append (line);
194 if (directiveFound) {
195 ParseDirective (directive.ToString ());
196 directiveFound = false;
198 cachedType = CachingCompiler.GetTypeFromCache (physPath);
199 if (cachedType != null)
206 content.Append (line + "\n");
212 throw new ParseException (null, "No @" + DefaultDirectiveName +
215 if (cachedType == null)
216 this.program = content.ToString ();
219 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
221 if (tagtype != System.Web.Compilation.TagType.Directive)
222 throw new ParseException (location, "Unexpected tag");
224 if (tagid == null || tagid.Length == 0 || String.Compare (tagid, DefaultDirectiveName, true) == 0) {
225 AddDefaultDirective (location, attributes);
226 } else if (String.Compare (tagid, "Assembly", true) == 0) {
227 AddAssemblyDirective (location, attributes);
229 throw new ParseException (location, "Unexpected directive: " + tagid);
233 void TextParsed (ILocation location, string text)
235 if (text.Trim () != "")
236 throw new ParseException (location, "Text not allowed here");
239 void ParseError (ILocation location, string message)
241 throw new ParseException (location, message);
244 static string GetAndRemove (Hashtable table, string key)
246 string o = table [key] as string;
251 void ParseDirective (string line)
255 using (StringReader input = new StringReader (line)) {
256 parser = new AspParser (physPath, input);
259 parser.Error += new ParseErrorHandler (ParseError);
260 parser.TagParsed += new TagParsedHandler (TagParsed);
261 parser.TextParsed += new TextParsedHandler (TextParsed);
266 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
269 CompilationSection compConfig;
271 CompilationConfiguration compConfig;
273 compConfig = CompilationConfig;
276 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
279 Hashtable attributes = attrs.GetDictionary (null);
280 className = GetAndRemove (attributes, "class");
281 if (className == null)
282 throw new ParseException (null, "No Class attribute found.");
284 string d = GetAndRemove (attributes, "debug");
286 debug = (String.Compare (d, "true", true) == 0);
287 if (debug == false && String.Compare (d, "false", true) != 0)
288 throw new ParseException (null, "Invalid value for Debug attribute");
290 debug = compConfig.Debug;
292 language = GetAndRemove (attributes, "language");
293 if (language == null)
294 language = compConfig.DefaultLanguage;
296 GetAndRemove (attributes, "codebehind");
297 if (attributes.Count > 0)
298 throw new ParseException (location, "Unrecognized attribute in " +
299 DefaultDirectiveName + " directive");
302 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
304 Hashtable tbl = attrs.GetDictionary (null);
305 string name = GetAndRemove (tbl, "Name");
306 string src = GetAndRemove (tbl, "Src");
307 if (name == null && src == null)
308 throw new ParseException (location, "You gotta specify Src or Name");
310 if (name != null && src != null)
311 throw new ParseException (location, "Src and Name cannot be used together");
314 AddAssemblyByName (name, location);
316 GetAssemblyFromSource (src, location);
320 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
323 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
325 if (assembly == null)
326 throw new ArgumentNullException ("assembly");
329 anames = new Hashtable ();
331 string name = assembly.GetName ().Name;
332 string loc = assembly.Location;
334 if (!assemblies.Contains (loc)) {
335 assemblies.Add (loc);
339 anames [loc] = assembly;
341 if (!assemblies.Contains (name)) {
342 assemblies.Add (name);
345 anames [name] = assembly;
349 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
352 anames = new Hashtable ();
354 if (anames.Contains (name)) {
355 object o = anames [name];
362 Assembly assembly = LoadAssemblyFromBin (name);
363 if (assembly != null) {
364 AddAssembly (assembly, true);
370 assembly = Assembly.LoadWithPartialName (name);
371 } catch (Exception e) {
376 if (assembly == null)
377 throw new ParseException (location, String.Format ("Assembly '{0}' not found", name), ex);
379 AddAssembly (assembly, true);
383 void AddAssembliesInBin ()
385 foreach (string s in HttpApplication.BinDirectoryAssemblies) {
387 Assembly assembly = Assembly.LoadFrom (s);
388 AddAssembly (assembly, true);
389 } catch (Exception e) {
390 throw new Exception ("Error while loading " + s, e);
395 Assembly LoadAssemblyFromBin (string name)
397 Assembly assembly = null;
398 foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
399 string fn = Path.GetFileName (dll);
400 fn = Path.ChangeExtension (fn, null);
404 assembly = Assembly.LoadFrom (dll);
411 Assembly GetAssemblyFromSource (string vpath, ILocation location)
413 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
414 string realPath = context.Request.MapPath (vpath);
415 if (!File.Exists (realPath))
416 throw new ParseException (location, "File " + vpath + " not found");
418 AddDependency (vpath);
420 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
421 if (result.NativeCompilerReturnValue != 0) {
422 using (StreamReader sr = new StreamReader (realPath)) {
423 throw new CompilationException (realPath, result.Errors, sr.ReadToEnd ());
427 AddAssembly (result.CompiledAssembly, true);
428 return result.CompiledAssembly;
431 internal Type GetTypeFromBin (string tname)
433 if (tname == null || tname.Length == 0)
434 throw new ArgumentNullException ("tname");
439 int comma = tname.IndexOf (',');
442 typeName = tname.Substring (0, comma).Trim ();
443 assemblyName = tname.Substring (comma + 1).Trim ();
450 Assembly assembly = null;
451 if (assemblyName != null) {
452 assembly = Assembly.Load (assemblyName);
453 if (assembly != null)
454 type = assembly.GetType (typeName, false);
460 IList toplevelAssemblies = BuildManager.TopLevelAssemblies;
461 if (toplevelAssemblies != null && toplevelAssemblies.Count > 0) {
462 foreach (Assembly asm in toplevelAssemblies) {
463 type = asm.GetType (typeName, false);
466 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
473 foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
474 assembly = Assembly.LoadFrom (dll);
475 type = assembly.GetType (typeName, false);
478 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
486 throw new HttpException (String.Format ("Type {0} not found.", typeName));
491 internal virtual void AddDependency (string filename)
493 if (dependencies == null)
494 dependencies = new ArrayList ();
496 if (!dependencies.Contains (filename))
497 dependencies.Add (filename);
501 protected abstract string DefaultDirectiveName { get; }
503 internal HttpContext Context {
504 get { return context; }
507 internal string VirtualPath {
508 get { return vPath; }
511 internal string PhysicalPath {
512 get { return physPath; }
515 internal string ClassName {
516 get { return className; }
519 internal bool Debug {
520 get { return debug; }
523 internal string Language {
524 get { return language; }
527 internal string Program {
536 internal ArrayList Assemblies {
538 if (appAssemblyIndex != -1) {
539 object o = assemblies [appAssemblyIndex];
540 assemblies.RemoveAt (appAssemblyIndex);
542 appAssemblyIndex = -1;
549 internal ArrayList Dependencies {
550 get { return dependencies; }
553 internal string BaseDir {
556 baseDir = context.Request.MapPath (BaseVirtualDir);
562 internal virtual string BaseVirtualDir {
564 if (baseVDir == null)
565 baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
572 CompilationSection CompilationConfig {
574 return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
578 internal TextReader Reader {
579 get { return reader; }
580 set { reader = value; }
583 internal CompilationConfiguration CompilationConfig {
585 if (compilationConfig == null)
586 compilationConfig = CompilationConfiguration.GetInstance (context);
588 return compilationConfig;