File: AppCodeCompiler.cs

package info (click to toggle)
mono 1.2.2.1-1etch1
  • links: PTS
  • area: main
  • in suites: etch
  • size: 142,720 kB
  • ctags: 256,408
  • sloc: cs: 1,495,736; ansic: 249,442; sh: 18,327; xml: 12,463; makefile: 5,046; perl: 1,248; asm: 635; yacc: 285; sql: 7
file content (328 lines) | stat: -rw-r--r-- 10,365 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
//
// System.Web.Compilation.AppCodeCompiler: A compiler for the App_Code folder
//
// Authors:
//   Marek Habersack (grendello@gmail.com)
//
// (C) 2006 Marek Habersack
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
// 
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0
using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Web;
using System.Web.Configuration;
using System.Web.Util;

namespace System.Web.Compilation
{
	internal class AppCodeAssembly
	{
		private List<string> files;

		private string name;
		private string path;
		private bool validAssembly;
		
		public bool IsValid
		{
			get { return validAssembly; }
		}

		public string SourcePath
		{
			get { return path; }
		}

// temporary
		public string Name
		{
			get { return name; }
		}
		
		public List<string> Files
		{
			get { return files; }
		}
// temporary
		
		public AppCodeAssembly (string name, string path)
		{
			this.files = new List<string>();
			this.validAssembly = true;
			this.name = name;
			this.path = path;
		}

		public void AddFile (string path)
		{
			files.Add (path);
		}

		object OnCreateTemporaryAssemblyFile (string path)
		{
			FileStream f = new FileStream (path, FileMode.CreateNew);
			f.Close ();
			return path;
		}
		
		// Build and add the assembly to the BuildManager's
		// CodeAssemblies collection
		public void Build (string[] binAssemblies)
		{
			Type compilerProvider = null;
			CompilerInfo compilerInfo = null, cit;
			string extension, language, cpfile = null;
			List<string> knownfiles = new List<string>();
			List<string> unknownfiles = new List<string>();
			
			// First make sure all the files are in the same
			// language
			bool known;
			foreach (string f in files) {
				known = true;
				language = null;
				
				extension = Path.GetExtension (f);
				if (!CodeDomProvider.IsDefinedExtension (extension))
					known = false;
				if (known) {
					language = CodeDomProvider.GetLanguageFromExtension(extension);
					if (!CodeDomProvider.IsDefinedLanguage (language))
						known = false;
				}
				if (!known || language == null) {
					unknownfiles.Add (f);
					continue;
				}
				
				cit = CodeDomProvider.GetCompilerInfo (language);
				if (cit == null || !cit.IsCodeDomProviderTypeValid)
					continue;
				if (compilerProvider == null) {
					cpfile = f;
					compilerProvider = cit.CodeDomProviderType;
					compilerInfo = cit;
				} else if (compilerProvider != cit.CodeDomProviderType)
					throw new HttpException (
						String.Format (
							"Files {0} and {1} are in different languages - they cannot be compiled into the same assembly",
							Path.GetFileName (cpfile),
							Path.GetFileName (f)));
				knownfiles.Add (f);
			}

			CodeDomProvider provider = null;
			if (compilerInfo == null) {
				CompilationSection config = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
				if (config == null || !CodeDomProvider.IsDefinedLanguage (config.DefaultLanguage))
					throw new HttpException ("Failed to retrieve default source language");
				compilerInfo = CodeDomProvider.GetCompilerInfo (config.DefaultLanguage);
				if (compilerInfo == null || !compilerInfo.IsCodeDomProviderTypeValid)
					throw new HttpException ("Internal error while initializing application");
				provider = compilerInfo.CreateProvider ();
				if (provider == null)
					throw new HttpException ("A code provider error occurred while initializing application.");
			}

			provider = compilerInfo.CreateProvider ();
			if (provider == null)
				throw new HttpException ("A code provider error occurred while initializing application.");

			AssemblyBuilder abuilder = new AssemblyBuilder (provider);
			foreach (string file in knownfiles)
				abuilder.AddCodeFile (file);
			
			BuildProvider bprovider;
			CompilationSection compilationSection = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
			CompilerParameters parameters = compilerInfo.CreateDefaultCompilerParameters ();
			if (binAssemblies != null && binAssemblies.Length > 0)
				parameters.ReferencedAssemblies.AddRange (binAssemblies);
			
			if (compilationSection != null) {
				foreach (AssemblyInfo ai in compilationSection.Assemblies)
					if (ai.Assembly != "*")
						parameters.ReferencedAssemblies.Add (ai.Assembly);
				
				BuildProviderCollection buildProviders = compilationSection.BuildProviders;
				
				foreach (string file in unknownfiles) {
					bprovider = GetBuildProviderFor (file, buildProviders);
					if (bprovider == null)
						continue;
					bprovider.GenerateCode (abuilder);
				}
			}
			
			string assemblyName = (string)FileUtils.CreateTemporaryFile (
				AppDomain.CurrentDomain.SetupInformation.DynamicBase,
				name, "dll", OnCreateTemporaryAssemblyFile);
			parameters.OutputAssembly = assemblyName;
			CompilerResults results = abuilder.BuildAssembly (parameters);
			if (results.Errors.Count == 0) {
				BuildManager.CodeAssemblies.Add (results.PathToAssembly);
				BuildManager.TopLevelAssemblies.Add (results.CompiledAssembly);
			} else {
				if (HttpContext.Current.IsCustomErrorEnabled)
					throw new HttpException ("An error occurred while initializing application.");
				throw new CompilationException (null, results.Errors, null);
			}
		}

		private BuildProvider GetBuildProviderFor (string file, BuildProviderCollection buildProviders)
		{
			if (file == null || file.Length == 0 || buildProviders == null || buildProviders.Count == 0)
				return null;

			BuildProvider ret = buildProviders.GetProviderForExtension (Path.GetExtension (file));
			if (ret != null && IsCorrectBuilderType (ret)) {
				ret.SetVirtualPath (VirtualPathUtility.ToAppRelative (file));
				return ret;
			}
				
			return null;
		}

		private bool IsCorrectBuilderType (BuildProvider bp)
		{
			if (bp == null)
				return false;
			Type type;
			object[] attrs;

			type = bp.GetType ();
			attrs = type.GetCustomAttributes (true);
			if (attrs == null)
				return false;
			
			BuildProviderAppliesToAttribute bpAppliesTo;
			bool attributeFound = false;
			foreach (object attr in attrs) {
				bpAppliesTo = attr as BuildProviderAppliesToAttribute;
				if (bpAppliesTo == null)
					continue;
				attributeFound = true;
				if ((bpAppliesTo.AppliesTo & BuildProviderAppliesTo.All) == BuildProviderAppliesTo.All ||
				    (bpAppliesTo.AppliesTo & BuildProviderAppliesTo.Code) == BuildProviderAppliesTo.Code)
					return true;
			}

			if (attributeFound)
				return false;
			return true;
		}
		
	}
	
	internal class AppCodeCompiler
	{
		// A dictionary that contains an entry per an assembly that will
		// be produced by compiling App_Code. There's one main assembly
		// and an optional number of assemblies as defined by the
		// codeSubDirectories sub-element of the compilation element in
		// the system.web section of the app's config file.
		// Each entry's value is an AppCodeAssembly instance.
		//
		// Assemblies are named as follows:
		//
		//  1. main assembly: App_Code.{HASH}
		//  2. subdir assemblies: App_SubCode_{DirName}.{HASH}
		//
		// If any of the assemblies contains files that would be
		// compiled with different compilers, a System.Web.HttpException
		// is thrown.
		//
		// Files for which there is no explicit builder are ignored
		// silently
		//
		// Files for which exist BuildProviders but which have no
		// unambiguous language assigned to them (e.g. .wsdl files), are
		// built using the default website compiler.
		private List<AppCodeAssembly> assemblies;
		
		public AppCodeCompiler ()
		{
			assemblies = new List<AppCodeAssembly>();
		}

		public void Compile ()
		{
			string appCode = Path.Combine (HttpRuntime.AppDomainAppPath, "App_Code");
			if (!Directory.Exists (appCode))
				return;
			
			// First process the codeSubDirectories
			CompilationSection cs = (CompilationSection) WebConfigurationManager.GetSection ("system.web/compilation");
			
			if (cs != null) {
				string aname;
				for (int i = 0; i < cs.CodeSubDirectories.Count; i++) {
					aname = String.Format ("App_SubCode_{0}", cs.CodeSubDirectories[i].DirectoryName);
					assemblies.Add (new AppCodeAssembly (
								aname,
								Path.Combine (appCode, cs.CodeSubDirectories[i].DirectoryName)));
				}
			}
			AppCodeAssembly defasm = new AppCodeAssembly ("App_Code", appCode);
			assemblies.Add (defasm);
			if (!CollectFiles (appCode, defasm))
				return;

			AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
			string bindir = Path.Combine (setup.ApplicationBase, setup.PrivateBinPath);
			string[] binAssemblies = null;
			if (Directory.Exists (bindir))
				binAssemblies = Directory.GetFiles (bindir, "*.dll");
			foreach (AppCodeAssembly aca in assemblies)
				aca.Build (binAssemblies);
		}

		private bool CollectFiles (string dir, AppCodeAssembly aca)
		{
			bool haveFiles = false;
			
			AppCodeAssembly curaca = aca;
			foreach (string f in Directory.GetFiles (dir)) {
				aca.AddFile (f);
				haveFiles = true;
			}
			
			foreach (string d in Directory.GetDirectories (dir)) {
				foreach (AppCodeAssembly a in assemblies)
					if (a.SourcePath == d) {
						curaca = a;
						break;
					}
				CollectFiles (d, curaca);
				curaca = aca;
			}
			return haveFiles;
		}
	}
}
#endif