* MainsoftWebApp20.Tomcat.vmwcsproj: converted to csproj
[mono.git] / mcs / class / System.Web / System.Web / HttpApplicationFactory.cs
1 //
2 // System.Web.HttpApplicationFactory
3 //
4 // Author:
5 //      Gonzalo Paniagua Javier (gonzalo@ximian.com)
6 //
7 // (c) 2002,2003 Ximian, Inc. (http://www.ximian.com)
8 // (c) Copyright 2004 Novell, Inc. (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29 using System;
30 using System.Collections;
31 using System.IO;
32 using System.Reflection;
33 using System.Web.UI;
34 using System.Web.SessionState;
35 using System.Web.Configuration;
36
37 #if !TARGET_J2EE
38 using System.Web.Compilation;
39 #else
40 using vmw.common;
41 #endif
42
43 #if NET_2_0 && !TARGET_J2EE
44 using System.CodeDom.Compiler;
45 #endif
46
47 namespace System.Web {
48         class HttpApplicationFactory {
49                 // Initialized in InitType
50 #if TARGET_J2EE
51                 static HttpApplicationFactory theFactory {
52                         get
53                         {
54                                 HttpApplicationFactory factory = (HttpApplicationFactory)AppDomain.CurrentDomain.GetData("HttpApplicationFactory");
55                                 if (factory == null) {
56                                         lock(typeof(HttpApplicationFactory)) {
57                                                 factory = (HttpApplicationFactory)AppDomain.CurrentDomain.GetData("HttpApplicationFactory");
58                                                 if (factory == null) {
59                                                         factory = new HttpApplicationFactory();
60                                                         System.Threading.Thread.Sleep(1);
61                                                         AppDomain.CurrentDomain.SetData("HttpApplicationFactory", factory);
62                                                 }
63                                         }
64                                 }
65                                 return factory;
66                         }
67                 }
68 #else
69                 static HttpApplicationFactory theFactory = new HttpApplicationFactory();
70 #endif
71         
72
73                 MethodInfo session_end;
74                 bool needs_init = true;
75                 bool app_start_needed = true;
76                 Type app_type;
77                 HttpApplicationState app_state;
78                 Hashtable app_event_handlers;
79                 static ArrayList watchers = new ArrayList();
80                 static object watchers_lock = new object();
81                 Stack available = new Stack ();
82                 Stack available_for_end = new Stack ();
83                 
84                 bool IsEventHandler (MethodInfo m)
85                 {
86                         int pos = m.Name.IndexOf ('_');
87                         if (pos == -1 || (m.Name.Length - 1) <= pos)
88                                 return false;
89
90                         if (m.ReturnType != typeof (void))
91                                 return false;
92
93                         ParameterInfo [] pi = m.GetParameters ();
94                         int length = pi.Length;
95                         if (length == 0)
96                                 return true;
97
98                         if (length != 2)
99                                 return false;
100
101                         if (pi [0].ParameterType != typeof (object) ||
102                             pi [1].ParameterType != typeof (EventArgs))
103                                 return false;
104                         
105                         return true;
106                 }
107
108                 void AddEvent (MethodInfo method, Hashtable appTypeEventHandlers)
109                 {
110                         string name = method.Name.Replace ("_On", "_");
111                         if (appTypeEventHandlers [name] == null) {
112                                 appTypeEventHandlers [name] = method;
113                                 return;
114                         }
115
116                         MethodInfo old_method = appTypeEventHandlers [name] as MethodInfo;
117                         ArrayList list;
118                         if (old_method != null){
119                                 list = new ArrayList (4);
120                                 list.Add (old_method);
121                                 appTypeEventHandlers [name] = list;
122                         } else 
123                                 list = appTypeEventHandlers [name] as ArrayList;
124
125                         list.Add (method);
126                 }
127                 
128                 Hashtable GetApplicationTypeEvents (Type type)
129                 {
130                         lock (this) {
131                                 if (app_event_handlers != null)
132                                         return app_event_handlers;
133
134                                 app_event_handlers = new Hashtable ();
135                                 BindingFlags flags = BindingFlags.Public    | BindingFlags.NonPublic | 
136                                         BindingFlags.Instance  | BindingFlags.Static;
137
138                                 MethodInfo [] methods = type.GetMethods (flags);
139                                 foreach (MethodInfo m in methods) {
140                                         if (m.DeclaringType != typeof (HttpApplication) && IsEventHandler (m))
141                                                 AddEvent (m, app_event_handlers);
142                                 }
143                         }
144
145                         return app_event_handlers;
146                 }
147
148                 Hashtable GetApplicationTypeEvents (HttpApplication app)
149                 {
150                         lock (this) {
151                                 if (app_event_handlers != null)
152                                         return app_event_handlers;
153
154                                 return GetApplicationTypeEvents (app.GetType ());
155                         }
156                 }
157
158                 bool FireEvent (string method_name, object target, object [] args)
159                 {
160                         Hashtable possibleEvents = GetApplicationTypeEvents ((HttpApplication) target);
161                         MethodInfo method = possibleEvents [method_name] as MethodInfo;
162                         if (method == null)
163                                 return false;
164
165                         if (method.GetParameters ().Length == 0)
166                                 args = null;
167
168                         method.Invoke (target, args);
169
170                         return true;
171                 }
172
173                 HttpApplication FireOnAppStart (HttpContext context)
174                 {
175                         HttpApplication app = (HttpApplication) Activator.CreateInstance (app_type, true);
176                         context.ApplicationInstance = app;
177                         app.SetContext (context);
178                         object [] args = new object [] {app, EventArgs.Empty};
179                         FireEvent ("Application_Start", app, args);
180                         return app;
181                 }
182
183                 void FireOnAppEnd ()
184                 {
185                         if (app_type == null)
186                                 return; // we didn't even get an application
187
188                         HttpApplication app = (HttpApplication) Activator.CreateInstance (app_type, true);
189                         FireEvent ("Application_End", app, new object [] {new object (), EventArgs.Empty});
190                         app.Dispose ();
191                 }
192
193                 //
194                 // This is invoked by HttpRuntime.Dispose, when we unload an AppDomain
195                 // To reproduce this in action, touch "global.asax" while XSP is running.
196                 //
197                 public static void Dispose ()
198                 {
199                         theFactory.FireOnAppEnd ();
200                 }
201
202                 static FileSystemWatcher CreateWatcher (string file, FileSystemEventHandler hnd, RenamedEventHandler reh)
203                 {
204                         FileSystemWatcher watcher = new FileSystemWatcher ();
205
206                         watcher.Path = Path.GetFullPath (Path.GetDirectoryName (file));
207                         watcher.Filter = Path.GetFileName (file);
208
209                         watcher.Changed += hnd;
210                         watcher.Created += hnd;
211                         watcher.Deleted += hnd;
212                         watcher.Renamed += reh;
213
214                         watcher.EnableRaisingEvents = true;
215
216                         return watcher;
217                 }
218
219                 internal static void AttachEvents (HttpApplication app)
220                 {
221                         HttpApplicationFactory factory = theFactory;
222                         Hashtable possibleEvents = factory.GetApplicationTypeEvents (app);
223                         foreach (string key in possibleEvents.Keys) {
224                                 int pos = key.IndexOf ('_');
225                                 string moduleName = key.Substring (0, pos);
226                                 object target;
227                                 if (moduleName == "Application") {
228                                         target = app;
229                                 } else {
230                                         target = app.Modules [moduleName];
231                                         if (target == null)
232                                                 continue;
233                                 }
234
235                                 string eventName = key.Substring (pos + 1);
236                                 EventInfo evt = target.GetType ().GetEvent (eventName);
237                                 if (evt == null)
238                                         continue;
239
240                                 string usualName = moduleName + "_" + eventName;
241                                 object methodData = possibleEvents [usualName];
242                                 if (methodData != null && eventName == "End" && moduleName == "Session") {
243                                         lock (factory) {
244                                                 if (factory.session_end == null)
245                                                         factory.session_end = (MethodInfo) methodData;
246                                         }
247                                         continue;
248                                 }
249
250                                 if (methodData == null)
251                                         continue;
252
253                                 if (methodData is MethodInfo) {
254                                         factory.AddHandler (evt, target, app, (MethodInfo) methodData);
255                                         continue;
256                                 }
257
258                                 ArrayList list = (ArrayList) methodData;
259                                 foreach (MethodInfo method in list)
260                                         factory.AddHandler (evt, target, app, method);
261                         }
262                 }
263
264                 void AddHandler (EventInfo evt, object target, HttpApplication app, MethodInfo method)
265                 {
266                         int length = method.GetParameters ().Length;
267
268                         if (length == 0) {
269                                 NoParamsInvoker npi = new NoParamsInvoker (app, method.Name);
270                                 evt.AddEventHandler (target, npi.FakeDelegate);
271                         } else {
272                                 evt.AddEventHandler (target, Delegate.CreateDelegate (
273                                                              evt.EventHandlerType, app, method.Name));
274                         }
275                 }
276
277                 internal static void InvokeSessionEnd (object state)
278                 {
279                         InvokeSessionEnd (state, null, EventArgs.Empty);
280                 }
281                 
282                 internal static void InvokeSessionEnd (object state, object source, EventArgs e)
283                 {
284                         HttpApplicationFactory factory = theFactory;
285                         MethodInfo method = null;
286                         HttpApplication app = null;
287                         lock (factory.available_for_end) {
288                                 method = factory.session_end;
289                                 if (method == null)
290                                         return;
291
292                                 app = GetApplicationForSessionEnd ();
293                         }
294
295                         app.SetSession ((HttpSessionState) state);
296                         try {
297                                 method.Invoke (app, new object [] {(source == null ? app : source), e});
298                         } catch (Exception) {
299                                 // Ignore
300                         }
301                         RecycleForSessionEnd (app);
302                 }
303
304                 static HttpStaticObjectsCollection MakeStaticCollection (ArrayList list)
305                 {
306                         if (list == null || list.Count == 0)
307                                 return null;
308
309                         HttpStaticObjectsCollection coll = new HttpStaticObjectsCollection ();
310                         foreach (ObjectTagBuilder tag in list) {
311                                 coll.Add (tag);
312                         }
313
314                         return coll;
315                 }
316                 
317                 internal static HttpApplicationState ApplicationState {
318 #if TARGET_J2EE
319                         get {
320                                 HttpApplicationFactory factory = theFactory;
321                                 if (factory.app_state == null)
322                                         factory.app_state = new HttpApplicationState (null, null);
323                                 return factory.app_state;
324                         }
325 #else
326                         get {
327                                 if (theFactory.app_state == null) {
328                                         HttpStaticObjectsCollection app = MakeStaticCollection (GlobalAsaxCompiler.ApplicationObjects);
329                                         HttpStaticObjectsCollection ses = MakeStaticCollection (GlobalAsaxCompiler.SessionObjects);
330
331                                         theFactory.app_state = new HttpApplicationState (app, ses);
332                                 }
333                                 return theFactory.app_state;
334                         }
335 #endif
336                 }
337
338                 internal static Type AppType {
339                         get {
340                                 return theFactory.app_type;
341                         }
342                 }
343                 
344                 void InitType (HttpContext context)
345                 {
346                         lock (this) {
347                                 if (!needs_init)
348                                         return;
349
350 #if NET_2_0
351                                 try {
352 #endif
353                                         string physical_app_path = context.Request.PhysicalApplicationPath;
354                                         string app_file = null;
355                                         
356                                         app_file = Path.Combine (physical_app_path, "Global.asax");
357                                         if (!File.Exists (app_file)) {
358                                                 app_file = Path.Combine (physical_app_path, "global.asax");
359                                                 if (!File.Exists (app_file))
360                                                         app_file = null;
361                                         }
362                         
363 #if !NET_2_0
364                                         WebConfigurationSettings.Init (context);
365 #endif
366                 
367 #if NET_2_0 && !TARGET_J2EE
368                                         AppResourcesCompiler ac = new AppResourcesCompiler (context, true);
369                                         ac.Compile ();
370                                 
371                                         // Todo: Process App_WebResources here
372                                 
373                                         // Todo: Generate profile properties assembly from Web.config here
374                                 
375                                         // Todo: Compile code from App_Code here
376                                         AppCodeCompiler acc = new AppCodeCompiler ();
377                                         acc.Compile ();
378 #endif
379
380                                         if (app_file != null) {
381 #if TARGET_J2EE
382                                                 app_type = System.Web.J2EE.PageMapper.GetObjectType(app_file);
383 #else
384                                                 app_type = ApplicationFileParser.GetCompiledApplicationType (app_file, context);
385                                                 if (app_type == null) {
386                                                         string msg = String.Format ("Error compiling application file ({0}).", app_file);
387                                                         throw new ApplicationException (msg);
388                                                 }
389 #endif
390                                         } else {
391                                                 app_type = typeof (System.Web.HttpApplication);
392                                                 app_state = new HttpApplicationState ();
393                                         }
394
395                                         if (app_file != null)
396                                                 WatchLocationForRestart(app_file);
397                                             
398                                         if (File.Exists(Path.Combine(physical_app_path, "Web.config")))
399                                                 WatchLocationForRestart("Web.config");
400                                         else if (File.Exists(Path.Combine(physical_app_path, "web.config")))
401                                                 WatchLocationForRestart("web.config");
402                                         else if (File.Exists(Path.Combine(physical_app_path, "Web.Config")))
403                                                 WatchLocationForRestart("Web.Config");
404                                         needs_init = false;
405 #if NET_2_0
406                                 } catch (Exception) {
407 #if !TARGET_J2EE
408                                         if (BuildManager.CodeAssemblies != null)
409                                                 BuildManager.CodeAssemblies.Clear ();
410                                         if (BuildManager.TopLevelAssemblies != null)
411                                                 BuildManager.TopLevelAssemblies.Clear ();
412 #endif
413                                         if (WebConfigurationManager.ExtraAssemblies != null)
414                                                 WebConfigurationManager.ExtraAssemblies.Clear ();
415                                         throw;
416                                 }
417 #endif
418                                 
419                                 //
420                                 // Now init the settings
421                                 //
422
423                         }
424                 }
425                 
426                 //
427                 // Multiple-threads might hit this one on startup, and we have
428                 // to delay-initialize until we have the HttpContext
429                 //
430                 internal static HttpApplication GetApplication (HttpContext context)
431                 {
432                         HttpApplicationFactory factory = theFactory;
433                         HttpApplication app = null;
434                         if (factory.app_start_needed){
435                                 if (context == null)
436                                         return null;
437
438                                 factory.InitType (context);
439                                 lock (factory) {
440                                         if (factory.app_start_needed) {
441                                                 WatchLocationForRestart (AppDomain.CurrentDomain.SetupInformation.PrivateBinPath,
442                                                                          "*.dll");
443 #if NET_2_0
444                                                 WatchLocationForRestart ("App_Code", "");
445                                                 WatchLocationForRestart ("App_Browsers", "");
446                                                 WatchLocationForRestart ("App_GlobalResources", "");
447 #endif
448                                                 app = factory.FireOnAppStart (context);
449                                                 factory.app_start_needed = false;
450                                                 return app;
451                                         }
452                                 }
453                         }
454
455                         lock (factory.available) {
456                                 if (factory.available.Count > 0) {
457                                         app = (HttpApplication) factory.available.Pop ();
458                                         app.RequestCompleted = false;
459                                         return app;
460                                 }
461                         }
462                         
463                         return (HttpApplication) Activator.CreateInstance (factory.app_type, true);
464                 }
465
466                 // The lock is in InvokeSessionEnd
467                 static HttpApplication GetApplicationForSessionEnd ()
468                 {
469                         HttpApplicationFactory factory = theFactory;
470                         if (factory.available_for_end.Count > 0)
471                                 return (HttpApplication) factory.available_for_end.Pop ();
472
473                         HttpApplication app = (HttpApplication) Activator.CreateInstance (factory.app_type, true);
474                         app.InitOnce (false);
475
476                         return app;
477                 }
478
479                 internal static void RecycleForSessionEnd (HttpApplication app)
480                 {
481                         HttpApplicationFactory factory = theFactory;
482                         lock (factory.available_for_end) {
483                                 if (factory.available_for_end.Count < 32)
484                                         factory.available_for_end.Push (app);
485                                 else
486                                         app.Dispose ();
487                         }
488                 }
489
490                 internal static void Recycle (HttpApplication app)
491                 {
492                         HttpApplicationFactory factory = theFactory;
493                         lock (factory.available) {
494                                 if (factory.available.Count < 32)
495                                         factory.available.Push (app);
496                                 else
497                                         app.Dispose ();
498                         }
499                 }
500
501                 internal static bool ContextAvailable {
502                         get { return theFactory != null && !theFactory.app_start_needed; }
503                 }
504                 
505                 internal static bool WatchLocationForRestart(string filter)
506                 {
507                         return WatchLocationForRestart("", filter);
508                 }
509         
510                 internal static bool WatchLocationForRestart(string virtualPath, string filter)
511                 {
512                         // map the path to the physical one
513                         string physicalPath = HttpRuntime.AppDomainAppPath;
514                         physicalPath = Path.Combine(physicalPath, virtualPath);
515
516                         if (Directory.Exists(physicalPath) || File.Exists(physicalPath)) {
517                                 physicalPath = Path.Combine(physicalPath, filter);
518
519                                 // create the watcher
520                                 FileSystemEventHandler fseh = new FileSystemEventHandler(OnFileChanged);
521                                 RenamedEventHandler reh = new RenamedEventHandler(OnFileRenamed);
522                                 FileSystemWatcher watcher = CreateWatcher(physicalPath, fseh, reh);
523                         
524                                 lock (watchers_lock) {
525                                         watchers.Add(watcher);
526                                 }
527                                 return true;
528                         } else {
529                                 return false;
530                         }
531                 }
532
533                 static void OnFileRenamed(object sender, RenamedEventArgs args)
534                 {
535                         OnFileChanged(sender, args);
536                 }
537
538                 static void OnFileChanged(object sender, FileSystemEventArgs args)
539                 {
540                         lock (watchers_lock) {
541                                 // Disable event raising to avoid concurrent restarts
542                                 foreach (FileSystemWatcher watcher in watchers) {
543                                         watcher.EnableRaisingEvents = false;
544                                 }
545                                 // Restart application
546                                 HttpRuntime.UnloadAppDomain();
547                         }
548                 }
549         }
550 }
551