Modification of the App_Code compiler which adds support for BuildProviders
[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                 string virtual_path;
56                 //TODO: there should be a Compile () method here which is where all the compilation exceptions are thrown from.
57
58                 internal AssemblyBuilder (CodeDomProvider provider)
59                 : this (null, provider)
60                 {}
61                 
62                 internal AssemblyBuilder (string virtualPath, CodeDomProvider provider)
63                 {
64                         this.provider = provider;
65                         this.virtual_path = virtualPath;
66                         units = new List <CodeCompileUnit> ();
67                         temp_files = new TempFileCollection ();
68                         referenced_assemblies = new List <string> ();
69                         CompilationSection section;
70                         if (virtualPath != null)
71                                 section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation", virtualPath);
72                         else
73                                 section = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
74                         string tempdir = section.TempDirectory;
75                         if (tempdir == null || tempdir == "")
76                                 tempdir = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
77                                 
78                         temp_files = new TempFileCollection (tempdir, KeepFiles);
79                 }
80                 
81                 internal TempFileCollection TempFiles {
82                         get { return temp_files; }
83                 }
84
85                 internal CodeCompileUnit [] GetUnitsAsArray ()
86                 {
87                         CodeCompileUnit [] result = new CodeCompileUnit [units.Count];
88                         units.CopyTo (result, 0);
89                         return result;
90                 }
91
92                 List <string> SourceFiles {
93                         get {
94                                 if (source_files == null)
95                                         source_files = new List <string> ();
96                                 return source_files;
97                         }
98                 }
99
100                 Dictionary <string, string> ResourceFiles {
101                         get {
102                                 if (resource_files == null)
103                                         resource_files = new Dictionary <string, string> ();
104                                 return resource_files;
105                         }
106                 }
107
108                 public void AddAssemblyReference (Assembly a)
109                 {
110                         if (a == null)
111                                 throw new ArgumentNullException ("a");
112                         
113                         referenced_assemblies.Add (a.Location);
114                 }
115
116                 public void AddCodeCompileUnit (BuildProvider buildProvider, CodeCompileUnit compileUnit)
117                 {
118                         if (buildProvider == null)
119                                 throw new ArgumentNullException ("buildProvider");
120
121                         if (compileUnit == null)
122                                 throw new ArgumentNullException ("compileUnit");
123
124                         units.Add (compileUnit);
125                 }
126
127                 public TextWriter CreateCodeFile (BuildProvider buildProvider)
128                 {
129                         if (buildProvider == null)
130                                 throw new ArgumentNullException ("buildProvider");
131
132                         // Generate a file name with the correct source language extension
133                         string filename = GetTempFilePhysicalPath (provider.FileExtension);
134                         SourceFiles.Add (filename);
135                         return new StreamWriter (File.OpenWrite (filename), WebEncoding.FileEncoding);
136                 }
137
138                 internal void AddCodeFile (string path)
139                 {
140                         if (path == null || path.Length == 0)
141                                 return;
142                         string extension = Path.GetExtension (path);
143                         if (extension == null || extension.Length == 0)
144                                 return; // maybe better to throw an exception here?
145                         extension = extension.Substring (1);
146                         string filename = GetTempFilePhysicalPath (extension);
147                         File.Copy (path, filename, true);
148                         SourceFiles.Add (filename);
149                 }
150                 
151                 public Stream CreateEmbeddedResource (BuildProvider buildProvider, string name)
152                 {
153                         if (buildProvider == null)
154                                 throw new ArgumentNullException ("buildProvider");
155
156                         if (name == null || name == "")
157                                 throw new ArgumentNullException ("name");
158
159                         string filename = GetTempFilePhysicalPath ("resource");
160                         Stream stream = File.OpenWrite (filename);
161                         ResourceFiles [name] = filename;
162                         return stream;
163                 }
164
165                 [MonoTODO]
166                 public void GenerateTypeFactory (string typeName)
167                 {
168                         // Do nothing by now.
169                 }
170
171                 public string GetTempFilePhysicalPath (string extension)
172                 {
173                         if (extension == null)
174                                 throw new ArgumentNullException ("extension");
175                         
176                         return temp_files.AddExtension (String.Format ("_{0}.{1}", temp_files.Count, extension), true);
177                 }
178
179                 public CodeDomProvider CodeDomProvider {
180                         get { return provider; }
181                 }
182
183                 internal CompilerResults BuildAssembly (CompilerParameters options)
184                 {
185                         return BuildAssembly (null, options);
186                 }
187                 
188                 internal CompilerResults BuildAssembly (string virtualPath, CompilerParameters options)
189                 {
190                         if (options == null)
191                                 throw new ArgumentNullException ("options");
192                         
193                         CompilerResults results;
194                         CodeCompileUnit [] units = GetUnitsAsArray ();
195
196                         // Since we may have some source files and some code
197                         // units, we generate code from all of them and then
198                         // compile the assembly from the set of temporary source
199                         // files. This also facilates possible debugging for the
200                         // end user, since they get the code beforehand.
201                         List <string> files = SourceFiles;
202                         string filename;
203                         StreamWriter sw = null;
204                         foreach (CodeCompileUnit unit in units) {
205                                 filename = GetTempFilePhysicalPath (provider.FileExtension);
206                                 try {
207                                         sw = new StreamWriter (File.OpenWrite (filename), WebEncoding.FileEncoding);
208                                         provider.GenerateCodeFromCompileUnit (unit, sw, null);
209                                         files.Add (filename);
210                                 } catch {
211                                         throw;
212                                 } finally {
213                                         if (sw != null) {
214                                                 sw.Flush ();
215                                                 sw.Close ();
216                                         }
217                                 }
218                         }
219
220                         Dictionary <string, string> resources = ResourceFiles;
221                         foreach (KeyValuePair <string, string> de in resources)
222                                 options.EmbeddedResources.Add (de.Value);
223                         foreach (string refasm in referenced_assemblies)
224                                 options.ReferencedAssemblies.Add (refasm);
225                         
226                         results = provider.CompileAssemblyFromFile (options, files.ToArray ());
227                         
228                         // FIXME: generate the code and display it
229                         if (results.NativeCompilerReturnValue != 0)
230                                 throw new CompilationException (virtualPath, results.Errors, "");
231
232                         Assembly assembly = results.CompiledAssembly;
233                         if (assembly == null) {
234                                 if (!File.Exists (options.OutputAssembly)) {
235                                         results.TempFiles.Delete ();
236                                         throw new CompilationException (virtualPath, results.Errors,
237                                                 "No assembly returned after compilation!?");
238                                 }
239
240                                 results.CompiledAssembly = Assembly.LoadFrom (options.OutputAssembly);
241                         }
242
243                         if (!KeepFiles)
244                                 results.TempFiles.Delete ();
245                         return results;
246                 }
247         }
248 }
249 #endif
250