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 #if NET_2_0 && !TARGET_J2EE
44 using System.CodeDom.Compiler;
47 namespace System.Web {
48 class HttpApplicationFactory {
49 // Initialized in InitType
51 static HttpApplicationFactory theFactory {
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);
69 static HttpApplicationFactory theFactory = new HttpApplicationFactory();
73 MethodInfo session_end;
74 bool needs_init = true;
75 bool app_start_needed = true;
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 ();
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 HttpApplication FireOnAppStart (HttpContext context)
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);
185 if (app_type == null)
186 return; // we didn't even get an application
188 HttpApplication app = (HttpApplication) Activator.CreateInstance (app_type, true);
189 FireEvent ("Application_End", app, new object [] {new object (), EventArgs.Empty});
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.
197 public static void Dispose ()
199 theFactory.FireOnAppEnd ();
202 static FileSystemWatcher CreateWatcher (string file, FileSystemEventHandler hnd, RenamedEventHandler reh)
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;
212 watcher.Renamed += reh;
214 watcher.EnableRaisingEvents = true;
219 internal static void AttachEvents (HttpApplication app)
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);
227 if (moduleName == "Application") {
230 target = app.Modules [moduleName];
235 string eventName = key.Substring (pos + 1);
236 EventInfo evt = target.GetType ().GetEvent (eventName);
240 string usualName = moduleName + "_" + eventName;
241 object methodData = possibleEvents [usualName];
242 if (methodData != null && eventName == "End" && moduleName == "Session") {
244 if (factory.session_end == null)
245 factory.session_end = (MethodInfo) methodData;
250 if (methodData == null)
253 if (methodData is MethodInfo) {
254 factory.AddHandler (evt, target, app, (MethodInfo) methodData);
258 ArrayList list = (ArrayList) methodData;
259 foreach (MethodInfo method in list)
260 factory.AddHandler (evt, target, app, method);
264 void AddHandler (EventInfo evt, object target, HttpApplication app, MethodInfo method)
266 int length = method.GetParameters ().Length;
269 NoParamsInvoker npi = new NoParamsInvoker (app, method.Name);
270 evt.AddEventHandler (target, npi.FakeDelegate);
272 evt.AddEventHandler (target, Delegate.CreateDelegate (
273 evt.EventHandlerType, app, method.Name));
277 internal static void InvokeSessionEnd (object state)
279 InvokeSessionEnd (state, null, EventArgs.Empty);
282 internal static void InvokeSessionEnd (object state, object source, EventArgs e)
284 HttpApplicationFactory factory = theFactory;
285 MethodInfo method = null;
286 HttpApplication app = null;
287 lock (factory.available_for_end) {
288 method = factory.session_end;
292 app = GetApplicationForSessionEnd ();
295 app.SetSession ((HttpSessionState) state);
297 method.Invoke (app, new object [] {(source == null ? app : source), e});
298 } catch (Exception) {
301 RecycleForSessionEnd (app);
304 static HttpStaticObjectsCollection MakeStaticCollection (ArrayList list)
306 if (list == null || list.Count == 0)
309 HttpStaticObjectsCollection coll = new HttpStaticObjectsCollection ();
310 foreach (ObjectTagBuilder tag in list) {
317 internal static HttpApplicationState ApplicationState {
320 HttpApplicationFactory factory = theFactory;
321 if (factory.app_state == null)
322 factory.app_state = new HttpApplicationState (null, null);
323 return factory.app_state;
327 if (theFactory.app_state == null) {
328 HttpStaticObjectsCollection app = MakeStaticCollection (GlobalAsaxCompiler.ApplicationObjects);
329 HttpStaticObjectsCollection ses = MakeStaticCollection (GlobalAsaxCompiler.SessionObjects);
331 theFactory.app_state = new HttpApplicationState (app, ses);
333 return theFactory.app_state;
338 internal static Type AppType {
340 return theFactory.app_type;
344 void InitType (HttpContext context)
353 string physical_app_path = context.Request.PhysicalApplicationPath;
354 string app_file = null;
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))
364 WebConfigurationSettings.Init (context);
367 #if NET_2_0 && !TARGET_J2EE
368 AppResourcesCompiler ac = new AppResourcesCompiler (context, true);
371 // Todo: Process App_WebResources here
373 // Todo: Generate profile properties assembly from Web.config here
375 // Todo: Compile code from App_Code here
376 AppCodeCompiler acc = new AppCodeCompiler ();
380 if (app_file != null) {
382 app_type = System.Web.J2EE.PageMapper.GetObjectType(app_file);
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);
391 app_type = typeof (System.Web.HttpApplication);
392 app_state = new HttpApplicationState ();
395 if (app_file != null)
396 WatchLocationForRestart(app_file);
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");
406 } catch (Exception) {
408 if (BuildManager.CodeAssemblies != null)
409 BuildManager.CodeAssemblies.Clear ();
410 if (BuildManager.TopLevelAssemblies != null)
411 BuildManager.TopLevelAssemblies.Clear ();
413 if (WebConfigurationManager.ExtraAssemblies != null)
414 WebConfigurationManager.ExtraAssemblies.Clear ();
420 // Now init the settings
427 // Multiple-threads might hit this one on startup, and we have
428 // to delay-initialize until we have the HttpContext
430 internal static HttpApplication GetApplication (HttpContext context)
432 HttpApplicationFactory factory = theFactory;
433 HttpApplication app = null;
434 if (factory.app_start_needed){
438 factory.InitType (context);
440 if (factory.app_start_needed) {
441 WatchLocationForRestart (AppDomain.CurrentDomain.SetupInformation.PrivateBinPath,
444 WatchLocationForRestart ("App_Code", "");
445 WatchLocationForRestart ("App_Browsers", "");
446 WatchLocationForRestart ("App_GlobalResources", "");
448 app = factory.FireOnAppStart (context);
449 factory.app_start_needed = false;
455 lock (factory.available) {
456 if (factory.available.Count > 0) {
457 app = (HttpApplication) factory.available.Pop ();
458 app.RequestCompleted = false;
463 return (HttpApplication) Activator.CreateInstance (factory.app_type, true);
466 // The lock is in InvokeSessionEnd
467 static HttpApplication GetApplicationForSessionEnd ()
469 HttpApplicationFactory factory = theFactory;
470 if (factory.available_for_end.Count > 0)
471 return (HttpApplication) factory.available_for_end.Pop ();
473 HttpApplication app = (HttpApplication) Activator.CreateInstance (factory.app_type, true);
474 app.InitOnce (false);
479 internal static void RecycleForSessionEnd (HttpApplication app)
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);
490 internal static void Recycle (HttpApplication app)
492 HttpApplicationFactory factory = theFactory;
493 lock (factory.available) {
494 if (factory.available.Count < 32)
495 factory.available.Push (app);
501 internal static bool ContextAvailable {
502 get { return theFactory != null && !theFactory.app_start_needed; }
505 internal static bool WatchLocationForRestart(string filter)
507 return WatchLocationForRestart("", filter);
510 internal static bool WatchLocationForRestart(string virtualPath, string filter)
512 // map the path to the physical one
513 string physicalPath = HttpRuntime.AppDomainAppPath;
514 physicalPath = Path.Combine(physicalPath, virtualPath);
516 if (Directory.Exists(physicalPath) || File.Exists(physicalPath)) {
517 physicalPath = Path.Combine(physicalPath, filter);
519 // create the watcher
520 FileSystemEventHandler fseh = new FileSystemEventHandler(OnFileChanged);
521 RenamedEventHandler reh = new RenamedEventHandler(OnFileRenamed);
522 FileSystemWatcher watcher = CreateWatcher(physicalPath, fseh, reh);
524 lock (watchers_lock) {
525 watchers.Add(watcher);
533 static void OnFileRenamed(object sender, RenamedEventArgs args)
535 OnFileChanged(sender, args);
538 static void OnFileChanged(object sender, FileSystemEventArgs args)
540 lock (watchers_lock) {
541 // Disable event raising to avoid concurrent restarts
542 foreach (FileSystemWatcher watcher in watchers) {
543 watcher.EnableRaisingEvents = false;
545 // Restart application
546 HttpRuntime.UnloadAppDomain();