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
57 ArrayList dependencies;
59 string privateBinPath;
62 CompilationConfiguration compilationConfig;
63 int appAssemblyIndex = -1;
66 protected SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath)
68 cachedType = CachingCompiler.GetTypeFromCache (physicalPath);
69 if (cachedType != null)
70 return; // We don't need anything else.
72 this.context = context;
73 this.vPath = virtualPath;
74 this.physPath = physicalPath;
75 AddDependency (physicalPath);
77 assemblies = new ArrayList ();
78 string location = Context.ApplicationInstance.AssemblyLocation;
79 if (location != typeof (TemplateParser).Assembly.Location)
80 appAssemblyIndex = assemblies.Add (location);
82 assemblies.AddRange (CompilationConfig.Assemblies);
83 if (CompilationConfig.AssembliesInBin)
84 AddAssembliesInBin ();
86 language = CompilationConfig.DefaultLanguage;
88 GetDirectivesAndContent ();
91 protected Type GetCompiledTypeFromCache ()
96 void GetDirectivesAndContent ()
98 StreamReader reader = new StreamReader (File.OpenRead (physPath));
100 bool directiveFound = false;
101 StringBuilder content = new StringBuilder ();
103 while ((line = reader.ReadLine ()) != null && cachedType == null) {
104 string trimmed = line.Trim ();
105 if (!directiveFound && trimmed == String.Empty)
108 if (trimmed.StartsWith ("<")) {
109 ParseDirective (trimmed);
110 directiveFound = true;
112 cachedType = CachingCompiler.GetTypeFromCache (physPath);
113 if (cachedType != null)
120 content.Append (line + "\n");
121 content.Append (reader.ReadToEnd ());
126 throw new ParseException (null, "No @" + DefaultDirectiveName +
129 if (cachedType == null)
130 this.program = content.ToString ();
133 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
135 if (tagtype != System.Web.Compilation.TagType.Directive)
136 throw new ParseException (location, "Unexpected tag");
138 if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
139 AddDefaultDirective (location, attributes);
140 } else if (String.Compare (tagid, "Assembly", true) == 0) {
141 AddAssemblyDirective (location, attributes);
143 throw new ParseException (location, "Unexpected directive: " + tagid);
147 void TextParsed (ILocation location, string text)
149 if (text.Trim () != "")
150 throw new ParseException (location, "Text not allowed here");
153 void ParseError (ILocation location, string message)
155 throw new ParseException (location, message);
158 static string GetAndRemove (Hashtable table, string key)
160 string o = table [key] as string;
165 void ParseDirective (string line)
167 AspParser parser = new AspParser (physPath, new StringReader (line));
168 parser.Error += new ParseErrorHandler (ParseError);
169 parser.TagParsed += new TagParsedHandler (TagParsed);
170 parser.TextParsed += new TextParsedHandler (TextParsed);
175 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
178 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
181 Hashtable attributes = attrs.GetDictionary (null);
182 className = GetAndRemove (attributes, "class");
183 if (className == null)
184 throw new ParseException (null, "No Class attribute found.");
186 string d = GetAndRemove (attributes, "debug");
188 debug = (String.Compare (d, "true", true) == 0);
189 if (debug == false && String.Compare (d, "false", true) != 0)
190 throw new ParseException (null, "Invalid value for Debug attribute");
193 language = GetAndRemove (attributes, "language");
194 if (language == null)
195 language = CompilationConfig.DefaultLanguage;
197 codeBehind = GetAndRemove (attributes, "codebehind");
198 if (attributes.Count > 0)
199 throw new ParseException (location, "Unrecognized attribute in " +
200 DefaultDirectiveName + " directive");
203 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
205 Hashtable tbl = attrs.GetDictionary (null);
206 string name = GetAndRemove (tbl, "Name");
207 string src = GetAndRemove (tbl, "Src");
208 if (name == null && src == null)
209 throw new ParseException (location, "You gotta specify Src or Name");
211 if (name != null && src != null)
212 throw new ParseException (location, "Src and Name cannot be used together");
215 AddAssemblyByName (name, location);
217 GetAssemblyFromSource (src, location);
221 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
224 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
227 anames = new Hashtable ();
229 string name = assembly.GetName ().Name;
230 string loc = assembly.Location;
232 if (!assemblies.Contains (loc)) {
233 assemblies.Add (loc);
237 anames [loc] = assembly;
239 if (!assemblies.Contains (name)) {
240 assemblies.Add (name);
243 anames [name] = assembly;
247 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
250 anames = new Hashtable ();
252 if (anames.Contains (name)) {
253 object o = anames [name];
260 Assembly assembly = LoadAssemblyFromBin (name);
261 if (assembly != null) {
262 AddAssembly (assembly, true);
267 assembly = Assembly.LoadWithPartialName (name);
268 } catch (Exception e) {
269 throw new ParseException (location, "Assembly " + name + " not found", e);
272 AddAssembly (assembly, true);
276 void AddAssembliesInBin ()
278 if (!Directory.Exists (PrivateBinPath))
281 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
282 foreach (string dll in binDlls) {
284 Assembly assembly = Assembly.LoadFrom (dll);
285 AddAssembly (assembly, true);
286 } catch (Exception e) {
287 throw new Exception ("Error while loading " + dll, e);
292 Assembly LoadAssemblyFromBin (string name)
295 if (!Directory.Exists (PrivateBinPath))
298 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
299 foreach (string dll in binDlls) {
300 string fn = Path.GetFileName (dll);
301 fn = Path.ChangeExtension (fn, null);
305 assembly = Assembly.LoadFrom (dll);
312 Assembly GetAssemblyFromSource (string vpath, ILocation location)
314 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
315 string realPath = context.Request.MapPath (vpath);
316 if (!File.Exists (realPath))
317 throw new ParseException (location, "File " + vpath + " not found");
319 AddDependency (realPath);
321 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
322 if (result.NativeCompilerReturnValue != 0) {
323 StreamReader reader = new StreamReader (realPath);
324 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
327 AddAssembly (result.CompiledAssembly, true);
328 return result.CompiledAssembly;
331 internal Type GetTypeFromBin (string typeName)
333 if (!Directory.Exists (PrivateBinPath))
334 throw new HttpException (String.Format ("Type {0} not found.", typeName));
336 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
338 foreach (string dll in binDlls) {
339 Assembly assembly = Assembly.LoadFrom (dll);
340 Type type = assembly.GetType (typeName, false);
343 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
350 throw new HttpException (String.Format ("Type {0} not found.", typeName));
355 internal virtual void AddDependency (string filename)
357 if (dependencies == null)
358 dependencies = new ArrayList ();
360 if (!dependencies.Contains (filename))
361 dependencies.Add (filename);
365 protected abstract string DefaultDirectiveName { get; }
367 internal HttpContext Context {
368 get { return context; }
371 internal string VirtualPath {
372 get { return vPath; }
375 internal string PhysicalPath {
376 get { return physPath; }
379 internal string ClassName {
380 get { return className; }
383 internal string CodeBehind {
384 get { return codeBehind; }
387 internal bool Debug {
388 get { return debug; }
391 internal string Language {
392 get { return language; }
395 internal string Program {
396 get { return program; }
399 internal ArrayList Assemblies {
401 if (appAssemblyIndex != -1) {
402 object o = assemblies [appAssemblyIndex];
403 assemblies.RemoveAt (appAssemblyIndex);
405 appAssemblyIndex = -1;
412 internal ArrayList Dependencies {
413 get { return dependencies; }
416 internal string PrivateBinPath {
418 if (privateBinPath != null)
419 return privateBinPath;
421 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
422 privateBinPath = setup.PrivateBinPath;
424 if (!Path.IsPathRooted (privateBinPath)) {
425 string appbase = setup.ApplicationBase;
426 if (appbase.StartsWith ("file://")) {
427 appbase = appbase.Substring (7);
428 if (Path.DirectorySeparatorChar != '/')
429 appbase = appbase.Replace ('/', Path.DirectorySeparatorChar);
431 privateBinPath = Path.Combine (appbase, privateBinPath);
434 return privateBinPath;
438 internal string BaseDir {
441 baseDir = context.Request.MapPath (BaseVirtualDir);
447 internal virtual string BaseVirtualDir {
449 if (baseVDir == null)
450 baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
456 internal CompilationConfiguration CompilationConfig {
458 if (compilationConfig == null)
459 compilationConfig = CompilationConfiguration.GetInstance (context);
461 return compilationConfig;