2 // System.Web.UI.SimpleWebHandlerParser
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (C) 2002,2003 Ximian, Inc (http://www.ximian.com)
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 using System.CodeDom.Compiler;
33 using System.Collections;
35 using System.Reflection;
38 using System.Web.Compilation;
39 using System.Web.Configuration;
40 using System.Web.Util;
42 namespace System.Web.UI
44 public abstract class SimpleWebHandlerParser
56 ArrayList dependencies;
58 string privateBinPath;
61 CompilationConfiguration compilationConfig;
62 int appAssemblyIndex = -1;
65 protected SimpleWebHandlerParser (HttpContext context, string virtualPath, string physicalPath)
67 cachedType = CachingCompiler.GetTypeFromCache (physicalPath);
68 if (cachedType != null)
69 return; // We don't need anything else.
71 this.context = context;
72 this.vPath = virtualPath;
73 this.physPath = physicalPath;
74 AddDependency (physicalPath);
76 assemblies = new ArrayList ();
77 string location = Context.ApplicationInstance.AssemblyLocation;
78 if (location != typeof (TemplateParser).Assembly.Location)
79 appAssemblyIndex = assemblies.Add (location);
81 assemblies.AddRange (CompilationConfig.Assemblies);
82 if (CompilationConfig.AssembliesInBin)
83 AddAssembliesInBin ();
85 language = CompilationConfig.DefaultLanguage;
87 GetDirectivesAndContent ();
90 protected Type GetCompiledTypeFromCache ()
95 void GetDirectivesAndContent ()
97 StreamReader reader = new StreamReader (File.OpenRead (physPath));
99 bool directiveFound = false;
100 StringBuilder content = new StringBuilder ();
102 while ((line = reader.ReadLine ()) != null && cachedType == null) {
103 string trimmed = line.Trim ();
104 if (!directiveFound && trimmed == String.Empty)
107 if (trimmed.StartsWith ("<")) {
108 ParseDirective (trimmed);
109 directiveFound = true;
111 cachedType = CachingCompiler.GetTypeFromCache (physPath);
112 if (cachedType != null)
119 content.Append (line + "\n");
120 content.Append (reader.ReadToEnd ());
125 throw new ParseException (null, "No @" + DefaultDirectiveName +
128 if (cachedType == null)
129 this.program = content.ToString ();
132 void TagParsed (ILocation location, System.Web.Compilation.TagType tagtype, string tagid, TagAttributes attributes)
134 if (tagtype != System.Web.Compilation.TagType.Directive)
135 throw new ParseException (location, "Unexpected tag");
137 if (String.Compare (tagid, DefaultDirectiveName, true) == 0) {
138 AddDefaultDirective (location, attributes);
139 } else if (String.Compare (tagid, "Assembly", true) == 0) {
140 AddAssemblyDirective (location, attributes);
142 throw new ParseException (location, "Unexpected directive: " + tagid);
146 void TextParsed (ILocation location, string text)
148 if (text.Trim () != "")
149 throw new ParseException (location, "Text not allowed here");
152 void ParseError (ILocation location, string message)
154 throw new ParseException (location, message);
157 static string GetAndRemove (Hashtable table, string key)
159 string o = table [key] as string;
164 void ParseDirective (string line)
166 AspParser parser = new AspParser (physPath, new StringReader (line));
167 parser.Error += new ParseErrorHandler (ParseError);
168 parser.TagParsed += new TagParsedHandler (TagParsed);
169 parser.TextParsed += new TextParsedHandler (TextParsed);
174 internal virtual void AddDefaultDirective (ILocation location, TagAttributes attrs)
177 throw new ParseException (location, "duplicate " + DefaultDirectiveName + " directive");
180 Hashtable attributes = attrs.GetDictionary (null);
181 className = GetAndRemove (attributes, "class");
182 if (className == null)
183 throw new ParseException (null, "No Class attribute found.");
185 string d = GetAndRemove (attributes, "debug");
187 debug = (String.Compare (d, "true", true) == 0);
188 if (debug == false && String.Compare (d, "false", true) != 0)
189 throw new ParseException (null, "Invalid value for Debug attribute");
192 language = GetAndRemove (attributes, "language");
193 if (language == null)
194 language = CompilationConfig.DefaultLanguage;
196 codeBehind = GetAndRemove (attributes, "codebehind");
197 if (attributes.Count > 0)
198 throw new ParseException (location, "Unrecognized attribute in " +
199 DefaultDirectiveName + " directive");
202 internal virtual void AddAssemblyDirective (ILocation location, TagAttributes attrs)
204 Hashtable tbl = attrs.GetDictionary (null);
205 string name = GetAndRemove (tbl, "Name");
206 string src = GetAndRemove (tbl, "Src");
207 if (name == null && src == null)
208 throw new ParseException (location, "You gotta specify Src or Name");
210 if (name != null && src != null)
211 throw new ParseException (location, "Src and Name cannot be used together");
214 AddAssemblyByName (name, location);
216 GetAssemblyFromSource (src, location);
220 throw new ParseException (location, "Unrecognized attribute in Assembly directive");
223 internal virtual void AddAssembly (Assembly assembly, bool fullPath)
226 anames = new Hashtable ();
228 string name = assembly.GetName ().Name;
229 string loc = assembly.Location;
231 if (!assemblies.Contains (loc)) {
232 assemblies.Add (loc);
236 anames [loc] = assembly;
238 if (!assemblies.Contains (name)) {
239 assemblies.Add (name);
242 anames [name] = assembly;
246 internal virtual Assembly AddAssemblyByName (string name, ILocation location)
249 anames = new Hashtable ();
251 if (anames.Contains (name)) {
252 object o = anames [name];
259 Assembly assembly = LoadAssemblyFromBin (name);
260 if (assembly != null) {
261 AddAssembly (assembly, true);
266 assembly = Assembly.LoadWithPartialName (name);
267 } catch (Exception e) {
268 throw new ParseException (location, "Assembly " + name + " not found", e);
271 AddAssembly (assembly, true);
275 void AddAssembliesInBin ()
277 if (!Directory.Exists (PrivateBinPath))
280 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
281 foreach (string dll in binDlls) {
283 Assembly assembly = Assembly.LoadFrom (dll);
284 AddAssembly (assembly, true);
285 } catch (Exception e) {
286 throw new Exception ("Error while loading " + dll, e);
291 Assembly LoadAssemblyFromBin (string name)
294 if (!Directory.Exists (PrivateBinPath))
297 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
298 foreach (string dll in binDlls) {
299 string fn = Path.GetFileName (dll);
300 fn = Path.ChangeExtension (fn, null);
304 assembly = Assembly.LoadFrom (dll);
311 Assembly GetAssemblyFromSource (string vpath, ILocation location)
313 vpath = UrlUtils.Combine (BaseVirtualDir, vpath);
314 string realPath = context.Request.MapPath (vpath);
315 if (!File.Exists (realPath))
316 throw new ParseException (location, "File " + vpath + " not found");
318 AddDependency (realPath);
320 CompilerResults result = CachingCompiler.Compile (language, realPath, realPath, assemblies);
321 if (result.NativeCompilerReturnValue != 0) {
322 StreamReader reader = new StreamReader (realPath);
323 throw new CompilationException (realPath, result.Errors, reader.ReadToEnd ());
326 AddAssembly (result.CompiledAssembly, true);
327 return result.CompiledAssembly;
330 internal Type GetTypeFromBin (string typeName)
332 if (!Directory.Exists (PrivateBinPath))
333 throw new HttpException (String.Format ("Type {0} not found.", typeName));
335 string [] binDlls = Directory.GetFiles (PrivateBinPath, "*.dll");
337 foreach (string dll in binDlls) {
338 Assembly assembly = Assembly.LoadFrom (dll);
339 Type type = assembly.GetType (typeName, false);
342 throw new HttpException (String.Format ("Type {0} is not unique.", typeName));
349 throw new HttpException (String.Format ("Type {0} not found.", typeName));
354 internal virtual void AddDependency (string filename)
356 if (dependencies == null)
357 dependencies = new ArrayList ();
359 if (!dependencies.Contains (filename))
360 dependencies.Add (filename);
364 protected abstract string DefaultDirectiveName { get; }
366 internal HttpContext Context {
367 get { return context; }
370 internal string VirtualPath {
371 get { return vPath; }
374 internal string PhysicalPath {
375 get { return physPath; }
378 internal string ClassName {
379 get { return className; }
382 internal string CodeBehind {
383 get { return codeBehind; }
386 internal bool Debug {
387 get { return debug; }
390 internal string Language {
391 get { return language; }
394 internal string Program {
395 get { return program; }
398 internal ArrayList Assemblies {
400 if (appAssemblyIndex != -1) {
401 object o = assemblies [appAssemblyIndex];
402 assemblies.RemoveAt (appAssemblyIndex);
404 appAssemblyIndex = -1;
411 internal ArrayList Dependencies {
412 get { return dependencies; }
415 internal string PrivateBinPath {
417 if (privateBinPath != null)
418 return privateBinPath;
420 AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
421 privateBinPath = setup.PrivateBinPath;
423 if (!Path.IsPathRooted (privateBinPath)) {
424 string appbase = setup.ApplicationBase;
425 if (appbase.StartsWith ("file://")) {
426 appbase = appbase.Substring (7);
427 if (Path.DirectorySeparatorChar != '/')
428 appbase = appbase.Replace ('/', Path.DirectorySeparatorChar);
430 privateBinPath = Path.Combine (appbase, privateBinPath);
433 return privateBinPath;
437 internal string BaseDir {
440 baseDir = context.Request.MapPath (BaseVirtualDir);
446 internal virtual string BaseVirtualDir {
448 if (baseVDir == null)
449 baseVDir = UrlUtils.GetDirectory (context.Request.FilePath);
455 internal CompilationConfiguration CompilationConfig {
457 if (compilationConfig == null)
458 compilationConfig = CompilationConfiguration.GetInstance (context);
460 return compilationConfig;