2005-11-02 Gonzalo Paniagua Javier <gonzalo@ximian.com>
[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 namespace System.Web {
44         class HttpApplicationFactory {
45                 // Initialized in InitType
46 #if TARGET_J2EE
47                 static HttpApplicationFactory theFactory {
48                         get
49                         {
50                                 HttpApplicationFactory factory = (HttpApplicationFactory)AppDomain.CurrentDomain.GetData("HttpApplicationFactory");
51                                 if (factory == null) {
52                                         lock(typeof(HttpApplicationFactory)) {
53                                                 factory = (HttpApplicationFactory)AppDomain.CurrentDomain.GetData("HttpApplicationFactory");
54                                                 if (factory == null) {
55                                                         factory = new HttpApplicationFactory();
56                                                         System.Threading.Thread.Sleep(1);
57                                                         AppDomain.CurrentDomain.SetData("HttpApplicationFactory", factory);
58                                                 }
59                                         }
60                                 }
61                                 return factory;
62                         }
63                 }
64 #else
65                 static HttpApplicationFactory theFactory = new HttpApplicationFactory();
66 #endif
67
68                 static MethodInfo session_end;
69                 bool needs_init = true;
70                 bool app_start_needed = true;
71                 Type app_type;
72                 HttpApplicationState app_state;
73                 Hashtable app_event_handlers;
74 #if !TARGET_JVM
75                 FileSystemWatcher app_file_watcher;
76                 FileSystemWatcher bin_watcher;
77 #endif
78                 Stack available = new Stack ();
79                 Stack available_for_end = new Stack ();
80                 
81                 // Watch this thing out when getting an instance
82                 IHttpHandler custom_application;
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                 void FireOnAppStart (HttpContext context)
174                 {
175                         HttpApplication app = (HttpApplication) Activator.CreateInstance (app_type, true);
176                         app.SetContext (context);
177                         object [] args = new object [] {app, EventArgs.Empty};
178                         FireEvent ("Application_Start", app, args);
179                         Recycle (app);
180                 }
181
182                 void FireOnAppEnd ()
183                 {
184                         if (app_type == null)
185                                 return; // we didn't even get an application
186
187                         HttpApplication app = (HttpApplication) Activator.CreateInstance (app_type, true);
188                         FireEvent ("Application_End", app, new object [] {new object (), EventArgs.Empty});
189                         app.Dispose ();
190                 }
191
192                 //
193                 // This is invoked by HttpRuntime.Dispose, when we unload an AppDomain
194                 // To reproduce this in action, touch "global.asax" while XSP is running.
195                 //
196                 public static void Dispose ()
197                 {
198                         theFactory.FireOnAppEnd ();
199                 }
200
201 #if !TARGET_JVM
202                 static FileSystemWatcher CreateWatcher (string file, FileSystemEventHandler hnd)
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
213                         watcher.EnableRaisingEvents = true;
214
215                         return watcher;
216                 }
217
218                 void OnAppFileChanged (object sender, FileSystemEventArgs args)
219                 {
220                         if (bin_watcher != null)
221                                 bin_watcher.EnableRaisingEvents = false;
222                         if (app_file_watcher != null)
223                                 app_file_watcher.EnableRaisingEvents = false;
224                         HttpRuntime.UnloadAppDomain ();
225                 }
226 #endif
227
228                 internal static void AttachEvents (HttpApplication app)
229                 {
230                         HttpApplicationFactory factory = theFactory;
231                         Hashtable possibleEvents = factory.GetApplicationTypeEvents (app);
232                         foreach (string key in possibleEvents.Keys) {
233                                 int pos = key.IndexOf ('_');
234                                 string moduleName = key.Substring (0, pos);
235                                 object target;
236                                 if (moduleName == "Application") {
237                                         target = app;
238                                 } else {
239                                         target = app.Modules [moduleName];
240                                         if (target == null)
241                                                 continue;
242                                 }
243
244                                 string eventName = key.Substring (pos + 1);
245                                 EventInfo evt = target.GetType ().GetEvent (eventName);
246                                 if (evt == null)
247                                         continue;
248
249                                 string usualName = moduleName + "_" + eventName;
250                                 object methodData = possibleEvents [usualName];
251                                 if (methodData != null && eventName == "End" && moduleName == "Session") {
252                                         lock (factory) {
253                                                 if (session_end == null)
254                                                         session_end = (MethodInfo) methodData;
255                                         }
256                                         continue;
257                                 }
258
259                                 if (methodData == null)
260                                         continue;
261
262                                 if (methodData is MethodInfo) {
263                                         factory.AddHandler (evt, target, app, (MethodInfo) methodData);
264                                         continue;
265                                 }
266
267                                 ArrayList list = (ArrayList) methodData;
268                                 foreach (MethodInfo method in list)
269                                         factory.AddHandler (evt, target, app, method);
270                         }
271                 }
272
273                 void AddHandler (EventInfo evt, object target, HttpApplication app, MethodInfo method)
274                 {
275                         int length = method.GetParameters ().Length;
276
277                         if (length == 0) {
278                                 NoParamsInvoker npi = new NoParamsInvoker (app, method.Name);
279                                 evt.AddEventHandler (target, npi.FakeDelegate);
280                         } else {
281                                 evt.AddEventHandler (target, Delegate.CreateDelegate (
282                                                         typeof (EventHandler), app, method.Name));
283                         }
284                 }
285
286                 internal static void InvokeSessionEnd (object state)
287                 {
288                         HttpApplicationFactory factory = theFactory;
289                         MethodInfo method = null;
290                         HttpApplication app = null;
291                         lock (factory.available_for_end) {
292                                 method = session_end;
293                                 if (method == null)
294                                         return;
295
296                                 app = GetApplicationForSessionEnd ();
297                         }
298
299                         app.SetSession ((HttpSessionState) state);
300                         try {
301                                 method.Invoke (app, new object [] {app, EventArgs.Empty});
302                         } catch (Exception e) {
303                                 // Ignore
304                         }
305                         RecycleForSessionEnd (app);
306                 }
307
308                 static HttpStaticObjectsCollection MakeStaticCollection (ArrayList list)
309                 {
310                         if (list == null || list.Count == 0)
311                                 return null;
312
313                         HttpStaticObjectsCollection coll = new HttpStaticObjectsCollection ();
314                         foreach (ObjectTagBuilder tag in list) {
315                                 coll.Add (tag);
316                         }
317
318                         return coll;
319                 }
320                 
321                 internal static HttpApplicationState ApplicationState {
322 #if TARGET_J2EE
323                         get {
324                                 HttpApplicationFactory factory = theFactory;
325                                 if (factory.app_state == null)
326                                         factory.app_state = new HttpApplicationState (null, null);
327                                 return factory.app_state;
328                         }
329 #else
330                         get {
331                                 if (theFactory.app_state == null) {
332                                         HttpStaticObjectsCollection app = MakeStaticCollection (GlobalAsaxCompiler.ApplicationObjects);
333                                         HttpStaticObjectsCollection ses = MakeStaticCollection (GlobalAsaxCompiler.SessionObjects);
334
335                                         theFactory.app_state = new HttpApplicationState (app, ses);
336                                 }
337                                 return theFactory.app_state;
338                         }
339 #endif
340                 }
341
342                 public static void SetCustomApplication (IHttpHandler customApplication)
343                 {
344                         theFactory.custom_application = customApplication;
345                 }
346
347                 internal static Type AppType {
348                         get {
349                                 return theFactory.app_type;
350                         }
351                 }
352
353                 void InitType (HttpContext context)
354                 {
355                         lock (this) {
356                                 if (!needs_init)
357                                         return;
358                                 
359                                 string physical_app_path = context.Request.PhysicalApplicationPath;
360                                 string app_file;
361                                 
362                                 app_file = Path.Combine (physical_app_path, "Global.asax");
363                                 if (!File.Exists (app_file))
364                                         app_file = Path.Combine (physical_app_path, "global.asax");
365                                 
366                                 WebConfigurationSettings.Init (context);
367                                 
368                                 if (File.Exists (app_file)) {
369 #if TARGET_J2EE
370                                         app_type = System.Web.J2EE.PageMapper.GetObjectType(app_file);
371 #else
372                                         app_type = ApplicationFileParser.GetCompiledApplicationType (app_file, context);
373                                         if (app_type == null) {
374                                                 string msg = String.Format ("Error compiling application file ({0}).", app_file);
375                                                 throw new ApplicationException (msg);
376                                         }
377                                         
378                                         app_file_watcher = CreateWatcher (app_file, new FileSystemEventHandler (OnAppFileChanged));
379 #endif
380                                 } else {
381                                         app_type = typeof (System.Web.HttpApplication);
382                                         app_state = new HttpApplicationState ();
383                                 }
384                                 needs_init = false;
385
386                                 //
387                                 // Now init the settings
388                                 //
389
390                         }
391                 }
392                 
393                 //
394                 // Multiple-threads might hit this one on startup, and we have
395                 // to delay-initialize until we have the HttpContext
396                 //
397                 internal static HttpApplication GetApplication (HttpContext context)
398                 {
399                         HttpApplicationFactory factory = theFactory;
400                         if (factory.needs_init){
401                                 if (context == null)
402                                         return null;
403
404                                 factory.InitType (context);
405                                 lock (factory) {
406                                         if (factory.app_start_needed) {
407 #if !TARGET_JVM
408                                                 string bin = HttpRuntime.BinDirectory;
409                                                 if (Directory.Exists (bin))
410                                                         bin = Path.Combine (bin, "*.dll");
411
412                                                 // We watch bin or bin/*.dll if the directory exists
413                                                 factory.bin_watcher = CreateWatcher (bin, new FileSystemEventHandler (factory.OnAppFileChanged));
414 #endif
415                                                 factory.FireOnAppStart (context);
416                                                 factory.app_start_needed = false;
417                                         }
418                                 }
419                         }
420
421                         lock (factory.available) {
422                                 if (factory.available.Count > 0)
423                                         return (HttpApplication) factory.available.Pop ();
424                         }
425                         
426                         HttpApplication app = (HttpApplication) Activator.CreateInstance (factory.app_type, true);
427
428                         return app;
429                 }
430
431                 // The lock is in InvokeSessionEnd
432                 static HttpApplication GetApplicationForSessionEnd ()
433                 {
434                         HttpApplicationFactory factory = theFactory;
435                         if (factory.available_for_end.Count > 0)
436                                 return (HttpApplication) factory.available_for_end.Pop ();
437
438                         HttpApplication app = (HttpApplication) Activator.CreateInstance (factory.app_type, true);
439                         app.InitOnce (false);
440
441                         return app;
442                 }
443
444                 internal static void RecycleForSessionEnd (HttpApplication app)
445                 {
446                         HttpApplicationFactory factory = theFactory;
447                         lock (factory.available_for_end) {
448                                 if (factory.available_for_end.Count < 32)
449                                         factory.available_for_end.Push (app);
450                                 else
451                                         app.Dispose ();
452                         }
453                 }
454
455                 internal static void Recycle (HttpApplication app)
456                 {
457                         HttpApplicationFactory factory = theFactory;
458                         lock (factory.available) {
459                                 if (factory.available.Count < 32)
460                                         factory.available.Push (app);
461                                 else
462                                         app.Dispose ();
463                         }
464                 }
465         }
466 }
467