File: BuildManager.cs

package info (click to toggle)
mono-reference-assemblies 3.12.1%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 604,240 kB
  • ctags: 625,505
  • sloc: cs: 3,967,741; xml: 2,793,081; ansic: 418,042; java: 60,435; sh: 14,833; makefile: 11,576; sql: 7,956; perl: 1,467; cpp: 1,446; yacc: 1,203; python: 598; asm: 422; sed: 16; php: 1
file content (1494 lines) | stat: -rw-r--r-- 46,424 bytes parent folder | download
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
//
// System.Web.Compilation.BuildManager
//
// Authors:
//	Chris Toshok (toshok@ximian.com)
//	Gonzalo Paniagua Javier (gonzalo@novell.com)
//      Marek Habersack (mhabersack@novell.com)
//
// (C) 2006-2009 Novell, Inc (http://www.novell.com)
//

//
// 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.
//

using System;
using System.CodeDom;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Xml;
using System.Web;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.Hosting;
using System.Web.Util;
#if NET_4_0
using System.Runtime.Versioning;
#endif

namespace System.Web.Compilation
{
	public sealed class BuildManager
	{
		internal const string FAKE_VIRTUAL_PATH_PREFIX = "/@@MonoFakeVirtualPath@@";
		const string BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX = "@@Build_Manager@@";
		static int BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH = BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX.Length;

		static readonly object bigCompilationLock = new object ();
		static readonly object virtualPathsToIgnoreLock = new object ();
		static readonly char[] virtualPathsToIgnoreSplitChars = {','};
		
		static EventHandlerList events = new EventHandlerList ();
		static object buildManagerRemoveEntryEvent = new object ();
		
		static bool hosted;
		static Dictionary <string, bool> virtualPathsToIgnore;
		static bool virtualPathsToIgnoreChecked;
		static bool haveVirtualPathsToIgnore;
		static List <Assembly> AppCode_Assemblies = new List<Assembly>();
		static List <Assembly> TopLevel_Assemblies = new List<Assembly>();
		static Dictionary <Type, CodeDomProvider> codeDomProviders;
		static Dictionary <string, BuildManagerCacheItem> buildCache;
		static List <Assembly> referencedAssemblies;
		static List <Assembly> configReferencedAssemblies;
		static bool getReferencedAssembliesInvoked;
		
		static int buildCount;
		static bool is_precompiled;
		static bool allowReferencedAssembliesCaching;
#if NET_4_0
		static List <Assembly> dynamicallyRegisteredAssemblies;
		static bool? batchCompilationEnabled;
		static FrameworkName targetFramework;
		static bool preStartMethodsDone;
		static bool preStartMethodsRunning;
#endif
		//static bool updatable; unused
		static Dictionary<string, PreCompilationData> precompiled;
		
		// This is here _only_ for the purpose of unit tests!
		internal static bool suppressDebugModeMessages;

		// See comment for the cacheLock field at top of System.Web.Caching/Cache.cs
		static ReaderWriterLockSlim buildCacheLock;
		static ulong recursionDepth;

		internal static bool AllowReferencedAssembliesCaching {
			get { return allowReferencedAssembliesCaching; }
			set { allowReferencedAssembliesCaching = value; }
		}
		
		internal static bool IsPrecompiled {
			get { return is_precompiled; }
		}
		
		internal static event BuildManagerRemoveEntryEventHandler RemoveEntry {
			add { events.AddHandler (buildManagerRemoveEntryEvent, value); }
			remove { events.RemoveHandler (buildManagerRemoveEntryEvent, value); }
		}

#if NET_4_0
		internal static bool CompilingTopLevelAssemblies {
			get; set;
		}
		
		internal static bool PreStartMethodsRunning {
			get { return preStartMethodsRunning; }
		}
		
		public static bool? BatchCompilationEnabled {
			get { return batchCompilationEnabled; }
			set {
				if (preStartMethodsDone)
					throw new InvalidOperationException ("This method cannot be called after the application's pre-start initialization stage.");
				batchCompilationEnabled = value;
			}
		}

		public static FrameworkName TargetFramework {
			get {
				if (targetFramework == null) {
					CompilationSection cs = CompilationConfig;
					string framework;
					if (cs == null)
						framework = null;
					else
						framework = cs.TargetFramework;
					
					if (String.IsNullOrEmpty (framework))
						targetFramework = new FrameworkName (".NETFramework,Version=v4.0");
					else
						targetFramework = new FrameworkName (framework);
				}

				return targetFramework;
			}
		}
#endif
		internal static bool BatchMode {
			get {
#if NET_4_0
				if (batchCompilationEnabled != null)
					return (bool)batchCompilationEnabled;
#endif
				if (!hosted)
					return false; // Fix for bug #380985

				CompilationSection cs = CompilationConfig;
				if (cs == null)
					return true;
				
				return cs.Batch;
			}
		}

		// Assemblies built from the App_Code directory
		public static IList CodeAssemblies {
			get { return AppCode_Assemblies; }
		}
		
		internal static CompilationSection CompilationConfig {
			get { return WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection; }
		}

		internal static bool HaveResources {
			get; set;
		}
		
		internal static IList TopLevelAssemblies {
			get { return TopLevel_Assemblies; }
		}
		
		static BuildManager ()
		{
			hosted = (AppDomain.CurrentDomain.GetData (ApplicationHost.MonoHostedDataKey) as string) == "yes";
			buildCache = new Dictionary <string, BuildManagerCacheItem> (RuntimeHelpers.StringEqualityComparer);
			buildCacheLock = new ReaderWriterLockSlim ();
			referencedAssemblies = new List <Assembly> ();
			recursionDepth = 0;

			string appPath = HttpRuntime.AppDomainAppPath;
			string precomp_name = null;
			is_precompiled = String.IsNullOrEmpty (appPath) ? false : File.Exists ((precomp_name = Path.Combine (appPath, "PrecompiledApp.config")));
			if (is_precompiled)
				is_precompiled = LoadPrecompilationInfo (precomp_name);
		}
#if NET_4_0
		internal static void AssertPreStartMethodsRunning ()
		{
			if (!BuildManager.PreStartMethodsRunning)
				throw new InvalidOperationException ("This method must be called during the application's pre-start initialization stage.");
		}
#endif
		// Deal with precompiled sites deployed in a different virtual path
		static void FixVirtualPaths ()
		{
			if (precompiled == null)
				return;
			
			string [] parts;
			int skip = -1;
			string appVirtualRoot = VirtualPathUtility.AppendTrailingSlash (HttpRuntime.AppDomainAppVirtualPath);
			foreach (string vpath in precompiled.Keys) {
				parts = vpath.Split ('/');
				for (int i = 0; i < parts.Length; i++) {
					if (String.IsNullOrEmpty (parts [i]))
						continue;
					// The path must be rooted, otherwise PhysicalPath returned
					// below will be relative to the current request path and
					// File.Exists will return a false negative. See bug #546053
					string test_path = appVirtualRoot + String.Join ("/", parts, i, parts.Length - i);
					VirtualPath result = GetAbsoluteVirtualPath (test_path);
					if (result != null && File.Exists (result.PhysicalPath)) {
						skip = i - 1;
						break;
					}
				}
			}
			
			string app_vpath = HttpRuntime.AppDomainAppVirtualPath;
			if (skip == -1 || (skip == 0 && app_vpath == "/"))
				return;

			if (!app_vpath.EndsWith ("/"))
				app_vpath = app_vpath + "/";
			Dictionary<string, PreCompilationData> copy = new Dictionary<string, PreCompilationData> (precompiled);
			precompiled.Clear ();
			foreach (KeyValuePair<string,PreCompilationData> entry in copy) {
				parts = entry.Key.Split ('/');
				string new_path;
				if (String.IsNullOrEmpty (parts [0]))
					new_path = app_vpath + String.Join ("/", parts, skip + 1, parts.Length - skip - 1);
				else
					new_path = app_vpath + String.Join ("/", parts, skip, parts.Length - skip);
				entry.Value.VirtualPath = new_path;
				precompiled.Add (new_path, entry.Value);
			}
		}

		static bool LoadPrecompilationInfo (string precomp_config)
		{
			using (XmlTextReader reader = new XmlTextReader (precomp_config)) {
				reader.MoveToContent ();
				if (reader.Name != "precompiledApp")
					return false;

				/* unused
				if (reader.HasAttributes)
					while (reader.MoveToNextAttribute ())
						if (reader.Name == "updatable") {
							updatable = (reader.Value == "true");
							break;
						}
				*/
			}

			string [] compiled = Directory.GetFiles (HttpRuntime.BinDirectory, "*.compiled");
			foreach (string str in compiled)
				LoadCompiled (str);

			FixVirtualPaths ();
			return true;
		}

		static void LoadCompiled (string filename)
		{
			using (XmlTextReader reader = new XmlTextReader (filename)) {
				reader.MoveToContent ();
				if (reader.Name == "preserve" && reader.HasAttributes) {
					reader.MoveToNextAttribute ();
					string val = reader.Value;
					// 1 -> app_code subfolder - add the assembly to CodeAssemblies
					// 2 -> ashx
					// 3 -> ascx, aspx
					// 6 -> app_code - add the assembly to CodeAssemblies
					// 8 -> global.asax
					// 9 -> App_GlobalResources - set the assembly for HttpContext
					if (reader.Name == "resultType" && (val == "2" || val == "3" || val == "8"))
						LoadPageData (reader, true);
					else if (val == "1" || val == "6") {
						PreCompilationData pd = LoadPageData (reader, false);
						CodeAssemblies.Add (Assembly.Load (pd.AssemblyFileName));
					} else if (val == "9") {
						PreCompilationData pd = LoadPageData (reader, false);
						HttpContext.AppGlobalResourcesAssembly = Assembly.Load (pd.AssemblyFileName);
					}
				}
			}
		}

		class PreCompilationData {
			public string VirtualPath;
			public string AssemblyFileName;
			public string TypeName;
			public Type Type;
		}

		static PreCompilationData LoadPageData (XmlTextReader reader, bool store)
		{
			PreCompilationData pc_data = new PreCompilationData ();

			while (reader.MoveToNextAttribute ()) {
				string name = reader.Name;
				if (name == "virtualPath")
					pc_data.VirtualPath = VirtualPathUtility.RemoveTrailingSlash (reader.Value);
				else if (name == "assembly")
					pc_data.AssemblyFileName = reader.Value;
				else if (name == "type")
					pc_data.TypeName = reader.Value;
			}
			if (store) {
				if (precompiled == null)
					precompiled = new Dictionary<string, PreCompilationData> (RuntimeHelpers.StringEqualityComparerCulture);
				precompiled.Add (pc_data.VirtualPath, pc_data);
			}
			return pc_data;
		}

		static void AddAssembly (Assembly asm, List <Assembly> al)
		{
			if (al.Contains (asm))
				return;

			al.Add (asm);
		}
		
		static void AddPathToIgnore (string vp)
		{
			if (virtualPathsToIgnore == null)
				virtualPathsToIgnore = new Dictionary <string, bool> (RuntimeHelpers.StringEqualityComparerCulture);
			
			VirtualPath path = GetAbsoluteVirtualPath (vp);
			string vpAbsolute = path.Absolute;
			if (!virtualPathsToIgnore.ContainsKey (vpAbsolute)) {
				virtualPathsToIgnore.Add (vpAbsolute, true);
				haveVirtualPathsToIgnore = true;
			}
			
			string vpRelative = path.AppRelative;
			if (!virtualPathsToIgnore.ContainsKey (vpRelative)) {
				virtualPathsToIgnore.Add (vpRelative, true);
				haveVirtualPathsToIgnore = true;
			}

			if (!virtualPathsToIgnore.ContainsKey (vp)) {
				virtualPathsToIgnore.Add (vp, true);
				haveVirtualPathsToIgnore = true;
			}
		}

		internal static void AddToReferencedAssemblies (Assembly asm)
		{
			// should not be used
		}
		
		static void AssertVirtualPathExists (VirtualPath virtualPath)
		{
			string realpath;
			bool dothrow = false;
			
			if (virtualPath.IsFake) {
				realpath = virtualPath.PhysicalPath;
				if (!File.Exists (realpath) && !Directory.Exists (realpath))
					dothrow = true;
			} else {
				VirtualPathProvider vpp = HostingEnvironment.VirtualPathProvider;
				string vpAbsolute = virtualPath.Absolute;
				
				if (!vpp.FileExists (vpAbsolute) && !vpp.DirectoryExists (vpAbsolute))
					dothrow = true;
			}

			if (dothrow)
				throw new HttpException (404, "The file '" + virtualPath + "' does not exist.", virtualPath.Absolute);
		}

		static void Build (VirtualPath vp)
		{
			AssertVirtualPathExists (vp);

			CompilationSection cs = CompilationConfig;
			lock (bigCompilationLock) {
				bool entryExists;
				if (HasCachedItemNoLock (vp.Absolute, out entryExists))
					return;

				if (recursionDepth == 0)
					referencedAssemblies.Clear ();

				recursionDepth++;
				try {
					BuildInner (vp, cs != null ? cs.Debug : false);
					if (entryExists && recursionDepth <= 1)
						// We count only update builds - first time a file
						// (or a batch) is built doesn't count.
						buildCount++;
				} finally {
					// See http://support.microsoft.com/kb/319947
					if (buildCount > cs.NumRecompilesBeforeAppRestart)
						HttpRuntime.UnloadAppDomain ();
					recursionDepth--;
				}
			}
		}

		// This method assumes it is being called with the big compilation lock held
		static void BuildInner (VirtualPath vp, bool debug)
		{
			var builder = new BuildManagerDirectoryBuilder (vp);
			bool recursive = recursionDepth > 1;
			List <BuildProviderGroup> builderGroups = builder.Build (IsSingleBuild (vp, recursive));
			if (builderGroups == null)
				return;

			string vpabsolute = vp.Absolute;
			int buildHash = (vpabsolute.GetHashCode () | (int)DateTime.Now.Ticks) + (int)recursionDepth;
			string assemblyBaseName;
			AssemblyBuilder abuilder;
			CompilerType ct;
			int attempts;
			bool singleBuild, needMainVpBuild;
			CompilationException compilationError;
			
			// Each group becomes a separate assembly.
			foreach (BuildProviderGroup group in builderGroups) {
				needMainVpBuild = false;
				compilationError = null;
				assemblyBaseName = null;
				
				if (group.Count == 1) {
					if (recursive || !group.Master)
						assemblyBaseName = String.Format ("{0}_{1}.{2:x}.", group.NamePrefix, VirtualPathUtility.GetFileName (group [0].VirtualPath), buildHash);
					singleBuild = true;
				} else
					singleBuild = false;
				
				if (assemblyBaseName == null)
					assemblyBaseName = group.NamePrefix + "_";
				
				ct = group.CompilerType;
				attempts = 3;
				while (attempts > 0) {
					abuilder = new AssemblyBuilder (vp, CreateDomProvider (ct), assemblyBaseName);
					abuilder.CompilerOptions = ct.CompilerParameters;
					abuilder.AddAssemblyReference (GetReferencedAssemblies () as List <Assembly>);
					try {
						GenerateAssembly (abuilder, group, vp, debug);
						attempts = 0;
					} catch (CompilationException ex) {
						attempts--;
						if (singleBuild)
							throw new HttpException ("Single file build failed.", ex);
						
						if (attempts == 0) {
							needMainVpBuild = true;
							compilationError = ex;
							break;
						}
						
						CompilerResults results = ex.Results;
						if (results == null)
							throw new HttpException ("No results returned from failed compilation.", ex);
						else
							RemoveFailedAssemblies (vpabsolute, ex, abuilder, group, results, debug);
					}
				}

				if (needMainVpBuild) {
					// One last attempt - try to build just the requested path
					// if it's not built yet or just return without throwing the
					// exception if it has already been built. 
					if (HasCachedItemNoLock (vpabsolute)) {
						if (debug)
							DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
										  compilationError, vpabsolute);
						return;
					};

					// This will trigger a recursive build of the requested vp,
					// which means only the vp alone will be built (or not); 
					Build (vp);
					if (HasCachedItemNoLock (vpabsolute)) {
						if (debug)
							DescribeCompilationError ("Path '{0}' built successfully, but a compilation exception has been thrown for other files:",
										  compilationError, vpabsolute);
						return;
					}

					// In theory this code is unreachable. If the recursive
					// build of the main vp failed, then it should have thrown
					// the build exception.
					throw new HttpException ("Requested virtual path build failed.", compilationError);
				}
			}
		}
		
		static CodeDomProvider CreateDomProvider (CompilerType ct)
		{
			if (codeDomProviders == null)
				codeDomProviders = new Dictionary <Type, CodeDomProvider> ();

			Type type = ct.CodeDomProviderType;
			if (type == null) {
				CompilationSection cs = CompilationConfig;
				CompilerType tmp = GetDefaultCompilerTypeForLanguage (cs.DefaultLanguage, cs);
				if (tmp != null)
					type = tmp.CodeDomProviderType;
			}

			if (type == null)
				return null;
			
			CodeDomProvider ret;
			if (codeDomProviders.TryGetValue (type, out ret))
				return ret;

			ret = Activator.CreateInstance (type) as CodeDomProvider;
			if (ret == null)
				return null;

			codeDomProviders.Add (type, ret);
			return ret;
		}		
#if NET_4_0
		internal static void CallPreStartMethods ()
		{
			if (preStartMethodsDone)
				return;

			preStartMethodsRunning = true;
			MethodInfo mi = null;
			try {
				List <MethodInfo> methods = LoadPreStartMethodsFromAssemblies (GetReferencedAssemblies () as List <Assembly>);
				if (methods == null || methods.Count == 0)
					return;
			
				foreach (MethodInfo m in methods) {
					mi = m;
					m.Invoke (null, null);
				}
			} catch (Exception ex) {
				throw new HttpException (
					String.Format ("The pre-application start initialization method {0} on type {1} threw an exception with the following error message: {2}",
						       mi != null ? mi.Name : "UNKNOWN",
						       mi != null ? mi.DeclaringType.FullName : "UNKNOWN",
						       ex.Message),
					ex
				);
			} finally {
				preStartMethodsRunning = false;
				preStartMethodsDone = true;
			}
		}

		static List <MethodInfo> LoadPreStartMethodsFromAssemblies (List <Assembly> assemblies)
		{
			if (assemblies == null || assemblies.Count == 0)
				return null;

			var ret = new List <MethodInfo> ();
			object[] attributes;
			Type type;
			PreApplicationStartMethodAttribute attr;
			
			foreach (Assembly asm in assemblies) {
				try {
					attributes = asm.GetCustomAttributes (typeof (PreApplicationStartMethodAttribute), false);
					if (attributes == null || attributes.Length == 0)
						continue;

					attr = attributes [0] as PreApplicationStartMethodAttribute;
					type = attr.Type;
					if (type == null)
						continue;
				} catch {
					continue;
				}

				MethodInfo mi;
				Exception error = null;
				try {
					if (type.IsPublic)
						mi = type.GetMethod (attr.MethodName, BindingFlags.Static | BindingFlags.Public, null, new Type[] {}, null);
					else
						mi = null;
				} catch (Exception ex) {
					error = ex;
					mi = null;
				}

				if (mi == null)
					throw new HttpException (
						String.Format (
							"The method specified by the PreApplicationStartMethodAttribute on assembly '{0}' cannot be resolved. Type: '{1}', MethodName: '{2}'. Verify that the type is public and the method is public and static (Shared in Visual Basic).",
							asm.FullName,
							type.FullName,
							attr.MethodName),
						error
					);
				
				ret.Add (mi);
			}

			return ret;
		}
		
		public static Type GetGlobalAsaxType ()
		{
			Type ret = HttpApplicationFactory.AppType;
			if (ret == null)
				return typeof (HttpApplication);
			
			return ret;
		}
		
		public static Stream CreateCachedFile (string fileName)
		{
			if (fileName != null && (fileName == String.Empty || fileName.IndexOf (Path.DirectorySeparatorChar) != -1))
				throw new ArgumentException ("Value does not fall within the expected range.");

			string path = Path.Combine (HttpRuntime.CodegenDir, fileName);
			return new FileStream (path, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
		}

		public static Stream ReadCachedFile (string fileName)
		{
			if (fileName != null && (fileName == String.Empty || fileName.IndexOf (Path.DirectorySeparatorChar) != -1))
				throw new ArgumentException ("Value does not fall within the expected range.");

			string path = Path.Combine (HttpRuntime.CodegenDir, fileName);
			if (!File.Exists (path))
				return null;
			
			return new FileStream (path, FileMode.Open, FileAccess.Read, FileShare.None);
		}

		[MonoDocumentationNote ("Fully implemented but no info on application pre-init stage is available yet.")]
		public static void AddReferencedAssembly (Assembly assembly)
		{
			if (assembly == null)
				throw new ArgumentNullException ("assembly");

			if (preStartMethodsDone)
				throw new InvalidOperationException ("This method cannot be called after the application's pre-start initialization stage.");

			if (dynamicallyRegisteredAssemblies == null)
				dynamicallyRegisteredAssemblies = new List <Assembly> ();

			if (!dynamicallyRegisteredAssemblies.Contains (assembly))
				dynamicallyRegisteredAssemblies.Add (assembly);
		}

		[MonoDocumentationNote ("Not used by Mono internally. Needed for MVC3")]
		public static IWebObjectFactory GetObjectFactory (string virtualPath, bool throwIfNotFound)
		{
			if (CompilingTopLevelAssemblies)
				throw new HttpException ("Method must not be called while compiling the top level assemblies.");

			Type type;
			if (is_precompiled) {
				type = GetPrecompiledType (virtualPath);
				if (type == null) {
					if (throwIfNotFound)
						throw new HttpException (String.Format ("Virtual path '{0}' not found in precompiled application type cache.", virtualPath));
					else
						return null;
				}
				return new SimpleWebObjectFactory (type);
			}

			Exception compileException = null;
			try {
				type = GetCompiledType (virtualPath);
			} catch (Exception ex) {
				compileException = ex;
				type = null;
			}
			
			if (type == null) {
				if (throwIfNotFound)
					throw new HttpException (String.Format ("Virtual path '{0}' does not exist.", virtualPath), compileException);
				return null;
			}
			
			return new SimpleWebObjectFactory (type);
		}
#endif
		public static object CreateInstanceFromVirtualPath (string virtualPath, Type requiredBaseType)
		{
			return CreateInstanceFromVirtualPath (GetAbsoluteVirtualPath (virtualPath), requiredBaseType);
		}

		internal static object CreateInstanceFromVirtualPath (VirtualPath virtualPath, Type requiredBaseType)
		{
			if (requiredBaseType == null)
				throw new NullReferenceException (); // This is what MS does, but
								     // from somewhere else.
			
			Type type = GetCompiledType (virtualPath);
			if (type == null)
				return null;

			if (!requiredBaseType.IsAssignableFrom (type))
				throw new HttpException (500,
							 String.Format ("Type '{0}' does not inherit from '{1}'.", type.FullName, requiredBaseType.FullName));

			return Activator.CreateInstance (type, null);
		}
		
		static void DescribeCompilationError (string format, CompilationException ex, params object[] parms)
		{
			StringBuilder sb = new StringBuilder ();
			string newline = Environment.NewLine;
			
			if (parms != null)
				sb.AppendFormat (format + newline, parms);
			else
				sb.Append (format + newline);

			CompilerResults results = ex != null ? ex.Results : null;
			if (results == null)
				sb.Append ("No compiler error information present." + newline);
			else {
				sb.Append ("Compiler errors:" + newline);
				foreach (CompilerError error in results.Errors)
					sb.Append ("  " + error.ToString () + newline);
			}

			if (ex != null) {
				sb.Append (newline + "Exception thrown:" + newline);
				sb.Append (ex.ToString ());
			}

			ShowDebugModeMessage (sb.ToString ());
		}
		
		static BuildProvider FindBuildProviderForPhysicalPath (string path, BuildProviderGroup group, HttpRequest req)
		{
			if (req == null || String.IsNullOrEmpty (path))
				return null;

			foreach (BuildProvider bp in group) {
				if (String.Compare (path, req.MapPath (bp.VirtualPath), RuntimeHelpers.StringComparison) == 0)
					return bp;
			}
			
			return null;
		}
		
		static void GenerateAssembly (AssemblyBuilder abuilder, BuildProviderGroup group, VirtualPath vp, bool debug)
		{
			IDictionary <string, bool> deps;
			BuildManagerCacheItem bmci;
			string bvp, vpabsolute = vp.Absolute;
			StringBuilder sb;
			string newline;
			int failedCount = 0;
			
			if (debug) {
				newline = Environment.NewLine;
				sb = new StringBuilder ("Code generation for certain virtual paths in a batch failed. Those files have been removed from the batch." + newline);
				sb.Append ("Since you're running in debug mode, here's some more information about the error:" + newline);
			} else {
				newline = null;
				sb = null;
			}
			
			List <BuildProvider> failedBuildProviders = null;
			StringComparison stringComparison = RuntimeHelpers.StringComparison;
			foreach (BuildProvider bp in group) {
				bvp = bp.VirtualPath;
				if (HasCachedItemNoLock (bvp))
					continue;
				
				try {
					bp.GenerateCode (abuilder);
				} catch (Exception ex) {
					if (String.Compare (bvp, vpabsolute, stringComparison) == 0) {
						if (ex is CompilationException || ex is ParseException)
							throw;
						
						throw new HttpException ("Code generation failed.", ex);
					}
					
					if (failedBuildProviders == null)
						failedBuildProviders = new List <BuildProvider> ();
					failedBuildProviders.Add (bp);
					failedCount++;
					if (sb != null) {
						if (failedCount > 1)
							sb.Append (newline);
						
						sb.AppendFormat ("Failed file virtual path: {0}; Exception: {1}{2}{1}", bp.VirtualPath, newline, ex);
					}
					continue;
				}
				
				deps = bp.ExtractDependencies ();
				if (deps != null) {
					foreach (var dep in deps) {
						bmci = GetCachedItemNoLock (dep.Key);
						if (bmci == null || bmci.BuiltAssembly == null)
							continue;
						abuilder.AddAssemblyReference (bmci.BuiltAssembly);
					}
				}
			}

			if (sb != null && failedCount > 0)
				ShowDebugModeMessage (sb.ToString ());
			
			if (failedBuildProviders != null) {
				foreach (BuildProvider bp in failedBuildProviders)
					group.Remove (bp);
			}
			
			foreach (Assembly asm in referencedAssemblies) {
				if (asm == null)
					continue;
				
				abuilder.AddAssemblyReference (asm);
			}
			
			CompilerResults results  = abuilder.BuildAssembly (vp);
			
			// No results is not an error - it is possible that the assembly builder contained only .asmx and
			// .ashx files which had no body, just the directive. In such case, no code unit or code file is added
			// to the assembly builder and, in effect, no assembly is produced but there are STILL types that need
			// to be added to the cache.
			Assembly compiledAssembly = results != null ? results.CompiledAssembly : null;
			try {
				buildCacheLock.EnterWriteLock ();
				if (compiledAssembly != null)
					referencedAssemblies.Add (compiledAssembly);
				
				foreach (BuildProvider bp in group) {
					if (HasCachedItemNoLock (bp.VirtualPath))
						continue;
					
					StoreInCache (bp, compiledAssembly, results);
				}
			} finally {
				buildCacheLock.ExitWriteLock ();
			}
		}
		
		static VirtualPath GetAbsoluteVirtualPath (string virtualPath)
		{
			string vp;

			if (!VirtualPathUtility.IsRooted (virtualPath)) {
				HttpContext ctx = HttpContext.Current;
				HttpRequest req = ctx != null ? ctx.Request : null;
				
				if (req != null) {
					string fileDir = req.FilePath;
					if (!String.IsNullOrEmpty (fileDir) && String.Compare (fileDir, "/", StringComparison.Ordinal) != 0)
						fileDir = VirtualPathUtility.GetDirectory (fileDir);
					else
						fileDir = "/";

					vp = VirtualPathUtility.Combine (fileDir, virtualPath);
				} else
					throw new HttpException ("No context, cannot map paths.");
			} else
				vp = virtualPath;

			return new VirtualPath (vp);
		}

		[MonoTODO ("Not implemented, always returns null")]
		public static BuildDependencySet GetCachedBuildDependencySet (HttpContext context, string virtualPath)
		{
			return null; // null is ok here until we store the dependency set in the Cache.
		}
#if NET_4_0
		[MonoTODO ("Not implemented, always returns null")]
		public static BuildDependencySet GetCachedBuildDependencySet (HttpContext context, string virtualPath, bool ensureIsUpToDate)
		{
			return null; // null is ok here until we store the dependency set in the Cache.
		}
#endif
		static BuildManagerCacheItem GetCachedItem (string vp)
		{
			try {
				buildCacheLock.EnterReadLock ();
				return GetCachedItemNoLock (vp);
			} finally {
				buildCacheLock.ExitReadLock ();
			}
		}

		static BuildManagerCacheItem GetCachedItemNoLock (string vp)
		{
			BuildManagerCacheItem ret;
			if (buildCache.TryGetValue (vp, out ret))
				return ret;
			
			return null;
		}
		
		internal static Type GetCodeDomProviderType (BuildProvider provider)
		{
			CompilerType codeCompilerType;
			Type codeDomProviderType = null;

			codeCompilerType = provider.CodeCompilerType;
			if (codeCompilerType != null)
				codeDomProviderType = codeCompilerType.CodeDomProviderType;
				
			if (codeDomProviderType == null)
				throw new HttpException (String.Concat ("Provider '", provider, " 'fails to specify the compiler type."));

			return codeDomProviderType;
		}

		static Type GetPrecompiledType (string virtualPath)
		{
			if (precompiled == null || precompiled.Count == 0)
				return null;

			PreCompilationData pc_data;
			var vp = new VirtualPath (virtualPath);
			if (!precompiled.TryGetValue (vp.Absolute, out pc_data))
				if (!precompiled.TryGetValue (virtualPath, out pc_data))
					return null;
				
			if (pc_data.Type == null)
				pc_data.Type = Type.GetType (pc_data.TypeName + ", " + pc_data.AssemblyFileName, true);
			return pc_data.Type;
		}

		internal static Type GetPrecompiledApplicationType ()
		{
			if (!is_precompiled)
				return null;

			string appVp = VirtualPathUtility.AppendTrailingSlash (HttpRuntime.AppDomainAppVirtualPath);
			Type apptype = GetPrecompiledType (VirtualPathUtility.Combine (appVp, "global.asax"));
			if (apptype == null)
				apptype = GetPrecompiledType (VirtualPathUtility.Combine (appVp, "Global.asax"));
			return apptype;
		}

		public static Assembly GetCompiledAssembly (string virtualPath)
		{
			return GetCompiledAssembly (GetAbsoluteVirtualPath (virtualPath));
		}

		internal static Assembly GetCompiledAssembly (VirtualPath virtualPath)
		{
			string vpabsolute = virtualPath.Absolute;
			if (is_precompiled) {
				Type type = GetPrecompiledType (vpabsolute);
				if (type != null)
					return type.Assembly;
			}
			BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
			if (bmci != null)
				return bmci.BuiltAssembly;

			Build (virtualPath);
			bmci = GetCachedItem (vpabsolute);
			if (bmci != null)
				return bmci.BuiltAssembly;
			
			return null;
		}
		
		public static Type GetCompiledType (string virtualPath)
		{
			return GetCompiledType (GetAbsoluteVirtualPath (virtualPath));
		}

		internal static Type GetCompiledType (VirtualPath virtualPath)
		{
			string vpabsolute = virtualPath.Absolute;
			if (is_precompiled) {
				Type type = GetPrecompiledType (vpabsolute);
				if (type != null)
					return type;
			}
			BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
			if (bmci != null) {
				ReferenceAssemblyInCompilation (bmci);
				return bmci.Type;
			}

			Build (virtualPath);
			bmci = GetCachedItem (vpabsolute);
			if (bmci != null) {
				ReferenceAssemblyInCompilation (bmci);
				return bmci.Type;
			}

			return null;
		}

		public static string GetCompiledCustomString (string virtualPath)
		{
			return GetCompiledCustomString (GetAbsoluteVirtualPath (virtualPath));
		}
	
		internal static string GetCompiledCustomString (VirtualPath virtualPath) 
		{
			string vpabsolute = virtualPath.Absolute;
			BuildManagerCacheItem bmci = GetCachedItem (vpabsolute);
			if (bmci != null)
				return bmci.CompiledCustomString;
			
			Build (virtualPath);
			bmci = GetCachedItem (vpabsolute);
			if (bmci != null)
				return bmci.CompiledCustomString;
			
			return null;
		}

		internal static CompilerType GetDefaultCompilerTypeForLanguage (string language, CompilationSection configSection)
		{
			return GetDefaultCompilerTypeForLanguage (language, configSection, true);
		}
		
		internal static CompilerType GetDefaultCompilerTypeForLanguage (string language, CompilationSection configSection, bool throwOnMissing)
		{
			// MS throws when accesing a Hashtable, we do here.
			if (language == null || language.Length == 0)
				throw new ArgumentNullException ("language");
				
			CompilationSection config;
			if (configSection == null)
				config = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
			else
				config = configSection;
			
			Compiler compiler = config.Compilers.Get (language);
			CompilerParameters p;
			Type type;
			
			if (compiler != null) {
				type = HttpApplication.LoadType (compiler.Type, true);
				p = new CompilerParameters ();
				p.CompilerOptions = compiler.CompilerOptions;
				p.WarningLevel = compiler.WarningLevel;
				SetCommonParameters (config, p, type, language);
				return new CompilerType (type, p);
			}

			if (CodeDomProvider.IsDefinedLanguage (language)) {
				CompilerInfo info = CodeDomProvider.GetCompilerInfo (language);
				p = info.CreateDefaultCompilerParameters ();
				type = info.CodeDomProviderType;
				SetCommonParameters (config, p, type, language);
				return new CompilerType (type, p);
			}

			if (throwOnMissing)
				throw new HttpException (String.Concat ("No compiler for language '", language, "'."));

			return null;
		}

		public static ICollection GetReferencedAssemblies ()
		{
			if (getReferencedAssembliesInvoked)
				return configReferencedAssemblies;

			if (allowReferencedAssembliesCaching)
				getReferencedAssembliesInvoked = true;
			
			if (configReferencedAssemblies == null)
				configReferencedAssemblies = new List <Assembly> ();
			else if (getReferencedAssembliesInvoked)
				configReferencedAssemblies.Clear ();
			
			CompilationSection compConfig = WebConfigurationManager.GetWebApplicationSection ("system.web/compilation") as CompilationSection;
                        if (compConfig == null)
				return configReferencedAssemblies;
			
                        bool addAssembliesInBin = false;
                        foreach (AssemblyInfo info in compConfig.Assemblies) {
                                if (info.Assembly == "*")
                                        addAssembliesInBin = is_precompiled ? false : true;
                                else
                                        LoadAssembly (info, configReferencedAssemblies);
                        }

			foreach (Assembly topLevelAssembly in TopLevelAssemblies)
				configReferencedAssemblies.Add (topLevelAssembly);

			foreach (string assLocation in WebConfigurationManager.ExtraAssemblies)
				LoadAssembly (assLocation, configReferencedAssemblies);
#if NET_4_0
			if (dynamicallyRegisteredAssemblies != null)
				foreach (Assembly registeredAssembly in dynamicallyRegisteredAssemblies)
					configReferencedAssemblies.Add (registeredAssembly);
#endif
			// Precompiled sites unconditionally load all assemblies from bin/ (fix for
			// bug #502016)
			if (is_precompiled || addAssembliesInBin) {
				foreach (string s in HttpApplication.BinDirectoryAssemblies) {
					try {
						LoadAssembly (s, configReferencedAssemblies);
					} catch (BadImageFormatException) {
						// ignore silently
					}
				}
			}
				
			return configReferencedAssemblies;
		}
		
		// The 2 GetType() overloads work on the global.asax, App_GlobalResources, App_WebReferences or App_Browsers
		public static Type GetType (string typeName, bool throwOnError)
		{
			return GetType (typeName, throwOnError, false);
		}
		
		public static Type GetType (string typeName, bool throwOnError, bool ignoreCase)
		{
			if (String.IsNullOrEmpty (typeName))
				throw new HttpException ("Type name must not be empty.");
			
			Type ret = null;
			Exception ex = null;
			try {
				string wantedAsmName;
				string wantedTypeName;
				int comma = typeName.IndexOf (',');

				if (comma > 0 && comma < typeName.Length - 1) {
					var aname = new AssemblyName (typeName.Substring (comma + 1));
					wantedAsmName = aname.ToString ();
					wantedTypeName = typeName.Substring (0, comma);
				} else {
					wantedAsmName = null;
					wantedTypeName = typeName;
				}

				var assemblies = new List <Assembly> ();
				assemblies.AddRange (BuildManager.GetReferencedAssemblies () as List <Assembly>);
				assemblies.AddRange (TopLevel_Assemblies);
				Type appType = HttpApplicationFactory.AppType;
				if (appType != null)
					assemblies.Add (appType.Assembly);
				
				foreach (Assembly asm in assemblies) {
					if (asm == null)
						continue;

					if (wantedAsmName != null) {
						// So dumb...
						if (String.Compare (wantedAsmName, asm.GetName ().ToString (), StringComparison.Ordinal) == 0) {
							ret = asm.GetType (wantedTypeName, throwOnError, ignoreCase);
							if (ret != null)
								return ret;
						}
						continue;
					}
					
					ret = asm.GetType (wantedTypeName, false, ignoreCase);
					if (ret != null)
						return ret;
				}
			} catch (Exception e) {
				ex = e;
			}

			if (throwOnError)
				throw new HttpException ("Failed to find the specified type.", ex);

			return null;
		}

		public static ICollection GetVirtualPathDependencies (string virtualPath)
		{
			return GetVirtualPathDependencies (virtualPath, null);
		}

		internal static ICollection GetVirtualPathDependencies (string virtualPath, BuildProvider bprovider)
		{
			BuildProvider provider = bprovider;
			if (provider == null) {
				CompilationSection cs = CompilationConfig;
				if (cs == null)
					return null;
				provider = BuildManagerDirectoryBuilder.GetBuildProvider (virtualPath, cs.BuildProviders);
			}
			
			if (provider == null)
				return null;
			
			IDictionary <string, bool> deps =  provider.ExtractDependencies ();
			if (deps == null)
				return null;

			return (ICollection)deps.Keys;
		}

		internal static bool HasCachedItemNoLock (string vp, out bool entryExists)
		{
			BuildManagerCacheItem item;
			
			if (buildCache.TryGetValue (vp, out item)) {
				entryExists = true;
				return item != null;
			}

			entryExists = false;
			return false;
		}
		
		internal static bool HasCachedItemNoLock (string vp)
		{
			bool dummy;
			return HasCachedItemNoLock (vp, out dummy);
		}
		
		internal static bool IgnoreVirtualPath (string virtualPath)
		{
			if (!virtualPathsToIgnoreChecked) {
				lock (virtualPathsToIgnoreLock) {
					if (!virtualPathsToIgnoreChecked)
						LoadVirtualPathsToIgnore ();
					virtualPathsToIgnoreChecked = true;
				}
			}
			
			if (!haveVirtualPathsToIgnore)
				return false;
			
			if (virtualPathsToIgnore.ContainsKey (virtualPath))
				return true;
			
			return false;
		}

		static bool IsSingleBuild (VirtualPath vp, bool recursive)
		{
			if (String.Compare (vp.AppRelative, "~/global.asax", StringComparison.OrdinalIgnoreCase) == 0)
				return true;

			if (!BatchMode)
				return true;
			
			return recursive;
		}
		
		static void LoadAssembly (string path, List <Assembly> al)
		{
			AddAssembly (Assembly.LoadFrom (path), al);
		}

		static void LoadAssembly (AssemblyInfo info, List <Assembly> al)
		{
			AddAssembly (Assembly.Load (info.Assembly), al);
		}
		
		static void LoadVirtualPathsToIgnore ()
		{
			NameValueCollection appSettings = WebConfigurationManager.AppSettings;
			if (appSettings == null)
				return;

			string pathsFromConfig = appSettings ["MonoAspnetBatchCompileIgnorePaths"];
			string pathsFromFile = appSettings ["MonoAspnetBatchCompileIgnoreFromFile"];

			if (!String.IsNullOrEmpty (pathsFromConfig)) {
				string[] paths = pathsFromConfig.Split (virtualPathsToIgnoreSplitChars);
				string path;
				
				foreach (string p in paths) {
					path = p.Trim ();
					if (path.Length == 0)
						continue;

					AddPathToIgnore (path);
				}
			}

			if (!String.IsNullOrEmpty (pathsFromFile)) {
				string realpath;
				HttpContext ctx = HttpContext.Current;
				HttpRequest req = ctx != null ? ctx.Request : null;

				if (req == null)
					throw new HttpException ("Missing context, cannot continue.");

				realpath = req.MapPath (pathsFromFile);
				if (!File.Exists (realpath))
					return;

				string[] paths = File.ReadAllLines (realpath);
				if (paths == null || paths.Length == 0)
					return;

				string path;
				foreach (string p in paths) {
					path = p.Trim ();
					if (path.Length == 0)
						continue;

					AddPathToIgnore (path);
				}
			}
		}

		static void OnEntryRemoved (string vp)
		{
			BuildManagerRemoveEntryEventHandler eh = events [buildManagerRemoveEntryEvent] as BuildManagerRemoveEntryEventHandler;

			if (eh != null)
				eh (new BuildManagerRemoveEntryEventArgs (vp, HttpContext.Current));
		}
		
		static void OnVirtualPathChanged (string key, object value, CacheItemRemovedReason removedReason)
		{
			string virtualPath;

			if (StrUtils.StartsWith (key, BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX))
				virtualPath = key.Substring (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX_LENGTH);
			else
				return;
			
			try {
				buildCacheLock.EnterWriteLock ();
				if (HasCachedItemNoLock (virtualPath)) {
					buildCache [virtualPath] = null;
					OnEntryRemoved (virtualPath);
				}
			} finally {
				buildCacheLock.ExitWriteLock ();
			}
		}
		
		static void ReferenceAssemblyInCompilation (BuildManagerCacheItem bmci)
		{
			if (recursionDepth == 0 || referencedAssemblies.Contains (bmci.BuiltAssembly))
				return;

			referencedAssemblies.Add (bmci.BuiltAssembly);
		}
		
		static void RemoveFailedAssemblies (string requestedVirtualPath, CompilationException ex, AssemblyBuilder abuilder,
						    BuildProviderGroup group, CompilerResults results, bool debug)
		{
			StringBuilder sb;
			string newline;
			
			if (debug) {
				newline = Environment.NewLine;
				sb = new StringBuilder ("Compilation of certain files in a batch failed. Another attempt to compile the batch will be made." + newline);
				sb.Append ("Since you're running in debug mode, here's some more information about the error:" + newline);
			} else {
				newline = null;
				sb = null;
			}
			
			var failedBuildProviders = new List <BuildProvider> ();
			BuildProvider bp;
			HttpContext ctx = HttpContext.Current;
			HttpRequest req = ctx != null ? ctx.Request : null;
			bool rethrow = false;
			
			foreach (CompilerError error in results.Errors) {
				if (error.IsWarning)
					continue;
				
				bp = abuilder.GetBuildProviderForPhysicalFilePath (error.FileName);
				if (bp == null) {
					bp = FindBuildProviderForPhysicalPath (error.FileName, group, req);
					if (bp == null)
						continue;
				}

				if (String.Compare (bp.VirtualPath, requestedVirtualPath, StringComparison.Ordinal) == 0)
					rethrow = true;

				if (!failedBuildProviders.Contains (bp)) {
					failedBuildProviders.Add (bp);
					if (sb != null)
						sb.AppendFormat ("\t{0}{1}", bp.VirtualPath, newline);
				}

				if (sb != null)
					sb.AppendFormat ("\t\t{0}{1}", error, newline);
			}

			foreach (BuildProvider fbp in failedBuildProviders)
				group.Remove (fbp);
			
			if (sb != null) {
				sb.AppendFormat ("{0}The following exception has been thrown for the file(s) listed above:{0}{1}",
						 newline, ex.ToString ());
				ShowDebugModeMessage (sb.ToString ());
				sb = null;
			}

			if (rethrow)
				throw new HttpException ("Compilation failed.", ex);
		}
		
		static void SetCommonParameters (CompilationSection config, CompilerParameters p, Type compilerType, string language)
		{
			p.IncludeDebugInformation = config.Debug;
			MonoSettingsSection mss = WebConfigurationManager.GetSection ("system.web/monoSettings") as MonoSettingsSection;
			if (mss == null || !mss.UseCompilersCompatibility)
				return;

			Compiler compiler = mss.CompilersCompatibility.Get (language);
			if (compiler == null)
				return;

			Type type = HttpApplication.LoadType (compiler.Type, false);
			if (type != compilerType)
				return;

			p.CompilerOptions = String.Concat (p.CompilerOptions, " ", compiler.CompilerOptions);
		}

		static void ShowDebugModeMessage (string msg)
		{
			if (suppressDebugModeMessages)
				return;
			
			Console.Error.WriteLine ();
			Console.Error.WriteLine ("******* DEBUG MODE MESSAGE *******");
			Console.Error.WriteLine (msg);
			Console.Error.WriteLine ("******* DEBUG MODE MESSAGE *******");
			Console.Error.WriteLine ();
		}

		static void StoreInCache (BuildProvider bp, Assembly compiledAssembly, CompilerResults results)
		{
			string virtualPath = bp.VirtualPath;
			var item = new BuildManagerCacheItem (compiledAssembly, bp, results);
			
			if (buildCache.ContainsKey (virtualPath))
				buildCache [virtualPath] = item;
			else
				buildCache.Add (virtualPath, item);
			
			HttpContext ctx = HttpContext.Current;
			HttpRequest req = ctx != null ? ctx.Request : null;
			CacheDependency dep;
			
			if (req != null) {
				IDictionary <string, bool> deps = bp.ExtractDependencies ();
				var files = new List <string> ();
				string physicalPath;

				physicalPath = req.MapPath (virtualPath);
				if (File.Exists (physicalPath))
					files.Add (physicalPath);
				
				if (deps != null && deps.Count > 0) {
					foreach (var d in deps) {
						physicalPath = req.MapPath (d.Key);
						if (!File.Exists (physicalPath))
							continue;
						if (!files.Contains (physicalPath))
							files.Add (physicalPath);
					}
				}

				dep = new CacheDependency (files.ToArray ());
			} else
				dep = null;

			HttpRuntime.InternalCache.Add (BUILD_MANAGER_VIRTUAL_PATH_CACHE_PREFIX + virtualPath,
						       true,
						       dep,
						       Cache.NoAbsoluteExpiration,
						       Cache.NoSlidingExpiration,
						       CacheItemPriority.High,
						       new CacheItemRemovedCallback (OnVirtualPathChanged));
		}
	}
}