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 bool inDirective = false;
123 StringBuilder directive = null;
124 StringBuilder content = new StringBuilder ();
125 int idxStart, idxEnd, length;
127 using (StreamReader reader = new StreamReader (File.OpenRead (physPath))) {
128 while ((line = reader.ReadLine ()) != null && cachedType == null) {
129 length = line.Length;
131 content.Append ("\n");
135 idxStart = line.IndexOf ("<%");
137 idxEnd = line.IndexOf ("%>");
139 content.Append (line.Substring (0, idxStart));
141 if (directive == null)
142 directive = new StringBuilder ();
144 directive.Length = 0;
147 directiveFound = true;
149 directive.Append (line.Substring (idxStart, idxEnd - idxStart + 2));
150 if (idxEnd < length - 2)
151 content.Append (line.Substring (idxEnd + 2, length - idxEnd - 2));
154 directiveFound = false;
155 directive.Append (line.Substring (idxStart));
161 int idx = line.IndexOf ("%>");
163 directive.Append (line.Substring (0, idx + 2));
165 content.Append (line.Substring (idx + 2) + "\n");
167 directiveFound = true;
169 directive.Append (line);
174 if (directiveFound) {
175 ParseDirective (directive.ToString ());
176 directiveFound = false;
178 cachedType = CachingCompiler.GetTypeFromCache (physPath);
179 if (cachedType != null)
186 content.Append (line + "\n");
192 throw new ParseException (null, "No @" + DefaultDirectiveName +
195 if (cachedType == null)
196 this.program = content.ToString ();
199 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
201 if (tagtype != System.Web.Compilation.TagType.Directive)
202 throw new ParseException (location, "Unexpected tag");
204 if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
205 AddDefaultDirective (location, attributes);
206 } else if (String.Compare (tagid, "Assembly", true) == 0) {
207 AddAssemblyDirective (location, attributes);
209 throw new ParseException (location, "Unexpected directive: " + tagid);
213 void TextParsed (ILocation location, string text)
215 if (text.Trim () != "")
216 throw new ParseException (location, "Text not allowed here");
219 void ParseError (ILocation location, string message)
221 throw new ParseException (location, message);
224 static string GetAndRemove (Hashtable table, string key)
226 string o = table [key] as string;
231 void ParseDirective (string line)
233 AspParser parser = new AspParser (physPath, new StringReader (line));
234 parser.Error += new ParseErrorHandler (ParseError);
235 parser.TagParsed += new TagParsedHandler (TagParsed);
236 parser.TextParsed += new TextParsedHandler (TextParsed);
241 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
244 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
247 Hashtable attributes = attrs.GetDictionary (null);
248 className = GetAndRemove (attributes, "class");
249 if (className == null)
250 throw new ParseException (null, "No Class attribute found.");
252 string d = GetAndRemove (attributes, "debug");
254 debug = (String.Compare (d, "true", true) == 0);
255 if (debug == false && String.Compare (d, "false", true) != 0)
256 throw new ParseException (null, "Invalid value for Debug attribute");
259 language = GetAndRemove (attributes, "language");
260 if (language == null)
261 language = CompilationConfig.DefaultLanguage;
263 GetAndRemove (attributes, "codebehind");
264 if (attributes.Count > 0)
265 throw new ParseException (location, "Unrecognized attribute in " +
266 DefaultDirectiveName + " directive");
269 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
271 Hashtable tbl = attrs.GetDictionary (null);
272 string name = GetAndRemove (tbl, "Name");
273 string src = GetAndRemove (tbl, "Src");
274 if (name == null && src == null)
275 throw new ParseException (location, "You gotta specify Src or Name");
277 if (name != null && src != null)
278 throw new ParseException (location, "Src and Name cannot be used together");
281 AddAssemblyByName (name, location);
283 GetAssemblyFromSource (src, location);
287 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
290 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
293 anames = new Hashtable ();
295 string name = assembly.GetName ().Name;
296 string loc = assembly.Location;
298 if (!assemblies.Contains (loc)) {
299 assemblies.Add (loc);
303 anames [loc] = assembly;
305 if (!assemblies.Contains (name)) {
306 assemblies.Add (name);
309 anames [name] = assembly;
313 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
316 anames = new Hashtable ();
318 if (anames.Contains (name)) {
319 object o = anames [name];
326 Assembly assembly = LoadAssemblyFromBin (name);
327 if (assembly != null) {
328 AddAssembly (assembly, true);
333 assembly = Assembly.LoadWithPartialName (name);
334 } catch (Exception e) {
335 throw new ParseException (location, "Assembly " + name + " not found", e);
338 AddAssembly (assembly, true);
342 void AddAssembliesInBin ()
344 foreach (string s in HttpApplication.BinDirectoryAssemblies) {
346 Assembly assembly = Assembly.LoadFrom (s);
347 AddAssembly (assembly, true);
348 } catch (Exception e) {
349 throw new Exception ("Error while loading " + s, e);
354 Assembly LoadAssemblyFromBin (string name)
356 Assembly assembly = null;
357 foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
358 string fn = Path.GetFileName (dll);
359 fn = Path.ChangeExtension (fn, null);
363 assembly = Assembly.LoadFrom (dll);
370 Assembly GetAssemblyFromSource (string vpath, ILocation location)
372 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
373 string realPath = context.Request.MapPath (vpath);
374 if (!File.Exists (realPath))
375 throw new ParseException (location, "File " + vpath + " not found");
377 AddDependency (realPath);
379 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
380 if (result.NativeCompilerReturnValue != 0) {
381 StreamReader reader = new StreamReader (realPath);
382 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
385 AddAssembly (result.CompiledAssembly, true);
386 return result.CompiledAssembly;
389 internal Type GetTypeFromBin (string typeName)
394 IList toplevelAssemblies = BuildManager.TopLevelAssemblies;
395 if (toplevelAssemblies != null && toplevelAssemblies.Count > 0) {
396 foreach (Assembly asm in toplevelAssemblies) {
397 Type type = asm.GetType (typeName, false);
400 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
407 foreach (string dll in HttpApplication.BinDirectoryAssemblies) {
408 Assembly assembly = Assembly.LoadFrom (dll);
409 Type type = assembly.GetType (typeName, false);
412 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
420 throw new HttpException (String.Format ("Type {0} not found.", typeName));
425 internal virtual void AddDependency (string filename)
427 if (dependencies == null)
428 dependencies = new ArrayList ();
430 if (!dependencies.Contains (filename))
431 dependencies.Add (filename);
435 protected abstract string DefaultDirectiveName { get; }
437 internal HttpContext Context {
438 get { return context; }
441 internal string VirtualPath {
442 get { return vPath; }
445 internal string PhysicalPath {
446 get { return physPath; }
449 internal string ClassName {
450 get { return className; }
453 internal bool Debug {
454 get { return debug; }
457 internal string Language {
458 get { return language; }
461 internal string Program {
462 get { return program; }
465 internal ArrayList Assemblies {
467 if (appAssemblyIndex != -1) {
468 object o = assemblies [appAssemblyIndex];
469 assemblies.RemoveAt (appAssemblyIndex);
471 appAssemblyIndex = -1;
478 internal ArrayList Dependencies {
479 get { return dependencies; }
482 internal string BaseDir {
485 baseDir = context.Request.MapPath (BaseVirtualDir);
491 internal virtual string BaseVirtualDir {
493 if (baseVDir == null)
494 baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
501 CompilationSection CompilationConfig {
503 return (CompilationSection)WebConfigurationManager.GetSection ("system.web/compilation");
507 internal TextReader Reader {
508 get { return reader; }
509 set { reader = value; }
512 internal CompilationConfiguration CompilationConfig {
514 if (compilationConfig == null)
515 compilationConfig = CompilationConfiguration.GetInstance (context);
517 return compilationConfig;