2 // System.Web.HttpApplicationFactory
5 // Gonzalo Paniagua Javier (gonzalo@ximian.com)
7 // (c) 2002,2003 Ximian, Inc. (http://www.ximian.com)
8 // (c) Copyright 2004 Novell, Inc. (http://www.novell.com)
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
30 using System.Collections;
32 using System.Reflection;
34 using System.Web.SessionState;
35 using System.Web.Configuration;
38 using System.Web.Compilation;
43 namespace System.Web {
44 class HttpApplicationFactory {
45 // Initialized in InitType
47 static HttpApplicationFactory theFactory {
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);
65 static HttpApplicationFactory theFactory = new HttpApplicationFactory();
68 static MethodInfo session_end;
69 bool needs_init = true;
70 bool app_start_needed = true;
72 HttpApplicationState app_state;
73 Hashtable app_event_handlers;
75 FileSystemWatcher app_file_watcher;
76 FileSystemWatcher bin_watcher;
78 Stack available = new Stack ();
79 Stack available_for_end = new Stack ();
81 // Watch this thing out when getting an instance
82 IHttpHandler custom_application;
84 bool IsEventHandler (MethodInfo m)
86 int pos = m.Name.IndexOf ('_');
87 if (pos == -1 || (m.Name.Length - 1) <= pos)
90 if (m.ReturnType != typeof (void))
93 ParameterInfo [] pi = m.GetParameters ();
94 int length = pi.Length;
101 if (pi [0].ParameterType != typeof (object) ||
102 pi [1].ParameterType != typeof (EventArgs))
108 void AddEvent (MethodInfo method, Hashtable appTypeEventHandlers)
110 string name = method.Name.Replace ("_On", "_");
111 if (appTypeEventHandlers [name] == null) {
112 appTypeEventHandlers [name] = method;
116 MethodInfo old_method = appTypeEventHandlers [name] as MethodInfo;
118 if (old_method != null){
119 list = new ArrayList (4);
120 list.Add (old_method);
121 appTypeEventHandlers [name] = list;
123 list = appTypeEventHandlers [name] as ArrayList;
128 Hashtable GetApplicationTypeEvents (Type type)
131 if (app_event_handlers != null)
132 return app_event_handlers;
134 app_event_handlers = new Hashtable ();
135 BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic |
136 BindingFlags.Instance | BindingFlags.Static;
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);
145 return app_event_handlers;
148 Hashtable GetApplicationTypeEvents (HttpApplication app)
151 if (app_event_handlers != null)
152 return app_event_handlers;
154 return GetApplicationTypeEvents (app.GetType ());
158 bool FireEvent (string method_name, object target, object [] args)
160 Hashtable possibleEvents = GetApplicationTypeEvents ((HttpApplication) target);
161 MethodInfo method = possibleEvents [method_name] as MethodInfo;
165 if (method.GetParameters ().Length == 0)
168 method.Invoke (target, args);
173 void FireOnAppStart (HttpContext context)
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);
184 if (app_type == null)
185 return; // we didn't even get an application
187 HttpApplication app = (HttpApplication) Activator.CreateInstance (app_type, true);
188 FireEvent ("Application_End", app, new object [] {new object (), EventArgs.Empty});
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.
196 public static void Dispose ()
198 theFactory.FireOnAppEnd ();
202 static FileSystemWatcher CreateWatcher (string file, FileSystemEventHandler hnd)
204 FileSystemWatcher watcher = new FileSystemWatcher ();
206 watcher.Path = Path.GetFullPath (Path.GetDirectoryName (file));
207 watcher.Filter = Path.GetFileName (file);
209 watcher.Changed += hnd;
210 watcher.Created += hnd;
211 watcher.Deleted += hnd;
213 watcher.EnableRaisingEvents = true;
218 void OnAppFileChanged (object sender, FileSystemEventArgs args)
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 ();
228 internal static void AttachEvents (HttpApplication app)
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);
236 if (moduleName == "Application") {
239 target = app.Modules [moduleName];
244 string eventName = key.Substring (pos + 1);
245 EventInfo evt = target.GetType ().GetEvent (eventName);
249 string usualName = moduleName + "_" + eventName;
250 object methodData = possibleEvents [usualName];
251 if (methodData != null && eventName == "End" && moduleName == "Session") {
253 if (session_end == null)
254 session_end = (MethodInfo) methodData;
259 if (methodData == null)
262 if (methodData is MethodInfo) {
263 factory.AddHandler (evt, target, app, (MethodInfo) methodData);
267 ArrayList list = (ArrayList) methodData;
268 foreach (MethodInfo method in list)
269 factory.AddHandler (evt, target, app, method);
273 void AddHandler (EventInfo evt, object target, HttpApplication app, MethodInfo method)
275 int length = method.GetParameters ().Length;
278 NoParamsInvoker npi = new NoParamsInvoker (app, method.Name);
279 evt.AddEventHandler (target, npi.FakeDelegate);
281 evt.AddEventHandler (target, Delegate.CreateDelegate (
282 typeof (EventHandler), app, method.Name));
286 internal static void InvokeSessionEnd (object state)
288 HttpApplicationFactory factory = theFactory;
289 MethodInfo method = null;
290 HttpApplication app = null;
291 lock (factory.available_for_end) {
292 method = session_end;
296 app = GetApplicationForSessionEnd ();
299 app.SetSession ((HttpSessionState) state);
301 method.Invoke (app, new object [] {app, EventArgs.Empty});
302 } catch (Exception e) {
305 RecycleForSessionEnd (app);
308 static HttpStaticObjectsCollection MakeStaticCollection (ArrayList list)
310 if (list == null || list.Count == 0)
313 HttpStaticObjectsCollection coll = new HttpStaticObjectsCollection ();
314 foreach (ObjectTagBuilder tag in list) {
321 internal static HttpApplicationState ApplicationState {
324 HttpApplicationFactory factory = theFactory;
325 if (factory.app_state == null)
326 factory.app_state = new HttpApplicationState (null, null);
327 return factory.app_state;
331 if (theFactory.app_state == null) {
332 HttpStaticObjectsCollection app = MakeStaticCollection (GlobalAsaxCompiler.ApplicationObjects);
333 HttpStaticObjectsCollection ses = MakeStaticCollection (GlobalAsaxCompiler.SessionObjects);
335 theFactory.app_state = new HttpApplicationState (app, ses);
337 return theFactory.app_state;
342 public static void SetCustomApplication (IHttpHandler customApplication)
344 theFactory.custom_application = customApplication;
347 internal static Type AppType {
349 return theFactory.app_type;
353 void InitType (HttpContext context)
359 string physical_app_path = context.Request.PhysicalApplicationPath;
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");
366 WebConfigurationSettings.Init (context);
368 if (File.Exists (app_file)) {
370 app_type = System.Web.J2EE.PageMapper.GetObjectType(app_file);
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);
378 app_file_watcher = CreateWatcher (app_file, new FileSystemEventHandler (OnAppFileChanged));
381 app_type = typeof (System.Web.HttpApplication);
382 app_state = new HttpApplicationState ();
387 // Now init the settings
394 // Multiple-threads might hit this one on startup, and we have
395 // to delay-initialize until we have the HttpContext
397 internal static HttpApplication GetApplication (HttpContext context)
399 HttpApplicationFactory factory = theFactory;
400 if (factory.needs_init){
404 factory.InitType (context);
406 if (factory.app_start_needed) {
408 string bin = HttpRuntime.BinDirectory;
409 if (Directory.Exists (bin))
410 bin = Path.Combine (bin, "*.dll");
412 // We watch bin or bin/*.dll if the directory exists
413 factory.bin_watcher = CreateWatcher (bin, new FileSystemEventHandler (factory.OnAppFileChanged));
415 factory.FireOnAppStart (context);
416 factory.app_start_needed = false;
421 lock (factory.available) {
422 if (factory.available.Count > 0)
423 return (HttpApplication) factory.available.Pop ();
426 HttpApplication app = (HttpApplication) Activator.CreateInstance (factory.app_type, true);
431 // The lock is in InvokeSessionEnd
432 static HttpApplication GetApplicationForSessionEnd ()
434 HttpApplicationFactory factory = theFactory;
435 if (factory.available_for_end.Count > 0)
436 return (HttpApplication) factory.available_for_end.Pop ();
438 HttpApplication app = (HttpApplication) Activator.CreateInstance (factory.app_type, true);
439 app.InitOnce (false);
444 internal static void RecycleForSessionEnd (HttpApplication app)
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);
455 internal static void Recycle (HttpApplication app)
457 HttpApplicationFactory factory = theFactory;
458 lock (factory.available) {
459 if (factory.available.Count < 32)
460 factory.available.Push (app);