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;
61 CompilationConfiguration compilationConfig;
68 int appAssemblyIndex = -1;
71 protected SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath)
72 : this (context, virtualPath, physicalPath, null)
75 internal SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath, TextReader reader)
80 cachedType = CachingCompiler.GetTypeFromCache (physicalPath);
81 if (cachedType != null)
82 return; // We don't need anything else.
84 // context is obsolete in 2.0+ - MSDN recommends passing null, so we need to
85 // take that into account
87 this.context = context;
89 this.context = HttpContext.Current;
91 this.vPath = virtualPath;
92 AddDependency (virtualPath);
94 // physicalPath is obsolete in 2.0+ - same note what for context applies here
95 if (physicalPath != null && physicalPath.Length > 0)
96 this.physPath = physicalPath;
98 HttpRequest req = this.context != null ? context.Request : null;
100 this.physPath = req.MapPath (virtualPath);
103 assemblies = new ArrayList ();
104 string location = Context.ApplicationInstance.AssemblyLocation;
105 if (location != typeof (TemplateParser).Assembly.Location)
106 appAssemblyIndex = assemblies.Add (location);
109 bool addAssembliesInBin = false;
110 foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
111 if (info.Assembly == "*")
112 addAssembliesInBin = true;
114 AddAssemblyByName (info.Assembly, null);
116 if (addAssembliesInBin)
117 AddAssembliesInBin ();
119 assemblies.AddRange (CompilationConfig.Assemblies);
120 if (CompilationConfig.AssembliesInBin)
121 AddAssembliesInBin ();
124 language = CompilationConfig.DefaultLanguage;
126 GetDirectivesAndContent ();
129 protected Type GetCompiledTypeFromCache ()
134 void GetDirectivesAndContent ()
137 bool directiveFound = false;
138 bool inDirective = false;
139 StringBuilder directive = null;
140 StringBuilder content = new StringBuilder ();
141 int idxStart, idxEnd, length;
146 sr = reader as StreamReader;
149 sr = new StreamReader (File.OpenRead (physPath), WebEncoding.FileEncoding);
152 while ((line = sr.ReadLine ()) != null && cachedType == null) {
153 length = line.Length;
155 content.Append ("\n");
159 idxStart = line.IndexOf ("<%");
161 idxEnd = line.IndexOf ("%>");
163 content.Append (line.Substring (0, idxStart));
165 if (directive == null)
166 directive = new StringBuilder ();
168 directive.Length = 0;
171 directiveFound = true;
173 directive.Append (line.Substring (idxStart, idxEnd - idxStart + 2));
174 if (idxEnd < length - 2)
175 content.Append (line.Substring (idxEnd + 2, length - idxEnd - 2));
178 directiveFound = false;
179 directive.Append (line.Substring (idxStart));
185 int idx = line.IndexOf ("%>");
187 directive.Append (line.Substring (0, idx + 2));
189 content.Append (line.Substring (idx + 2) + "\n");
191 directiveFound = true;
193 directive.Append (line);
198 if (directiveFound) {
199 ParseDirective (directive.ToString ());
200 directiveFound = false;
202 cachedType = CachingCompiler.GetTypeFromCache (physPath);
203 if (cachedType != null)
210 content.Append (line + "\n");
216 throw new ParseException (null, "No @" + DefaultDirectiveName +
219 if (cachedType == null)
220 this.program = content.ToString ();
223 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
225 if (tagtype != System.Web.Compilation.TagType.Directive)
226 throw new ParseException (location, "Unexpected tag");
228 if (tagid == null || tagid.Length == 0 || String.Compare (tagid, DefaultDirectiveName, true) == 0) {
229 AddDefaultDirective (location, attributes);
230 } else if (String.Compare (tagid, "Assembly", true) == 0) {
231 AddAssemblyDirective (location, attributes);
233 throw new ParseException (location, "Unexpected directive: " + tagid);
237 void TextParsed (ILocation location, string text)
239 if (text.Trim () != "")
240 throw new ParseException (location, "Text not allowed here");
243 void ParseError (ILocation location, string message)
245 throw new ParseException (location, message);
248 static string GetAndRemove (Hashtable table, string key)
250 string o = table [key] as string;
255 void ParseDirective (string line)
259 using (StringReader input = new StringReader (line)) {
260 parser = new AspParser (physPath, input);
263 parser.Error += new ParseErrorHandler (ParseError);
264 parser.TagParsed += new TagParsedHandler (TagParsed);
265 parser.TextParsed += new TextParsedHandler (TextParsed);
270 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
273 CompilationSection compConfig;
275 CompilationConfiguration compConfig;
277 compConfig = CompilationConfig;
280 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
283 Hashtable attributes = attrs.GetDictionary (null);
284 className = GetAndRemove (attributes, "class");
285 if (className == null)
286 throw new ParseException (null, "No Class attribute found.");
288 string d = GetAndRemove (attributes, "debug");
290 debug = (String.Compare (d, "true", true) == 0);
291 if (debug == false && String.Compare (d, "false", true) != 0)
292 throw new ParseException (null, "Invalid value for Debug attribute");
294 debug = compConfig.Debug;
296 language = GetAndRemove (attributes, "language");
297 if (language == null)
298 language = compConfig.DefaultLanguage;
300 GetAndRemove (attributes, "codebehind");
301 if (attributes.Count > 0)
302 throw new ParseException (location, "Unrecognized attribute in " +
303 DefaultDirectiveName + " directive");
306 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
308 Hashtable tbl = attrs.GetDictionary (null);
309 string name = GetAndRemove (tbl, "Name");
310 string src = GetAndRemove (tbl, "Src");
311 if (name == null && src == null)
312 throw new ParseException (location, "You gotta specify Src or Name");
314 if (name != null && src != null)
315 throw new ParseException (location, "Src and Name cannot be used together");
318 AddAssemblyByName (name, location);
320 GetAssemblyFromSource (src, location);
324 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
327 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
329 if (assembly == null)
330 throw new ArgumentNullException ("assembly");
333 anames = new Hashtable ();
335 string name = assembly.GetName ().Name;
336 string loc = assembly.Location;
338 if (!assemblies.Contains (loc)) {
339 assemblies.Add (loc);
343 anames [loc] = assembly;
345 if (!assemblies.Contains (name)) {
346 assemblies.Add (name);
349 anames [name] = assembly;
353 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
356 anames = new Hashtable ();
358 if (anames.Contains (name)) {
359 object o = anames [name];
366 Assembly assembly = LoadAssemblyFromBin (name);
367 if (assembly != null) {
368 AddAssembly (assembly, true);
374 assembly = Assembly.LoadWithPartialName (name);
375 } catch (Exception e) {
380 if (assembly == null)
381 throw new ParseException (location, String.Format ("Assembly '{0}' not found", name), ex);
383 AddAssembly (assembly, true);
387 void AddAssembliesInBin ()
389 foreach (string s in HttpApplication.BinDirectoryAssemblies) {
391 Assembly assembly = Assembly.LoadFrom (s);
392 AddAssembly (assembly, true);
393 } catch (Exception e) {
394 throw new Exception ("Error while loading " + s, e);
399 Assembly LoadAssemblyFromBin (string name)
401 Assembly assembly = null;
402 foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
403 string fn = Path.GetFileName (dll);
404 fn = Path.ChangeExtension (fn, null);
408 assembly = Assembly.LoadFrom (dll);
415 Assembly GetAssemblyFromSource (string vpath, ILocation location)
417 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
418 string realPath = context.Request.MapPath (vpath);
419 if (!File.Exists (realPath))
420 throw new ParseException (location, "File " + vpath + " not found");
422 AddDependency (vpath);
424 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
425 if (result.NativeCompilerReturnValue != 0) {
426 using (StreamReader sr = new StreamReader (realPath)) {
427 throw new CompilationException (realPath, result.Errors, sr.ReadToEnd ());
431 AddAssembly (result.CompiledAssembly, true);
432 return result.CompiledAssembly;
435 internal Type GetTypeFromBin (string tname)
437 if (tname == null || tname.Length == 0)
438 throw new ArgumentNullException ("tname");
443 int comma = tname.IndexOf (',');
446 typeName = tname.Substring (0, comma).Trim ();
447 assemblyName = tname.Substring (comma + 1).Trim ();
454 Assembly assembly = null;
455 if (assemblyName != null) {
456 assembly = Assembly.Load (assemblyName);
457 if (assembly != null)
458 type = assembly.GetType (typeName, false);
464 IList toplevelAssemblies = BuildManager.TopLevelAssemblies;
465 if (toplevelAssemblies != null && toplevelAssemblies.Count > 0) {
466 foreach (Assembly asm in toplevelAssemblies) {
467 type = asm.GetType (typeName, false);
470 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
477 foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
478 assembly = Assembly.LoadFrom (dll);
479 type = assembly.GetType (typeName, false);
482 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
490 throw new HttpException (String.Format ("Type {0} not found.", typeName));
495 internal virtual void AddDependency (string filename)
497 if (dependencies == null)
498 dependencies = new ArrayList ();
500 if (!dependencies.Contains (filename))
501 dependencies.Add (filename);
505 protected abstract string DefaultDirectiveName { get; }
507 internal HttpContext Context {
508 get { return context; }
511 internal string VirtualPath {
512 get { return vPath; }
515 internal string PhysicalPath {
516 get { return physPath; }
519 internal string ClassName {
520 get { return className; }
523 internal bool Debug {
524 get { return debug; }
527 internal string Language {
528 get { return language; }
531 internal string Program {
540 internal ArrayList Assemblies {
542 if (appAssemblyIndex != -1) {
543 object o = assemblies [appAssemblyIndex];
544 assemblies.RemoveAt (appAssemblyIndex);
546 appAssemblyIndex = -1;
553 internal ArrayList Dependencies {
554 get { return dependencies; }
557 internal string BaseDir {
560 baseDir = context.Request.MapPath (BaseVirtualDir);
566 internal virtual string BaseVirtualDir {
568 if (baseVDir == null)
569 baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
576 CompilationSection CompilationConfig {
578 return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
582 internal TextReader Reader {
583 get { return reader; }
584 set { reader = value; }
587 internal CompilationConfiguration CompilationConfig {
589 if (compilationConfig == null)
590 compilationConfig = CompilationConfiguration.GetInstance (context);
592 return compilationConfig;