2010-02-03 Marek Habersack <mhabersack@novell.com>
[mono.git] / mcs / class / System.Web / System.Web / HttpRuntime.cs
1 //
2 // System.Web.HttpRuntime.cs 
3 // 
4 // Authors:
5 //      Miguel de Icaza (miguel@novell.com)
6 //      Marek Habersack <mhabersack@novell.com>
7 //
8 //
9 // Copyright (C) 2005-2010 Novell, Inc (http://www.novell.com)
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 //
32 // TODO: Call HttpRequest.CloseInputStream when we finish a request, as we are using the IntPtr stream.
33 //
34 using System.IO;
35 using System.Text;
36 using System.Globalization;
37 using System.Collections;
38 using System.Reflection;
39 using System.Security;
40 using System.Security.Permissions;
41 using System.Web.Caching;
42 using System.Web.Configuration;
43 using System.Web.UI;
44 using System.Web.Util;
45 #if MONOWEB_DEP
46 using Mono.Web.Util;
47 #endif
48 using System.Threading;
49 #if TARGET_J2EE
50 using Mainsoft.Web;
51 #else
52 using System.CodeDom.Compiler;
53 using System.Web.Compilation;
54 #endif
55
56 namespace System.Web
57 {       
58         // CAS - no InheritanceDemand here as the class is sealed
59         [AspNetHostingPermission (SecurityAction.LinkDemand, Level = AspNetHostingPermissionLevel.Minimal)]
60         public sealed class HttpRuntime
61         {
62                 static bool caseInsensitive;
63                 static bool runningOnWindows;
64                 static bool isunc;
65                 static string monoVersion;
66                 
67 #if TARGET_J2EE
68                 static QueueManager queue_manager { get { return _runtime._queue_manager; } }
69                 static TraceManager trace_manager { get { return _runtime._trace_manager; } }
70                 static Cache cache { get { return _runtime._cache; } }
71                 static Cache internalCache { get { return _runtime._internalCache; } }
72                 static WaitCallback do_RealProcessRequest;
73                 
74                 QueueManager _queue_manager;
75                 TraceManager _trace_manager;
76                 Cache _cache;
77                 Cache _internalCache;
78
79                 public HttpRuntime ()
80                 {
81                         WebConfigurationManager.Init ();
82                         _queue_manager = new QueueManager ();
83                         _trace_manager = new TraceManager ();
84                         _cache = new Cache ();
85                         _internalCache = new Cache();
86                         _internalCache.DependencyCache = _cache;
87                 }
88
89                 static HttpRuntime _runtimeInstance {
90                         get {
91                                 HttpRuntime runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
92                                 if (runtime == null)
93                                         lock (typeof (HttpRuntime)) {
94                                                 runtime = (HttpRuntime) AppDomain.CurrentDomain.GetData ("HttpRuntime");
95                                                 if (runtime == null) {
96                                                         runtime = new HttpRuntime ();
97                                                         AppDomain.CurrentDomain.SetData ("HttpRuntime", runtime);
98                                                 }
99                                         }
100                                 return runtime;
101                         }
102                 }
103                 static HttpRuntime _runtime
104                 {
105                         get
106                         {
107                                 if (HttpContext.Current != null)
108                                         return HttpContext.Current.HttpRuntimeInstance;
109                                 else
110                                         return _runtimeInstance;
111                         }
112                 }
113 #else
114                 static QueueManager queue_manager;
115                 static TraceManager trace_manager;
116                 static Cache cache;
117                 static Cache internalCache;
118                 static WaitCallback do_RealProcessRequest;
119                 static Exception initialException;
120                 static bool firstRun;
121                 static bool assemblyMappingEnabled;
122                 static object assemblyMappingLock = new object ();
123                 static object appOfflineLock = new object ();
124                 
125                 public HttpRuntime ()
126                 {
127
128                 }
129 #endif
130
131                 static HttpRuntime ()
132                 {
133                         PlatformID pid = Environment.OSVersion.Platform;
134                         runningOnWindows = ((int) pid != 128 && pid != PlatformID.Unix && pid != PlatformID.MacOSX);
135
136                         if (runningOnWindows) {
137                                 caseInsensitive = true;
138                                 if (AppDomainAppPath != null)
139                                         isunc = new Uri (AppDomainAppPath).IsUnc;
140                         } else {
141                                 string mono_iomap = Environment.GetEnvironmentVariable ("MONO_IOMAP");
142                                 if (mono_iomap != null) {
143                                         if (mono_iomap == "all")
144                                                 caseInsensitive = true;
145                                         else {
146                                                 string[] parts = mono_iomap.Split (':');
147                                                 foreach (string p in parts) {
148                                                         if (p == "all" || p == "case") {
149                                                                 caseInsensitive = true;
150                                                                 break;
151                                                         }
152                                                 }
153                                         }
154                                 }
155                         }
156
157                         Type monoRuntime = Type.GetType ("Mono.Runtime", false);
158                         monoVersion = null;
159                         if (monoRuntime != null) {
160                                 MethodInfo mi = monoRuntime.GetMethod ("GetDisplayName", BindingFlags.Static | BindingFlags.NonPublic);
161                                 if (mi != null)
162                                         monoVersion = mi.Invoke (null, new object [0]) as string;
163                         }
164
165                         if (monoVersion == null)
166                                 monoVersion = Environment.Version.ToString ();
167                         
168 #if !TARGET_J2EE
169                         firstRun = true;
170                         try {
171                                 WebConfigurationManager.Init ();
172 #if MONOWEB_DEP
173                                 SettingsMappingManager.Init ();
174 #endif
175                         } catch (Exception ex) {
176                                 initialException = ex;
177                         }
178
179                         // The classes in whose constructors exceptions may be thrown, should be handled the same way QueueManager
180                         // and TraceManager are below. The constructors themselves MUST NOT throw any exceptions - we MUST be sure
181                         // the objects are created here. The exceptions will be dealt with below, in RealProcessRequest.
182                         queue_manager = new QueueManager ();
183                         if (queue_manager.HasException)
184                                 initialException = queue_manager.InitialException;
185
186                         trace_manager = new TraceManager ();
187                         if (trace_manager.HasException)
188                                         initialException = trace_manager.InitialException;
189
190                         cache = new Cache ();
191                         internalCache = new Cache ();
192                         internalCache.DependencyCache = internalCache;
193 #endif
194                         do_RealProcessRequest = new WaitCallback (RealProcessRequest);
195                 }
196                 
197 #region AppDomain handling
198                 //
199                 // http://radio.weblogs.com/0105476/stories/2002/07/12/executingAspxPagesWithoutAWebServer.html
200                 //
201                 public static string AppDomainAppId {
202                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
203                         get {
204                                 //
205                                 // This value should not change across invocations
206                                 //
207                                 string dirname = (string) AppDomain.CurrentDomain.GetData (".appId");
208                                 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
209                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
210                                 }
211                                 return dirname;
212                         }
213                 }
214
215                 // Physical directory for the application
216                 public static string AppDomainAppPath {
217                         get {
218                                 string dirname = (string) AppDomain.CurrentDomain.GetData (".appPath");
219                                 if (SecurityManager.SecurityEnabled) {
220                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
221                                 }
222                                 return dirname;
223                         }
224                 }
225
226                 public static string AppDomainAppVirtualPath {
227                         get {
228                                 return (string) AppDomain.CurrentDomain.GetData (".appVPath");
229                         }
230                 }
231
232                 public static string AppDomainId {
233                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.High)]
234                         get {
235                                 return (string) AppDomain.CurrentDomain.GetData (".domainId");
236                         }
237                 }
238
239                 public static string AspInstallDirectory {
240                         get {
241                                 string dirname = (string) AppDomain.CurrentDomain.GetData (".hostingInstallDir");
242                                 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
243                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
244                                 }
245                                 return dirname;
246                         }
247                 }
248 #endregion
249
250                 static string _actual_bin_directory;
251                 public static string BinDirectory {
252                         get {
253                                 if (_actual_bin_directory == null) {
254                                         string[] parts = AppDomain.CurrentDomain.SetupInformation.PrivateBinPath.Split (';');
255                                         string mypath = AppDomainAppPath;
256                                         string tmp;
257                                         
258                                         foreach (string p in parts) {
259                                                 tmp = Path.Combine (mypath, p);
260                                                 if (Directory.Exists (tmp)) {
261                                                         _actual_bin_directory = tmp;
262                                                         break;
263                                                 }
264                                         }
265
266                                         if (_actual_bin_directory == null)
267                                                 _actual_bin_directory = Path.Combine (mypath, "bin");
268
269                                         if (_actual_bin_directory [_actual_bin_directory.Length - 1] != Path.DirectorySeparatorChar)
270                                                 _actual_bin_directory += Path.DirectorySeparatorChar;
271                                 }
272                                 
273                                 if (SecurityManager.SecurityEnabled)
274                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, _actual_bin_directory).Demand ();
275
276                                 return _actual_bin_directory;
277                         }
278                 }
279
280                 public static Cache Cache {
281                         get {
282                                 return cache;
283                         }
284                 }
285
286                 internal static Cache InternalCache {
287                         get {
288                                 return internalCache;
289                         }
290                 }
291                 
292                 public static string ClrInstallDirectory {
293                         get {
294                                 string dirname = Path.GetDirectoryName (typeof (Object).Assembly.Location);
295                                 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
296                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
297                                 }
298                                 return dirname;
299                         }
300                 }
301
302                 public static string CodegenDir {
303                         get {
304                                 string dirname = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
305                                 if (SecurityManager.SecurityEnabled) {
306                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
307                                 }
308                                 return dirname;
309                         }
310                 }
311
312                 public static bool IsOnUNCShare {
313                         [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Low)]
314                         get {
315                                 return isunc;
316                         }
317                 }
318
319                 public static string MachineConfigurationDirectory {
320                         get {
321                                 string dirname = Path.GetDirectoryName (ICalls.GetMachineConfigPath ());
322                                 if ((dirname != null) && (dirname.Length > 0) && SecurityManager.SecurityEnabled) {
323                                         new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dirname).Demand ();
324                                 }
325                                 return dirname;
326                         }
327                 }
328
329                 
330                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
331                 public static void Close ()
332                 {
333                         // Remove all items from cache.
334                 }
335
336                 internal static HttpWorkerRequest QueuePendingRequest (bool started_internally)
337                 {
338                         HttpWorkerRequest next = queue_manager.GetNextRequest (null);
339                         if (next == null)
340                                 return null;
341
342                         if (!started_internally) {
343                                 next.StartedInternally = true;
344                                 ThreadPool.QueueUserWorkItem (do_RealProcessRequest, next);
345                                 return null;
346                         }
347                         return next;
348                 }
349
350 #if !TARGET_J2EE
351                 static readonly string[] app_offline_files = {"app_offline.htm", "App_Offline.htm", "APP_OFFLINE.HTM"};
352                 static string app_offline_file;
353                 
354                 static bool AppIsOffline (HttpContext context)
355                 {
356                         if (!HttpApplicationFactory.ApplicationDisabled || app_offline_file == null)
357                                 return false;
358
359                         HttpResponse response = context.Response;
360                         response.Clear ();
361                         response.ContentType = "text/html";
362                         response.ExpiresAbsolute = DateTime.UtcNow;
363                         response.StatusCode = 503;
364                         response.TransmitFile (app_offline_file, true);
365                         
366                         context.Request.ReleaseResources ();
367                         context.Response.ReleaseResources ();
368                         HttpContext.Current = null;
369                         HttpApplication.requests_total_counter.Increment ();
370                         
371                         return true;
372                 }
373
374                 static void AppOfflineFileRenamed (object sender, RenamedEventArgs args)
375                 {
376                         AppOfflineFileChanged (sender, args);
377                 }
378
379                 static void AppOfflineFileChanged (object sender, FileSystemEventArgs args)
380                 {
381                         lock (appOfflineLock) {
382                                 bool offline;
383                                 
384                                 switch (args.ChangeType) {
385                                         case WatcherChangeTypes.Created:
386                                         case WatcherChangeTypes.Changed:
387                                                 offline = true;
388                                                 break;
389
390                                         case WatcherChangeTypes.Deleted:
391                                                 offline = false;
392                                                 break;
393
394                                         case WatcherChangeTypes.Renamed:
395                                                 RenamedEventArgs rargs = args as RenamedEventArgs;
396
397                                                 if (rargs != null &&
398                                                     String.Compare (rargs.Name, "app_offline.htm", StringComparison.OrdinalIgnoreCase) == 0)
399                                                         offline = true;
400                                                 else
401                                                         offline = false;
402                                                 break;
403
404                                         default:
405                                                 offline = false;
406                                                 break;
407                                 }
408                                 SetOfflineMode (offline, args.FullPath);
409                         }
410                 }
411
412                 static void SetOfflineMode (bool offline, string filePath)
413                 {
414                         if (!offline) {
415                                 app_offline_file = null;
416                                 if (HttpApplicationFactory.ApplicationDisabled)
417                                         HttpRuntime.UnloadAppDomain ();
418                         } else {
419                                 app_offline_file = filePath;
420                                 HttpApplicationFactory.DisableWatchers ();
421                                 HttpApplicationFactory.ApplicationDisabled = true;
422                                 InternalCache.InvokePrivateCallbacks ();
423                                 HttpApplicationFactory.Dispose ();
424                         }
425                 }
426                 
427                 static void SetupOfflineWatch ()
428                 {
429                         lock (appOfflineLock) {
430                                 FileSystemEventHandler seh = new FileSystemEventHandler (AppOfflineFileChanged);
431                                 RenamedEventHandler reh = new RenamedEventHandler (AppOfflineFileRenamed);
432
433                                 string app_dir = AppDomainAppPath;
434                                 ArrayList watchers = new ArrayList ();
435                                 FileSystemWatcher watcher;
436                                 string offlineFile = null, tmp;
437                                 
438                                 foreach (string f in app_offline_files) {
439                                         watcher = new FileSystemWatcher ();
440                                         watcher.Path = Path.GetDirectoryName (app_dir);
441                                         watcher.Filter = Path.GetFileName (f);
442                                         watcher.NotifyFilter |= NotifyFilters.Size;
443                                         watcher.Deleted += seh;
444                                         watcher.Changed += seh;
445                                         watcher.Created += seh;
446                                         watcher.Renamed += reh;
447                                         watcher.EnableRaisingEvents = true;
448                                         
449                                         watchers.Add (watcher);
450
451                                         tmp = Path.Combine (app_dir, f);
452                                         if (File.Exists (tmp))
453                                                 offlineFile = tmp;
454                                 }
455
456                                 if (offlineFile != null)
457                                         SetOfflineMode (true, offlineFile);
458                         }
459                 }
460 #endif
461                 
462                 static void RealProcessRequest (object o)
463                 {
464                         HttpWorkerRequest req = (HttpWorkerRequest) o;
465                         bool started_internally = req.StartedInternally;
466                         do {
467                                 Process (req);
468                                 req = QueuePendingRequest (started_internally);
469                         } while (started_internally && req != null);
470                 }
471
472                 static void Process (HttpWorkerRequest req)
473                 {
474 #if TARGET_J2EE
475                         HttpContext context = HttpContext.Current;
476                         if (context == null)
477                                 context = new HttpContext (req);
478                         else
479                                 context.SetWorkerRequest (req);
480 #else
481                         HttpContext context = new HttpContext (req);
482 #endif
483                         HttpContext.Current = context;
484                         bool error = false;
485 #if !TARGET_J2EE
486                         if (firstRun) {
487                                 SetupOfflineWatch ();
488                                 firstRun = false;
489                                 if (initialException != null) {
490                                         FinishWithException (req, new HttpException ("Initial exception", initialException));
491                                         error = true;
492                                 }
493                         }
494
495                         if (AppIsOffline (context))
496                                 return;
497 #endif
498                         
499                         //
500                         // Get application instance (create or reuse an instance of the correct class)
501                         //
502                         HttpApplication app = null;
503                         if (!error) {
504                                 try {
505                                         app = HttpApplicationFactory.GetApplication (context);
506                                 } catch (Exception e) {
507                                         FinishWithException (req, new HttpException ("", e));
508                                         error = true;
509                                 }
510                         }
511                         
512                         if (error) {
513                                 context.Request.ReleaseResources ();
514                                 context.Response.ReleaseResources ();
515                                 HttpContext.Current = null;
516                         } else {
517                                 context.ApplicationInstance = app;
518
519                                 //
520                                 // Ask application to service the request
521                                 //
522                                 
523 #if TARGET_J2EE
524                                 IHttpAsyncHandler ihah = app;
525                                 if (context.Handler == null)
526                                         ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
527                                 else
528                                         app.Tick ();
529                                 //ihh.ProcessRequest (context);
530                                 IHttpExtendedHandler extHandler = context.Handler as IHttpExtendedHandler;
531                                 if (extHandler != null && !extHandler.IsCompleted)
532                                         return;
533                                 if (context.Error is UnifyRequestException)
534                                         return;
535
536                                 ihah.EndProcessRequest (null);
537 #else
538                                 IHttpHandler ihh = app;
539 //                              IAsyncResult appiar = ihah.BeginProcessRequest (context, new AsyncCallback (request_processed), context);
540 //                              ihah.EndProcessRequest (appiar);
541                                 ihh.ProcessRequest (context);
542 #endif
543
544                                 HttpApplicationFactory.Recycle (app);
545                         }
546                 }
547                 
548                 //
549                 // ProcessRequest method is executed in the AppDomain of the application
550                 //
551                 // Observations:
552                 //    ProcessRequest does not guarantee that `wr' will be processed synchronously,
553                 //    the request can be queued and processed later.
554                 //
555                 [AspNetHostingPermission (SecurityAction.Demand, Level = AspNetHostingPermissionLevel.Medium)]
556                 public static void ProcessRequest (HttpWorkerRequest wr)
557                 {
558                         if (wr == null)
559                                 throw new ArgumentNullException ("wr");
560                         //
561                         // Queue our request, fetch the next available one from the queue
562                         //
563                         HttpWorkerRequest request = queue_manager.GetNextRequest (wr);
564                         if (request == null)
565                                 return;
566
567                         QueuePendingRequest (false);
568                         RealProcessRequest (request);
569                 }
570
571 #if TARGET_J2EE
572                 //
573                 // Callback to be invoked by IHttpAsyncHandler.BeginProcessRequest
574                 //
575                 static void request_processed (IAsyncResult iar)
576                 {
577                         HttpContext context = (HttpContext) iar.AsyncState;
578
579                         context.Request.ReleaseResources ();
580                         context.Response.ReleaseResources ();
581                 }
582 #endif
583                 
584 #if TARGET_JVM
585                 [MonoNotSupported ("UnloadAppDomain is not supported")]
586                 public static void UnloadAppDomain ()
587                 {
588                         throw new NotImplementedException ("UnloadAppDomain is not supported");
589                 }
590 #else
591                 //
592                 // Called when we are shutting down or we need to reload an application
593                 // that has been modified (touch global.asax) 
594                 //
595                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
596                 public static void UnloadAppDomain ()
597                 {
598                         //
599                         // TODO: call ReleaseResources
600                         //
601                         ThreadPool.QueueUserWorkItem (new WaitCallback (ShutdownAppDomain), null);
602                 }
603 #endif
604                 //
605                 // Shuts down the AppDomain
606                 //
607                 static void ShutdownAppDomain (object args)
608                 {
609                         queue_manager.Dispose ();
610                         // This will call Session_End if needed.
611                         InternalCache.InvokePrivateCallbacks ();
612                         // Kill our application.
613                         HttpApplicationFactory.Dispose ();
614                         ThreadPool.QueueUserWorkItem (new WaitCallback (DoUnload), null);
615                 }
616
617                 static void DoUnload (object state)
618                 {
619 #if TARGET_J2EE
620                         // No unload support for appdomains under Grasshopper
621 #else
622                         AppDomain.Unload (AppDomain.CurrentDomain);
623 #endif
624                 }
625
626                 static string content503 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\n" +
627                         "<html><head>\n<title>503 Server Unavailable</title>\n</head><body>\n" +
628                         "<h1>Server Unavailable</h1>\n" +
629                         "</body></html>\n";
630
631                 static void FinishWithException (HttpWorkerRequest wr, HttpException e)
632                 {
633                         int code = e.GetHttpCode ();
634                         wr.SendStatus (code, HttpWorkerRequest.GetStatusDescription (code));
635                         wr.SendUnknownResponseHeader ("Connection", "close");
636                         Encoding enc = Encoding.ASCII;
637                         wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
638                         string msg = e.GetHtmlErrorMessage ();
639                         byte [] contentBytes = enc.GetBytes (msg);
640                         wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
641                         wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
642                         wr.FlushResponse (true);
643                         wr.CloseConnection ();
644                         HttpApplication.requests_total_counter.Increment ();
645                 }
646
647                 //
648                 // This is called from the QueueManager if a request
649                 // can not be processed (load, no resources, or
650                 // appdomain unload).
651                 //
652                 static internal void FinishUnavailable (HttpWorkerRequest wr)
653                 {
654                         wr.SendStatus (503, "Service unavailable");
655                         wr.SendUnknownResponseHeader ("Connection", "close");
656                         Encoding enc = Encoding.ASCII;
657                         wr.SendUnknownResponseHeader ("Content-Type", "text/html; charset=" + enc.WebName);
658                         byte [] contentBytes = enc.GetBytes (content503);
659                         wr.SendUnknownResponseHeader ("Content-Length", contentBytes.Length.ToString ());
660                         wr.SendResponseFromMemory (contentBytes, contentBytes.Length);
661                         wr.FlushResponse (true);
662                         wr.CloseConnection ();
663                         HttpApplication.requests_total_counter.Increment ();
664                 }
665
666 #if !TARGET_J2EE
667                 static internal void WritePreservationFile (Assembly asm, string genericNameBase)
668                 {
669                         if (asm == null)
670                                 throw new ArgumentNullException ("asm");
671                         if (String.IsNullOrEmpty (genericNameBase))
672                                 throw new ArgumentNullException ("genericNameBase");
673
674                         string compiled = Path.Combine (AppDomain.CurrentDomain.SetupInformation.DynamicBase,
675                                                         genericNameBase + ".compiled");
676                         PreservationFile pf = new PreservationFile ();
677                         try {
678                                 pf.VirtualPath = String.Concat ("/", genericNameBase, "/");
679
680                                 AssemblyName an = asm.GetName ();
681                                 pf.Assembly = an.Name;
682                                 pf.ResultType = BuildResultTypeCode.TopLevelAssembly;
683                                 pf.Save (compiled);
684                         } catch (Exception ex) {
685                                 throw new HttpException (
686                                         String.Format ("Failed to write preservation file {0}", genericNameBase + ".compiled"),
687                                         ex);
688                         }
689                 }
690                 
691                 static Assembly ResolveAssemblyHandler(object sender, ResolveEventArgs e)
692                 {
693                         AssemblyName an = new AssemblyName (e.Name);
694                         string dynamic_base = AppDomain.CurrentDomain.SetupInformation.DynamicBase;
695                         string compiled = Path.Combine (dynamic_base, an.Name + ".compiled");
696
697                         if (!File.Exists (compiled))
698                                 return null;
699
700                         PreservationFile pf;
701                         try {
702                                 pf = new PreservationFile (compiled);
703                         } catch (Exception ex) {
704                                 throw new HttpException (
705                                         String.Format ("Failed to read preservation file {0}", an.Name + ".compiled"),
706                                         ex);
707                         }
708                         
709                         Assembly ret = null;
710                         try {
711                                 string asmPath = Path.Combine (dynamic_base, pf.Assembly + ".dll");
712                                 ret = Assembly.LoadFrom (asmPath);
713                         } catch (Exception) {
714                                 // ignore
715                         }
716                         
717                         return ret;
718                 }
719                 
720                 internal static void EnableAssemblyMapping (bool enable)
721                 {
722                         lock (assemblyMappingLock) {
723                                 if (assemblyMappingEnabled == enable)
724                                         return;
725                                 if (enable)
726                                         AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler (ResolveAssemblyHandler);
727                                 else
728                                         AppDomain.CurrentDomain.AssemblyResolve -= new ResolveEventHandler (ResolveAssemblyHandler);
729                                 assemblyMappingEnabled = enable;
730                         }
731                 }
732 #endif // #if !TARGET_J2EE
733
734                 internal static string MonoVersion {
735                         get { return monoVersion; }
736                 }
737                 
738                 internal static bool RunningOnWindows {
739                         get { return runningOnWindows; }
740                 }
741
742                 internal static bool CaseInsensitive {
743                         get { return caseInsensitive; }
744                 }
745
746                 internal static bool IsDebuggingEnabled {
747                         get {
748                                 CompilationSection cs = WebConfigurationManager.GetSection ("system.web/compilation") as CompilationSection;
749                                 if (cs != null)
750                                         return cs.Debug;
751
752                                 return false;
753                         }
754                 }
755                 
756                 internal static TraceManager TraceManager {
757                         get {
758                                 return trace_manager;
759                         }
760                 }
761         }
762 }