2007-05-07 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / class / System.Web / System.Web.Compilation / AssemblyBuilder.cs
1 //
2 // System.Web.Compilation.AssemblyBuilder
3 //
4 // Authors:
5 //      Chris Toshok (toshok@ximian.com)
6 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 //
8 // (C) 2006 Novell, Inc (http://www.novell.com)
9 //
10
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31
32 #if NET_2_0
33
34 using System;
35 using System.CodeDom;
36 using System.CodeDom.Compiler;
37 using System.Collections.Generic;
38 using System.Collections.Specialized;
39 using System.IO;
40 using System.Reflection;
41 using System.Web.Configuration;
42 using System.Web.Util;
43
44 namespace System.Web.Compilation {
45
46         public class AssemblyBuilder {
47                 static bool KeepFiles = (Environment.GetEnvironmentVariable ("MONO_ASPNET_NODELETE") != null);
48
49                 CodeDomProvider provider;
50                 List <CodeCompileUnit> units;
51                 List <string> source_files;
52                 List <string> referenced_assemblies;
53                 Dictionary <string, string> resource_files;
54                 TempFileCollection temp_files;
55                 //TODO: there should be a Compile () method here which is where all the compilation exceptions are thrown from.
56
57                 internal AssemblyBuilder (CodeDomProvider provider)
58                 : this (null, provider)
59                 {}
60                 
61                 internal AssemblyBuilder (string virtualPath, CodeDomProvider provider)
62                 {
63                         this.provider = provider;
64                         units = new List <CodeCompileUnit> ();
65                         temp_files = new TempFileCollection ();
66                         referenced_assemblies = new List <string> ();
67                         CompilationSection section;
68                         if (virtualPath != null)
69                                 section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation", virtualPath);
70                         else
71                                 section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
72                         string tempdir = section.TempDirectory;
73                         if (tempdir == null || tempdir == "")
74                                 tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
75                                 
76                         temp_files = new TempFileCollection (tempdir, KeepFiles);
77                 }
78                 
79                 internal TempFileCollection TempFiles {
80                         get { return temp_files; }
81                 }
82
83                 internal CodeCompileUnit [] GetUnitsAsArray ()
84                 {
85                         CodeCompileUnit [] result = new CodeCompileUnit [units.Count];
86                         units.CopyTo (result, 0);
87                         return result;
88                 }
89
90                 List <string> SourceFiles {
91                         get {
92                                 if (source_files == null)
93                                         source_files = new List <string> ();
94                                 return source_files;
95                         }
96                 }
97
98                 Dictionary <string, string> ResourceFiles {
99                         get {
100                                 if (resource_files == null)
101                                         resource_files = new Dictionary <string, string> ();
102                                 return resource_files;
103                         }
104                 }
105
106                 public void AddAssemblyReference (Assembly a)
107                 {
108                         if (a == null)
109                                 throw new ArgumentNullException ("a");
110
111                         referenced_assemblies.Add (a.Location);
112                 }
113
114                 internal void AddCodeCompileUnit (CodeCompileUnit compileUnit)
115                 {
116                         if (compileUnit == null)
117                                 throw new ArgumentNullException ("compileUnit");
118                         units.Add (compileUnit);
119                 }
120                 
121                 public void AddCodeCompileUnit (BuildProvider buildProvider, CodeCompileUnit compileUnit)
122                 {
123                         if (buildProvider == null)
124                                 throw new ArgumentNullException ("buildProvider");
125
126                         if (compileUnit == null)
127                                 throw new ArgumentNullException ("compileUnit");
128
129                         units.Add (compileUnit);
130                 }
131
132                 public TextWriter CreateCodeFile (BuildProvider buildProvider)
133                 {
134                         if (buildProvider == null)
135                                 throw new ArgumentNullException ("buildProvider");
136
137                         // Generate a file name with the correct source language extension
138                         string filename = GetTempFilePhysicalPath (provider.FileExtension);
139                         SourceFiles.Add (filename);
140                         return new StreamWriter (File.OpenWrite (filename), WebEncoding.FileEncoding);
141                 }
142
143                 internal void AddCodeFile (string path)
144                 {
145                         if (path == null || path.Length == 0)
146                                 return;
147                         string extension = Path.GetExtension (path);
148                         if (extension == null || extension.Length == 0)
149                                 return; // maybe better to throw an exception here?
150                         extension = extension.Substring (1);
151                         string filename = GetTempFilePhysicalPath (extension);
152                         File.Copy (path, filename, true);
153                         SourceFiles.Add (filename);
154                 }
155                 
156                 public Stream CreateEmbeddedResource (BuildProvider buildProvider, string name)
157                 {
158                         if (buildProvider == null)
159                                 throw new ArgumentNullException ("buildProvider");
160
161                         if (name == null || name == "")
162                                 throw new ArgumentNullException ("name");
163
164                         string filename = GetTempFilePhysicalPath ("resource");
165                         Stream stream = File.OpenWrite (filename);
166                         ResourceFiles [name] = filename;
167                         return stream;
168                 }
169
170                 [MonoTODO ("Not implemented, does nothing")]
171                 public void GenerateTypeFactory (string typeName)
172                 {
173                         // Do nothing by now.
174                 }
175
176                 public string GetTempFilePhysicalPath (string extension)
177                 {
178                         if (extension == null)
179                                 throw new ArgumentNullException ("extension");
180                         
181                         return temp_files.AddExtension (String.Format ("_{0}.{1}", temp_files.Count, extension), true);
182                 }
183
184                 public CodeDomProvider CodeDomProvider {
185                         get { return provider; }
186                 }
187
188                 internal CompilerResults BuildAssembly (CompilerParameters options)
189                 {
190                         return BuildAssembly (null, options);
191                 }
192                 
193                 internal CompilerResults BuildAssembly (string virtualPath, CompilerParameters options)
194                 {
195                         if (options == null)
196                                 throw new ArgumentNullException ("options");
197                         
198                         CompilerResults results;
199                         CodeCompileUnit [] units = GetUnitsAsArray ();
200
201                         // Since we may have some source files and some code
202                         // units, we generate code from all of them and then
203                         // compile the assembly from the set of temporary source
204                         // files. This also facilates possible debugging for the
205                         // end user, since they get the code beforehand.
206                         List <string> files = SourceFiles;
207                         string filename;
208                         StreamWriter sw = null;
209                         foreach (CodeCompileUnit unit in units) {
210                                 filename = GetTempFilePhysicalPath (provider.FileExtension);
211                                 try {
212                                         sw = new StreamWriter (File.OpenWrite (filename), WebEncoding.FileEncoding);
213                                         provider.GenerateCodeFromCompileUnit (unit, sw, null);
214                                         files.Add (filename);
215                                 } catch {
216                                         throw;
217                                 } finally {
218                                         if (sw != null) {
219                                                 sw.Flush ();
220                                                 sw.Close ();
221                                         }
222                                 }
223                         }
224                         Dictionary <string, string> resources = ResourceFiles;
225                         foreach (KeyValuePair <string, string> de in resources)
226                                 options.EmbeddedResources.Add (de.Value);
227                         foreach (string refasm in referenced_assemblies)
228                                 options.ReferencedAssemblies.Add (refasm);
229                         
230                         results = provider.CompileAssemblyFromFile (options, files.ToArray ());                 
231
232                         if (results.NativeCompilerReturnValue != 0) {
233                                 string fileText = null;
234                                 try {
235                                         using (StreamReader sr = File.OpenText (results.Errors [0].FileName)) {
236                                                 fileText = sr.ReadToEnd ();
237                                         }
238                                 } catch (Exception) {}
239                                 
240                                 throw new CompilationException (virtualPath, results.Errors, fileText);
241                         }
242                         
243                         Assembly assembly = results.CompiledAssembly;
244                         if (assembly == null) {
245                                 if (!File.Exists (options.OutputAssembly)) {
246                                         results.TempFiles.Delete ();
247                                         throw new CompilationException (virtualPath, results.Errors,
248                                                 "No assembly returned after compilation!?");
249                                 }
250
251                                 try {
252                                         results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
253                                 } catch (Exception ex) {
254                                         results.TempFiles.Delete ();
255                                         throw new HttpException ("Unable to load compiled assembly");
256                                 }
257                         }
258
259                         if (!KeepFiles)
260                                 results.TempFiles.Delete ();
261                         return results;
262                 }
263         }
264 }
265 #endif
266