Files
Umbraco-CMS/src/Umbraco.Core/UmbracoApplicationBase.cs

251 lines
9.7 KiB
C#
Raw Normal View History

using System;
using System.Reflection;
using System.Threading;
using System.Web;
using System.Web.Hosting;
using log4net;
using LightInject;
2017-05-30 15:46:25 +02:00
using Umbraco.Core.Composing;
using Umbraco.Core.Logging;
namespace Umbraco.Core
{
/// <summary>
2016-08-25 15:09:51 +02:00
/// Provides an abstract base class for the Umbraco HttpApplication.
/// </summary>
2016-05-30 19:54:36 +02:00
public abstract class UmbracoApplicationBase : HttpApplication
{
2016-08-25 15:09:51 +02:00
private IRuntime _runtime;
/// <summary>
2016-08-25 15:09:51 +02:00
/// Gets a runtime.
/// </summary>
2016-08-25 15:09:51 +02:00
protected abstract IRuntime GetRuntime();
/// <summary>
2016-08-25 10:23:41 +02:00
/// Gets a logger.
/// </summary>
2016-08-25 10:23:41 +02:00
protected virtual ILogger GetLogger()
{
2016-08-25 10:23:41 +02:00
return Logger.CreateWithDefaultLog4NetConfiguration();
}
2016-09-08 18:43:58 +02:00
// events - in the order they trigger
// were part of the BootManager architecture, would trigger only for the initial
// application, so they need not be static, and they would let ppl hook into the
// boot process... but I believe this can be achieved with components as well and
// we don't need these events.
//public event EventHandler ApplicationStarting;
//public event EventHandler ApplicationStarted;
// this event can only be static since there will be several instances of this class
// triggers for each application instance, ie many times per lifetime of the application
public static event EventHandler ApplicationInit;
// this event can only be static since there will be several instances of this class
// triggers once per error
public static event EventHandler ApplicationError;
// this event can only be static since there will be several instances of this class
// triggers once per lifetime of the application, before it is unloaded
public static event EventHandler ApplicationEnd;
2016-08-25 15:09:51 +02:00
2016-09-08 18:43:58 +02:00
#region Start
2016-08-25 15:09:51 +02:00
// internal for tests
internal void HandleApplicationStart(object sender, EventArgs evargs)
{
2016-09-08 18:43:58 +02:00
// ******** THIS IS WHERE EVERYTHING BEGINS ********
2016-08-25 15:09:51 +02:00
2016-07-29 10:58:57 +02:00
// create the container for the application, and configure.
2016-08-25 10:23:41 +02:00
// the boot manager is responsible for registrations
var container = new ServiceContainer();
container.ConfigureUmbracoCore(); // also sets Current.Container
// register the essential stuff,
// ie the global application logger
// (profiler etc depend on boot manager)
var logger = GetLogger();
container.RegisterInstance(logger);
2016-08-25 15:09:51 +02:00
// now it is ok to use Current.Logger
2016-07-29 10:58:57 +02:00
2016-11-05 19:23:55 +01:00
ConfigureUnhandledException(logger);
2017-05-12 14:49:44 +02:00
ConfigureAssemblyResolve(logger);
2016-11-05 19:23:55 +01:00
// get runtime & boot
_runtime = GetRuntime();
_runtime.Boot(container);
}
protected virtual void ConfigureUnhandledException(ILogger logger)
{
2017-07-20 11:21:28 +02:00
//take care of unhandled exceptions - there is nothing we can do to
// prevent the entire w3wp process to go down but at least we can try
// and log the exception
AppDomain.CurrentDomain.UnhandledException += (_, args) =>
{
2016-08-25 10:23:41 +02:00
var exception = (Exception)args.ExceptionObject;
var isTerminating = args.IsTerminating; // always true?
var msg = "Unhandled exception in AppDomain";
if (isTerminating) msg += " (terminating)";
2016-08-25 15:09:51 +02:00
msg += ".";
2016-08-25 10:23:41 +02:00
logger.Error<UmbracoApplicationBase>(msg, exception);
};
}
2017-05-12 14:49:44 +02:00
protected virtual void ConfigureAssemblyResolve(ILogger logger)
{
// When an assembly can't be resolved. In here we can do magic with the assembly name and try loading another.
// This is used for loading a signed assembly of AutoMapper (v. 3.1+) without having to recompile old code.
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
// ensure the assembly is indeed AutoMapper and that the PublicKeyToken is null before trying to Load again
// do NOT just replace this with 'return Assembly', as it will cause an infinite loop -> stackoverflow
if (args.Name.StartsWith("AutoMapper") && args.Name.EndsWith("PublicKeyToken=null"))
return Assembly.Load(args.Name.Replace(", PublicKeyToken=null", ", PublicKeyToken=be96cd2c38ef1005"));
return null;
};
}
2016-08-25 15:09:51 +02:00
// called by ASP.NET (auto event wireup) once per app domain
// do NOT set instance data here - only static (see docs)
// sender is System.Web.HttpApplicationFactory, evargs is EventArgs.Empty
protected void Application_Start(object sender, EventArgs evargs)
{
Thread.CurrentThread.SanitizeThreadCulture();
HandleApplicationStart(sender, evargs);
}
2016-08-25 10:23:41 +02:00
2016-08-25 15:09:51 +02:00
#endregion
2016-08-25 10:23:41 +02:00
2016-08-25 15:09:51 +02:00
#region Init
2016-08-25 10:23:41 +02:00
2016-08-25 15:09:51 +02:00
private void OnApplicationInit(object sender, EventArgs evargs)
{
2016-09-08 18:43:58 +02:00
TryInvoke(ApplicationInit, "ApplicationInit", sender, evargs);
}
2016-08-25 15:09:51 +02:00
// called by ASP.NET for every HttpApplication instance after all modules have been created
// which means that this will be called *many* times for different apps when Umbraco runs
public override void Init()
2013-05-10 10:15:30 -02:00
{
2016-08-25 15:09:51 +02:00
// note: base.Init() is what initializes all of the httpmodules, ties up a bunch of stuff with IIS, etc...
// therefore, since OWIN is an HttpModule when running in IIS/ASP.Net the OWIN startup is not executed
// until this method fires and by that time - Umbraco has booted already
base.Init();
OnApplicationInit(this, new EventArgs());
2013-05-10 10:15:30 -02:00
}
2017-07-20 11:21:28 +02:00
2016-08-25 15:09:51 +02:00
#endregion
#region End
protected virtual void OnApplicationEnd(object sender, EventArgs evargs)
{
2016-08-25 15:09:51 +02:00
ApplicationEnd?.Invoke(this, EventArgs.Empty);
}
2016-08-25 15:09:51 +02:00
// internal for tests
internal void HandleApplicationEnd()
{
2016-08-25 15:09:51 +02:00
if (_runtime != null)
2016-08-25 10:23:41 +02:00
{
2016-08-25 15:09:51 +02:00
_runtime.Terminate();
_runtime.DisposeIfDisposable();
2017-07-20 11:21:28 +02:00
2016-08-25 15:09:51 +02:00
_runtime = null;
2015-07-08 16:27:06 +02:00
}
2016-11-05 19:23:55 +01:00
Current.Reset(); // dispose the container and everything
2016-08-25 15:09:51 +02:00
if (SystemUtilities.GetCurrentTrustLevel() != AspNetHostingPermissionLevel.Unrestricted) return;
// try to log the detailed shutdown message (typical asp.net hack: http://weblogs.asp.net/scottgu/433194)
2016-08-25 10:23:41 +02:00
try
2015-07-08 16:27:06 +02:00
{
2016-08-25 15:09:51 +02:00
var runtime = (HttpRuntime) typeof(HttpRuntime).InvokeMember("_theRuntime",
BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.GetField,
null, null, null);
if (runtime == null)
return;
var shutDownMessage = (string)runtime.GetType().InvokeMember("_shutDownMessage",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
null, runtime, null);
var shutDownStack = (string)runtime.GetType().InvokeMember("_shutDownStack",
BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.GetField,
null, runtime, null);
var shutdownMsg = $"Application shutdown. Details: {HostingEnvironment.ShutdownReason}\r\n\r\n_shutDownMessage={shutDownMessage}\r\n\r\n_shutDownStack={shutDownStack}";
Current.Logger.Info<UmbracoApplicationBase>(shutdownMsg);
2016-08-25 10:23:41 +02:00
}
2016-08-25 15:09:51 +02:00
catch (Exception)
2016-08-25 10:23:41 +02:00
{
2016-08-25 15:09:51 +02:00
//if for some reason that fails, then log the normal output
Current.Logger.Info<UmbracoApplicationBase>("Application shutdown. Reason: " + HostingEnvironment.ShutdownReason);
2015-07-08 16:27:06 +02:00
}
}
2016-08-25 15:09:51 +02:00
// called by ASP.NET (auto event wireup) once per app domain
// sender is System.Web.HttpApplicationFactory, evargs is EventArgs.Empty
protected void Application_End(object sender, EventArgs evargs)
{
HandleApplicationEnd();
OnApplicationEnd(sender, evargs);
LogManager.Shutdown();
}
#endregion
#region Error
protected virtual void OnApplicationError(object sender, EventArgs evargs)
{
2016-08-25 10:23:41 +02:00
ApplicationError?.Invoke(this, EventArgs.Empty);
}
2016-08-25 15:09:51 +02:00
private void HandleApplicationError()
{
2016-08-25 15:09:51 +02:00
var exception = Server.GetLastError();
2016-08-25 15:09:51 +02:00
// ignore HTTP errors
if (exception.GetType() == typeof(HttpException)) return;
2016-08-25 15:09:51 +02:00
Current.Logger.Error<UmbracoApplicationBase>("An unhandled exception occurred.", exception);
}
2016-08-25 15:09:51 +02:00
// called by ASP.NET (auto event wireup) at any phase in the application life cycle
protected void Application_Error(object sender, EventArgs e)
{
// when unhandled errors occur
HandleApplicationError();
OnApplicationError(sender, e);
}
2016-08-25 15:09:51 +02:00
#endregion
2017-07-20 11:21:28 +02:00
2016-09-08 18:43:58 +02:00
#region Utilities
2016-08-25 15:09:51 +02:00
2016-09-08 18:43:58 +02:00
private static void TryInvoke(EventHandler handler, string name, object sender, EventArgs evargs)
{
2016-08-25 15:09:51 +02:00
try
{
2016-09-08 18:43:58 +02:00
handler?.Invoke(sender, evargs);
2016-08-25 15:09:51 +02:00
}
catch (Exception ex)
{
2016-09-08 18:43:58 +02:00
Current.Logger.Error<UmbracoApplicationBase>($"Error in {name} handler.", ex);
2016-08-25 15:09:51 +02:00
throw;
}
}
2016-09-08 18:43:58 +02:00
#endregion
}
}