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;
61 #if !CONFIGURATION_2_0
62 CompilationConfiguration compilationConfig;
64 int appAssemblyIndex = -1;
67 protected SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath)
69 cachedType = CachingCompiler.GetTypeFromCache (physicalPath);
70 if (cachedType != null)
71 return; // We don't need anything else.
73 this.context = context;
74 this.vPath = virtualPath;
75 this.physPath = physicalPath;
76 AddDependency (physicalPath);
78 assemblies = new ArrayList ();
79 string location = Context.ApplicationInstance.AssemblyLocation;
80 if (location != typeof (TemplateParser).Assembly.Location)
81 appAssemblyIndex = assemblies.Add (location);
84 bool addAssembliesInBin = false;
85 foreach (AssemblyInfo info in CompilationConfig.Assemblies) {
86 if (info.Assembly == "*")
87 addAssembliesInBin = true;
89 assemblies.Add (info.Assembly);
91 if (addAssembliesInBin)
92 AddAssembliesInBin ();
94 assemblies.AddRange (CompilationConfig.Assemblies);
95 if (CompilationConfig.AssembliesInBin)
96 AddAssembliesInBin ();
99 #if !CONFIGURATION_2_0
102 language = CompilationConfig.DefaultLanguage;
104 GetDirectivesAndContent ();
107 protected Type GetCompiledTypeFromCache ()
112 void GetDirectivesAndContent ()
114 StreamReader reader = new StreamReader (File.OpenRead (physPath));
116 bool directiveFound = false;
117 StringBuilder content = new StringBuilder ();
119 while ((line = reader.ReadLine ()) != null && cachedType == null) {
120 string trimmed = line.Trim ();
121 if (!directiveFound && trimmed == String.Empty)
124 if (trimmed.StartsWith ("<")) {
125 ParseDirective (trimmed);
126 directiveFound = true;
128 cachedType = CachingCompiler.GetTypeFromCache (physPath);
129 if (cachedType != null)
136 content.Append (line + "\n");
137 content.Append (reader.ReadToEnd ());
142 throw new ParseException (null, "No @" + DefaultDirectiveName +
145 if (cachedType == null)
146 this.program = content.ToString ();
149 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
151 if (tagtype != System.Web.Compilation.TagType.Directive)
152 throw new ParseException (location, "Unexpected tag");
154 if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
155 AddDefaultDirective (location, attributes);
156 } else if (String.Compare (tagid, "Assembly", true) == 0) {
157 AddAssemblyDirective (location, attributes);
159 throw new ParseException (location, "Unexpected directive: " + tagid);
163 void TextParsed (ILocation location, string text)
165 if (text.Trim () != "")
166 throw new ParseException (location, "Text not allowed here");
169 void ParseError (ILocation location, string message)
171 throw new ParseException (location, message);
174 static string GetAndRemove (Hashtable table, string key)
176 string o = table [key] as string;
181 void ParseDirective (string line)
183 AspParser parser = new AspParser (physPath, new StringReader (line));
184 parser.Error += new ParseErrorHandler (ParseError);
185 parser.TagParsed += new TagParsedHandler (TagParsed);
186 parser.TextParsed += new TextParsedHandler (TextParsed);
191 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
194 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
197 Hashtable attributes = attrs.GetDictionary (null);
198 className = GetAndRemove (attributes, "class");
199 if (className == null)
200 throw new ParseException (null, "No Class attribute found.");
202 string d = GetAndRemove (attributes, "debug");
204 debug = (String.Compare (d, "true", true) == 0);
205 if (debug == false && String.Compare (d, "false", true) != 0)
206 throw new ParseException (null, "Invalid value for Debug attribute");
209 language = GetAndRemove (attributes, "language");
210 if (language == null)
211 language = CompilationConfig.DefaultLanguage;
213 GetAndRemove (attributes, "codebehind");
214 if (attributes.Count > 0)
215 throw new ParseException (location, "Unrecognized attribute in " +
216 DefaultDirectiveName + " directive");
219 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
221 Hashtable tbl = attrs.GetDictionary (null);
222 string name = GetAndRemove (tbl, "Name");
223 string src = GetAndRemove (tbl, "Src");
224 if (name == null && src == null)
225 throw new ParseException (location, "You gotta specify Src or Name");
227 if (name != null && src != null)
228 throw new ParseException (location, "Src and Name cannot be used together");
231 AddAssemblyByName (name, location);
233 GetAssemblyFromSource (src, location);
237 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
240 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
243 anames = new Hashtable ();
245 string name = assembly.GetName ().Name;
246 string loc = assembly.Location;
248 if (!assemblies.Contains (loc)) {
249 assemblies.Add (loc);
253 anames [loc] = assembly;
255 if (!assemblies.Contains (name)) {
256 assemblies.Add (name);
259 anames [name] = assembly;
263 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
266 anames = new Hashtable ();
268 if (anames.Contains (name)) {
269 object o = anames [name];
276 Assembly assembly = LoadAssemblyFromBin (name);
277 if (assembly != null) {
278 AddAssembly (assembly, true);
283 assembly = Assembly.LoadWithPartialName (name);
284 } catch (Exception e) {
285 throw new ParseException (location, "Assembly " + name + " not found", e);
288 AddAssembly (assembly, true);
292 void AddAssembliesInBin ()
294 if (!Directory.Exists (PrivateBinPath))
297 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
298 foreach (string dll in binDlls) {
300 Assembly assembly = Assembly.LoadFrom (dll);
301 AddAssembly (assembly, true);
302 } catch (Exception e) {
303 throw new Exception ("Error while loading " + dll, e);
308 Assembly LoadAssemblyFromBin (string name)
311 if (!Directory.Exists (PrivateBinPath))
314 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
315 foreach (string dll in binDlls) {
316 string fn = Path.GetFileName (dll);
317 fn = Path.ChangeExtension (fn, null);
321 assembly = Assembly.LoadFrom (dll);
328 Assembly GetAssemblyFromSource (string vpath, ILocation location)
330 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
331 string realPath = context.Request.MapPath (vpath);
332 if (!File.Exists (realPath))
333 throw new ParseException (location, "File " + vpath + " not found");
335 AddDependency (realPath);
337 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
338 if (result.NativeCompilerReturnValue != 0) {
339 StreamReader reader = new StreamReader (realPath);
340 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
343 AddAssembly (result.CompiledAssembly, true);
344 return result.CompiledAssembly;
347 internal Type GetTypeFromBin (string typeName)
349 if (!Directory.Exists (PrivateBinPath))
350 throw new HttpException (String.Format ("Type {0} not found.", typeName));
352 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
354 foreach (string dll in binDlls) {
355 Assembly assembly = Assembly.LoadFrom (dll);
356 Type type = assembly.GetType (typeName, false);
359 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
366 throw new HttpException (String.Format ("Type {0} not found.", typeName));
371 internal virtual void AddDependency (string filename)
373 if (dependencies == null)
374 dependencies = new ArrayList ();
376 if (!dependencies.Contains (filename))
377 dependencies.Add (filename);
381 protected abstract string DefaultDirectiveName { get; }
383 internal HttpContext Context {
384 get { return context; }
387 internal string VirtualPath {
388 get { return vPath; }
391 internal string PhysicalPath {
392 get { return physPath; }
395 internal string ClassName {
396 get { return className; }
399 internal bool Debug {
400 get { return debug; }
403 internal string Language {
404 get { return language; }
407 internal string Program {
408 get { return program; }
411 internal ArrayList Assemblies {
413 if (appAssemblyIndex != -1) {
414 object o = assemblies [appAssemblyIndex];
415 assemblies.RemoveAt (appAssemblyIndex);
417 appAssemblyIndex = -1;
424 internal ArrayList Dependencies {
425 get { return dependencies; }
428 internal string PrivateBinPath {
430 if (privateBinPath != null)
431 return privateBinPath;
433 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
434 privateBinPath = setup.PrivateBinPath;
436 if (!Path.IsPathRooted (privateBinPath)) {
437 string appbase = setup.ApplicationBase;
438 if (appbase.StartsWith ("file://")) {
439 appbase = appbase.Substring (7);
440 if (Path.DirectorySeparatorChar != '/')
441 appbase = appbase.Replace ('/', Path.DirectorySeparatorChar);
443 privateBinPath = Path.Combine (appbase, privateBinPath);
446 return privateBinPath;
450 internal string BaseDir {
453 baseDir = context.Request.MapPath (BaseVirtualDir);
459 internal virtual string BaseVirtualDir {
461 if (baseVDir == null)
462 baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
468 #if CONFIGURATION_2_0
469 CompilationSection CompilationConfig {
471 return (CompilationSection)WebConfigurationManager.GetWebApplicationSection ("system.web/compilation");
475 internal CompilationConfiguration CompilationConfig {
477 if (compilationConfig == null)
478 compilationConfig = CompilationConfiguration.GetInstance (context);
480 return compilationConfig;