File: HttpRuntime.cs

package info (click to toggle)
mono 2.6.7-5.1%2Bdeb6u2
  • links: PTS, VCS
  • area: main
  • in suites: squeeze-lts
  • size: 327,392 kB
  • ctags: 413,647
  • sloc: cs: 2,472,296; xml: 1,768,594; ansic: 350,669; sh: 13,676; makefile: 8,640; perl: 1,784; asm: 717; cpp: 209; python: 146; sql: 81; sed: 16
file content (795 lines) | stat: -rw-r--r-- 22,724 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
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
//
// System.Web.HttpRuntime.cs 
// 
// Author:
//	Miguel de Icaza (miguel@novell.com)
//
//
// Copyright (C) 2005 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.
//

//
// TODO: Call HttpRequest.CloseInputStream when we finish a request, as we are using the IntPtr stream.
//
using System.IO;
using System.Text;
using System.Globalization;
using System.Collections;
using System.Reflection;
using System.Security;
using System.Security.Permissions;
using System.Web.Caching;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.Util;
#if MONOWEB_DEP
using Mono.Web.Util;
#endif
using System.Threading;
#if TARGET_J2EE
using Mainsoft.Web;
#endif

#if NET_2_0 && !TARGET_JVM
using System.CodeDom.Compiler;
using System.Web.Compilation;
#endif

namespace System.Web {
	
	// CAS - no InheritanceDemand here as the class is sealed
	[AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
	public sealed class HttpRuntime {
		static bool caseInsensitive;
		static bool runningOnWindows;
		static bool isunc;
		static string monoVersion;
		static bool domainUnloading;
		
#if TARGET_J2EE
		static QueueManager queue_manager { get { return _runtime._queue_manager; } }
		static TraceManager trace_manager { get { return _runtime._trace_manager; } }
		static Cache cache { get { return _runtime._cache; } }
		static Cache internalCache { get { return _runtime._internalCache; } }
		static WaitCallback do_RealProcessRequest;
		
		QueueManager _queue_manager;
		TraceManager _trace_manager;
		Cache _cache;
		Cache _internalCache;

		public HttpRuntime ()
		{
			WebConfigurationManager.Init ();
			_queue_manager = new QueueManager ();
			_trace_manager = new TraceManager ();
			_cache = new Cache ();
			_internalCache = new Cache();
			_internalCache.DependencyCache = _cache;
		}

		static HttpRuntime _runtimeInstance {
			get {
				HttpRuntime runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
				if (runtime == null)
					lock (typeof (HttpRuntime)) {
						runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
						if (runtime == null) {
							runtime = new HttpRuntime ();
							AppDomain.CurrentDomain.SetData ("HttpRuntime", runtime);
						}
					}
				return runtime;
			}
		}
		static HttpRuntime _runtime
		{
			get
			{
				if (HttpContext.Current != null)
					return HttpContext.Current.HttpRuntimeInstance;
				else
					return _runtimeInstance;
			}
		}
#else
		static QueueManager queue_manager;
		static TraceManager trace_manager;
		static Cache cache;
		static Cache internalCache;
		static WaitCallback do_RealProcessRequest;
		static Exception initialException;
		static bool firstRun;
		
#if NET_2_0
		static bool assemblyMappingEnabled;
		static object assemblyMappingLock = new object ();
		static object appOfflineLock = new object ();
#endif
		
#if ONLY_1_1
		[SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
#endif
		public HttpRuntime ()
		{

		}
#endif

		static HttpRuntime ()
		{
			PlatformID pid = Environment.OSVersion.Platform;
			runningOnWindows = ((int) pid != 128
#if NET_2_0
					    && pid != PlatformID.Unix && pid != PlatformID.MacOSX
#endif
			);

			if (runningOnWindows) {
				caseInsensitive = true;
				if (AppDomainAppPath != null)
					isunc = new Uri (AppDomainAppPath).IsUnc;
			} else {
				string mono_iomap = Environment.GetEnvironmentVariable ("MONO_IOMAP");
				if (mono_iomap != null) {
					if (mono_iomap == "all")
						caseInsensitive = true;
					else {
						string[] parts = mono_iomap.Split (':');
						foreach (string p in parts) {
							if (p == "all" || p == "case") {
								caseInsensitive = true;
								break;
							}
						}
					}
				}
			}

			Type monoRuntime = Type.GetType ("Mono.Runtime", false);
			monoVersion = null;
			if (monoRuntime != null) {
				MethodInfo mi = monoRuntime.GetMethod ("GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic);
				if (mi != null)
					monoVersion = mi.Invoke (null, new object [0]) as string;
			}

			if (monoVersion == null)
				monoVersion = Environment.Version.ToString ();
			
#if !TARGET_J2EE
			firstRun = true;
#if NET_2_0
			try {
				WebConfigurationManager.Init ();
#if MONOWEB_DEP
				SettingsMappingManager.Init ();
#endif
			} catch (Exception ex) {
				initialException = ex;
			}
#endif

			// The classes in whose constructors exceptions may be thrown, should be handled the same way QueueManager
			// and TraceManager are below. The constructors themselves MUST NOT throw any exceptions - we MUST be sure
			// the objects are created here. The exceptions will be dealt with below, in RealProcessRequest.
			queue_manager = new QueueManager ();
			if (queue_manager.HasException)
				initialException = queue_manager.InitialException;

			trace_manager = new TraceManager ();
			if (trace_manager.HasException)
					initialException = trace_manager.InitialException;

			cache = new Cache ();
			internalCache = new Cache ();
			internalCache.DependencyCache = cache;
#endif
			do_RealProcessRequest = new WaitCallback (RealProcessRequest);
		}
		
#region AppDomain handling
		internal static bool DomainUnloading {
			get { return domainUnloading; }
		}
		
		//
		// http://radio.weblogs.com/0105476/stories/2002/07/12/executingAspxPagesWithoutAWebServer.html
		//
		public static string AppDomainAppId {
			[AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
			get {
				//
				// This value should not change across invocations
				//
				string dirname = (string) AppDomain.CurrentDomain.GetData (".appId");
				if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
					new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
				}
				return dirname;
			}
		}

		// Physical directory for the application
		public static string AppDomainAppPath {
			get {
				string dirname = (string) AppDomain.CurrentDomain.GetData (".appPath");
				if (SecurityManager.SecurityEnabled) {
					new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
				}
				return dirname;
			}
		}

		public static string AppDomainAppVirtualPath {
			get {
				return (string) AppDomain.CurrentDomain.GetData (".appVPath");
			}
		}

		public static string AppDomainId {
			[AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
			get {
				return (string) AppDomain.CurrentDomain.GetData (".domainId");
			}
		}

		public static string AspInstallDirectory {
			get {
				string dirname = (string) AppDomain.CurrentDomain.GetData (".hostingInstallDir");
				if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
					new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
				}
				return dirname;
			}
		}
#endregion

		static string _actual_bin_directory;
		public static string BinDirectory {
			get {
				if (_actual_bin_directory == null) {
					string[] parts = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split (';');
					string mypath = AppDomainAppPath;
					string tmp;
					
					foreach (string p in parts) {
						tmp = Path.Combine (mypath, p);
						if (Directory.Exists (tmp)) {
							_actual_bin_directory = tmp;
							break;
						}
					}

					if (_actual_bin_directory == null)
						_actual_bin_directory = Path.Combine (mypath, "bin");

					if (_actual_bin_directory [_actual_bin_directory.Length - 1] != Path.DirectorySeparatorChar)
						_actual_bin_directory += Path.DirectorySeparatorChar;
				}
				
				if (SecurityManager.SecurityEnabled)
					new FileIOPermission (FileIOPermissionAccess.PathDiscovery, _actual_bin_directory).Demand ();

				return _actual_bin_directory;
			}
		}

		public static Cache Cache {
			get {
				return cache;
			}
		}

		internal static Cache InternalCache {
			get {
				return internalCache;
			}
		}
		
		public static string ClrInstallDirectory {
			get {
				string dirname = Path.GetDirectoryName (typeof (Object).Assembly.Location);
				if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
					new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
				}
				return dirname;
			}
		}

		public static string CodegenDir {
			get {
				string dirname = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
				if (SecurityManager.SecurityEnabled) {
					new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
				}
				return dirname;
			}
		}

		public static bool IsOnUNCShare {
			[AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
			get {
				return isunc;
			}
		}

		public static string MachineConfigurationDirectory {
			get {
				string dirname = Path.GetDirectoryName (ICalls.GetMachineConfigPath ());
				if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
					new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
				}
				return dirname;
			}
		}

		
		[SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
		public static void Close ()
		{
			// Remove all items from cache.
		}

		internal static HttpWorkerRequest QueuePendingRequest (bool started_internally)
		{
			HttpWorkerRequest next = queue_manager.GetNextRequest (null);
			if (next == null)
				return null;

			if (!started_internally) {
				next.StartedInternally = true;
				ThreadPool.QueueUserWorkItem (do_RealProcessRequest, next);
				return null;
			}
			return next;
		}

#if !TARGET_J2EE
#if NET_2_0
		static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
		static string app_offline_file;
		
		static bool AppIsOffline (HttpContext context)
		{
			if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
				return false;

			HttpResponse response = context.Response;
			response.Clear ();
			response.ContentType = "text/html";
			response.ExpiresAbsolute = DateTime.UtcNow;
			response.StatusCode = 503;
			response.TransmitFile (app_offline_file, true);
			
			context.Request.ReleaseResources ();
			context.Response.ReleaseResources ();
			HttpContext.Current = null;
			HttpApplication.requests_total_counter.Increment ();
			
			return true;
		}

		static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
		{
			AppOfflineFileChanged (sender, args);
		}

		static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
		{
			lock (appOfflineLock) {
				bool offline;
				
				switch (args.ChangeType) {
					case WatcherChangeTypes.Created:
					case WatcherChangeTypes.Changed:
						offline = true;
						break;

					case WatcherChangeTypes.Deleted:
						offline = false;
						break;

					case WatcherChangeTypes.Renamed:
						RenamedEventArgs rargs = args as RenamedEventArgs;

						if (rargs != null &&
						    String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
							offline = true;
						else
							offline = false;
						break;

					default:
						offline = false;
						break;
				}
				SetOfflineMode (offline, args.FullPath);
			}
		}

		static void SetOfflineMode (bool offline, string filePath)
		{
			if (!offline) {
				app_offline_file = null;
				if (HttpApplicationFactory.ApplicationDisabled)
					HttpRuntime.UnloadAppDomain ();
			} else {
				app_offline_file = filePath;
				HttpApplicationFactory.DisableWatchers ();
				HttpApplicationFactory.ApplicationDisabled = true;
				InternalCache.InvokePrivateCallbacks ();
				HttpApplicationFactory.Dispose ();
			}
		}
		
 		static void SetupOfflineWatch ()
		{
			lock (appOfflineLock) {
				FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
				RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);

				string app_dir = AppDomainAppPath;
				ArrayList watchers = new ArrayList ();
				FileSystemWatcher watcher;
				string offlineFile = null, tmp;
				
				foreach (string f in app_offline_files) {
					watcher = new FileSystemWatcher ();
					watcher.Path = Path.GetDirectoryName (app_dir);
					watcher.Filter = Path.GetFileName (f);
					watcher.NotifyFilter |= NotifyFilters.Size;
					watcher.Deleted += seh;
					watcher.Changed += seh;
					watcher.Created += seh;
					watcher.Renamed += reh;
					watcher.EnableRaisingEvents = true;
					
					watchers.Add (watcher);

					tmp = Path.Combine (app_dir, f);
					if (File.Exists (tmp))
						offlineFile = tmp;
				}

				if (offlineFile != null)
					SetOfflineMode (true, offlineFile);
			}
		}
#endif
#endif
		
		static void RealProcessRequest (object o)
		{
			HttpWorkerRequest req = (HttpWorkerRequest) o;
			bool started_internally = req.StartedInternally;
			do {
				Process (req);
				req = QueuePendingRequest (started_internally);
			} while (started_internally && req != null);
		}

		static void Process (HttpWorkerRequest req)
		{
#if TARGET_J2EE
			HttpContext context = HttpContext.Current;
			if (context == null)
				context = new HttpContext (req);
			else
				context.SetWorkerRequest (req);
#else
			HttpContext context = new HttpContext (req);
#endif
			HttpContext.Current = context;
			bool error = false;
#if !TARGET_J2EE
			if (firstRun) {
#if NET_2_0
				SetupOfflineWatch ();
#endif
				firstRun = false;
				if (initialException != null) {
					FinishWithException (req, new HttpException ("Initial exception", initialException));
					error = true;
				}
			}

#if NET_2_0
			if (AppIsOffline (context))
				return;
#endif
#endif
			
			//
			// Get application instance (create or reuse an instance of the correct class)
			//
			HttpApplication app = null;
			if (!error) {
				try {
					app = HttpApplicationFactory.GetApplication (context);
				} catch (Exception e) {
					FinishWithException (req, new HttpException ("", e));
					error = true;
				}
			}
			
			if (error) {
				context.Request.ReleaseResources ();
				context.Response.ReleaseResources ();
				HttpContext.Current = null;
			} else {
				context.ApplicationInstance = app;

				//
				// Ask application to service the request
				//
				
#if TARGET_J2EE
				IHttpAsyncHandler ihah = app;
				if (context.Handler == null)
					ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
				else
					app.Tick ();
				//ihh.ProcessRequest (context);
				IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
				if (extHandler != null && !extHandler.IsCompleted)
					return;
				if (context.Error is UnifyRequestException)
					return;

				ihah.EndProcessRequest (null);
#else
				IHttpHandler ihh = app;
//				IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
//				ihah.EndProcessRequest (appiar);
				ihh.ProcessRequest (context);
#endif

				HttpApplicationFactory.Recycle (app);
			}
		}
		
		//
		// ProcessRequest method is executed in the AppDomain of the application
		//
		// Observations:
		//    ProcessRequest does not guarantee that `wr' will be processed synchronously,
		//    the request can be queued and processed later.
		//
		[AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
		public static void ProcessRequest (HttpWorkerRequest wr)
		{
			if (wr == null)
				throw new ArgumentNullException ("wr");
			//
			// Queue our request, fetch the next available one from the queue
			//
			HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
			if (request == null)
				return;

			QueuePendingRequest (false);
			RealProcessRequest (request);
		}

#if TARGET_J2EE
		//
		// Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
		//
		static void request_processed (IAsyncResult iar)
		{
			HttpContext context = (HttpContext) iar.AsyncState;

			context.Request.ReleaseResources ();
			context.Response.ReleaseResources ();
		}
#endif
		
#if TARGET_JVM
		[MonoNotSupported ("UnloadAppDomain is not supported")]
		public static void UnloadAppDomain ()
		{
			throw new NotImplementedException ("UnloadAppDomain is not supported");
		}
#else
		//
		// Called when we are shutting down or we need to reload an application
		// that has been modified (touch global.asax) 
		//
		[SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
		public static void UnloadAppDomain ()
		{
			//
			// TODO: call ReleaseResources
			//
			domainUnloading = true;
			ThreadPool.QueueUserWorkItem (new WaitCallback (ShutdownAppDomain), null);
		}
#endif
		//
		// Shuts down the AppDomain
		//
		static void ShutdownAppDomain (object args)
		{
			queue_manager.Dispose ();
			// This will call Session_End if needed.
			InternalCache.InvokePrivateCallbacks ();
			// Kill our application.
			HttpApplicationFactory.Dispose ();
			ThreadPool.QueueUserWorkItem (new WaitCallback (DoUnload), null);
		}

		static void DoUnload (object state)
		{
#if TARGET_J2EE
			// No unload support for appdomains under Grasshopper
#else
			AppDomain.Unload (AppDomain.CurrentDomain);
#endif
		}

		static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
			"<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
			"<h1>Server Unavailable</h1>\n" +
			"</body></html>\n";

		static void FinishWithException (HttpWorkerRequest wr, HttpException e)
		{
			int code = e.GetHttpCode ();
			wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
			wr.SendUnknownResponseHeader ("Connection", "close");
			Encoding enc = Encoding.ASCII;
			wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
			string msg = e.GetHtmlErrorMessage ();
			byte [] contentBytes = enc.GetBytes (msg);
			wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
			wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
			wr.FlushResponse (true);
			wr.CloseConnection ();
			HttpApplication.requests_total_counter.Increment ();
		}

		//
		// This is called from the QueueManager if a request
		// can not be processed (load, no resources, or
		// appdomain unload).
		//
		static internal void FinishUnavailable (HttpWorkerRequest wr)
		{
			wr.SendStatus (503, "Service unavailable");
			wr.SendUnknownResponseHeader ("Connection", "close");
			Encoding enc = Encoding.ASCII;
			wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
			byte [] contentBytes = enc.GetBytes (content503);
			wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
			wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
			wr.FlushResponse (true);
			wr.CloseConnection ();
			HttpApplication.requests_total_counter.Increment ();
		}

#if NET_2_0 
#if !TARGET_J2EE
		static internal void WritePreservationFile (Assembly asm, string genericNameBase)
		{
			if (asm == null)
				throw new ArgumentNullException ("asm");
			if (String.IsNullOrEmpty (genericNameBase))
				throw new ArgumentNullException ("genericNameBase");

			string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
							genericNameBase + ".compiled");
			PreservationFile pf = new PreservationFile ();
			try {
				pf.VirtualPath = String.Concat ("/", genericNameBase, "/");

				AssemblyName an = asm.GetName ();
				pf.Assembly = an.Name;
				pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
				pf.Save (compiled);
			} catch (Exception ex) {
				throw new HttpException (
					String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
					ex);
			}
		}
		
		static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
		{
			AssemblyName an = new AssemblyName (e.Name);
			string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
			string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");

			if (!File.Exists (compiled))
				return null;

			PreservationFile pf;
			try {
				pf = new PreservationFile (compiled);
			} catch (Exception ex) {
				throw new HttpException (
					String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
					ex);
			}
			
			Assembly ret = null;
			try {
				string asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
				ret = Assembly.LoadFrom (asmPath);
			} catch (Exception) {
				// ignore
			}
			
			return ret;
		}
		
		internal static void EnableAssemblyMapping (bool enable)
		{
			lock (assemblyMappingLock) {
				if (assemblyMappingEnabled == enable)
					return;
				if (enable)
					AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
				else
					AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
				assemblyMappingEnabled = enable;
			}
		}
#endif // #if !TARGET_J2EE
#endif
		internal static string MonoVersion {
			get { return monoVersion; }
		}
		
		internal static bool RunningOnWindows {
			get { return runningOnWindows; }
		}

		internal static bool CaseInsensitive {
			get { return caseInsensitive; }
		}

		internal static bool IsDebuggingEnabled {
			get {
#if NET_2_0
				CompilationSection cs = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
				if (cs != null)
					return cs.Debug;

				return false;
#else
				try {
					return CompilationConfiguration.GetInstance (HttpContext.Current).Debug;
				} catch {
					return false;
				}
#endif
			}
		}
		
		internal static TraceManager TraceManager {
			get {
				return trace_manager;
			}
		}
	}
}