Skip to content

Commit

Permalink
Removed auto start due to test purposes
Browse files Browse the repository at this point in the history
  • Loading branch information
Mantas Janulionis committed May 5, 2016
1 parent d529c13 commit e2a87a9
Show file tree
Hide file tree
Showing 4 changed files with 161 additions and 5 deletions.
151 changes: 150 additions & 1 deletion BetterModules.Core.Web/Environment/Host/DefaultWebApplicationHost.cs
Original file line number Diff line number Diff line change
@@ -1,24 +1,43 @@
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Hosting;
using System.Web.Mvc;
using System.Web.Routing;

using BetterModules.Core.DataAccess.DataContext.Migrations;
using BetterModules.Core.Exceptions;
using BetterModules.Core.Web.Exceptions.Host;
using BetterModules.Core.Web.Modules.Registration;

using Common.Logging;

using RazorGenerator.Mvc;

namespace BetterModules.Core.Web.Environment.Host
{
/// <summary>
/// Default web host implementation.
/// </summary>
[Obsolete("DefaultWebApplicationHost is deprecated. Consider utilizing DefaultWebApplicationAutoHost")]
public class DefaultWebApplicationHost : IWebApplicationHost
{
private static readonly ILog Logger = LogManager.GetLogger<DefaultWebApplicationHost>();

private readonly IWebModulesRegistration modulesRegistration;

private readonly IMigrationRunner migrationRunner;

/// <summary>
/// Initializes a new instance of the <see cref="DefaultWebApplicationHost" /> class.
/// </summary>
/// <param name="modulesRegistration">The modules registration.</param>
/// <param name="migrationRunner">The migration runner.</param>
public DefaultWebApplicationHost(IWebModulesRegistration modulesRegistration, IMigrationRunner migrationRunner)
{
this.modulesRegistration = modulesRegistration;
this.migrationRunner = migrationRunner;
}

/// <summary>
Expand All @@ -29,6 +48,27 @@ public DefaultWebApplicationHost(IWebModulesRegistration modulesRegistration, IM
/// <exception cref="CoreException">ViewEngines.Engines collection doesn't contain any precompiled MVC view engines. Each module uses precompiled MVC engines for rendering views. Please check if Engines list is not cleared manualy in global.asax.cx</exception>
public virtual void OnApplicationStart(HttpApplication application, bool validateViewEngines = true)
{
try
{
Logger.Info("Web application host starting...");

if (validateViewEngines && !ViewEngines.Engines.Any(engine => engine is CompositePrecompiledMvcEngine))
{
throw new CoreException("ViewEngines.Engines collection doesn't contain precompiled composite MVC view engine. Application modules use precompiled MVC views for rendering. Please check if Engines list is not cleared manualy in global.asax.cx");
}

modulesRegistration.RegisterKnownModuleRoutes(RouteTable.Routes);
MigrateDatabase();

// Notify.
Events.WebCoreEvents.Instance.OnHostStart(application);

Logger.Info("Web application host started.");
}
catch (Exception ex)
{
Logger.Fatal("Failed to start host application.", ex);
}
}

/// <summary>
Expand All @@ -37,6 +77,10 @@ public virtual void OnApplicationStart(HttpApplication application, bool validat
/// <param name="application">The host application.</param>
public virtual void OnApplicationEnd(HttpApplication application)
{
Logger.Info("Web host application stopped.");

// Notify.
Events.WebCoreEvents.Instance.OnHostStop(application);
}

/// <summary>
Expand All @@ -45,6 +89,11 @@ public virtual void OnApplicationEnd(HttpApplication application)
/// <param name="application">The host application.</param>
public virtual void OnApplicationError(HttpApplication application)
{
var error = application.Server.GetLastError();
Logger.Fatal("Unhandled exception occurred in web host application.", error);

// Notify.
Events.WebCoreEvents.Instance.OnHostError(application);
}

/// <summary>
Expand All @@ -61,6 +110,14 @@ public virtual void OnEndRequest(HttpApplication application)
/// <param name="application">The host application.</param>
public virtual void OnBeginRequest(HttpApplication application)
{
#if DEBUG
// A quick way to restart an application host.
// This is not going to affect production as it is compiled only in the debug mode.
if (application.Request["restart"] == "1")
{
RestartAndReloadHost(application);
}
#endif
}

/// <summary>
Expand All @@ -70,6 +127,8 @@ public virtual void OnBeginRequest(HttpApplication application)
/// <exception cref="System.NotImplementedException"></exception>
public virtual void OnAuthenticateRequest(HttpApplication application)
{
// Notify.
Events.WebCoreEvents.Instance.OnHostAuthenticateRequest(application);
}

/// <summary>
Expand All @@ -78,13 +137,103 @@ public virtual void OnAuthenticateRequest(HttpApplication application)
/// <param name="application">The application.</param>
public virtual void RestartAndReloadHost(HttpApplication application)
{
RestartApplicationHost();

Thread.Sleep(500);

UriBuilder uri = new UriBuilder(application.Request.Url);
uri.Query = string.Empty;

application.Response.ClearContent();
application.Response.Write(string.Format("<script type=\"text/javascript\">window.location = '{0}';</script>", uri));
application.Response.End();
}

/// <summary>
/// Terminates current application. The application restarts on the next time a request is received for it.
/// </summary>
public virtual void RestartApplicationHost()
{
try
{
HttpRuntime.UnloadAppDomain();
}
catch
{
try
{
bool success = TryTouchBinRestartMarker() || TryTouchWebConfig();

if (!success)
{
throw new RestartApplicationException("Failed to terminate host application.");
}
}
catch (Exception ex)
{
throw new RestartApplicationException("Failed to terminate host application.", ex);
}
}
}

/// <summary>
/// Tries to update last write time for web configuration file to restart application.
/// </summary>
/// <returns><c>true</c> if web.config file updated successfully; otherwise, <c>false</c>. </returns>
private bool TryTouchWebConfig()
{
try
{
File.SetLastWriteTimeUtc(HostingEnvironment.MapPath("~/web.config"), DateTime.UtcNow);
return true;
}
catch (Exception ex)
{
Logger.Warn("Failed to touch web host application web.config file.", ex);
return false;
}
}

/// <summary>
/// Tries the touch restart marker in ~/bin/restart folder.
/// </summary>
/// <returns><c>true</c> if file updated successfully; otherwise, <c>false</c>. </returns>
private bool TryTouchBinRestartMarker()
{
try
{
var binMarker = HostingEnvironment.MapPath("~/bin/restart");
Directory.CreateDirectory(binMarker);

using (var stream = File.CreateText(Path.Combine(binMarker, "marker.txt")))
{
stream.WriteLine("Restarted on '{0}'", DateTime.UtcNow);
stream.Flush();
}

return true;
}
catch (Exception ex)
{
Logger.Warn("Failed to touch web host application \bin folder.", ex);
return false;
}
}

/// <summary>
/// Updates database.
/// </summary>
private void MigrateDatabase()
{
try
{
var descriptors = modulesRegistration.GetModules().Select(m => m.ModuleDescriptor).ToList();
migrationRunner.MigrateStructure(descriptors);
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
}
}
2 changes: 1 addition & 1 deletion BetterModules.Core.Web/Environment/Host/UtilityHost.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
using BetterModules.Core.Web.Modules.Registration;
using BetterModules.Events;

[assembly : WebApplicationHost(typeof(UtilityHost), Order = Int32.MaxValue)]
//[assembly : WebApplicationHost(typeof(UtilityHost), Order = Int32.MaxValue)]
namespace BetterModules.Core.Web.Environment.Host
{
public sealed class UtilityHost : DefaultWebApplicationAutoHost
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@
<DependentUpon>Global.asax</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SampleDefaultWebApplicationAutoHost.cs" />
<Compile Include="SampleWebApplicationHost.cs" />
</ItemGroup>
<ItemGroup>
<Content Include="Content\bootstrap-theme.css" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
using System;
using System.Web;

using BetterModules.Core.DataAccess.DataContext.Migrations;
using BetterModules.Core.Exceptions;
using BetterModules.Core.Web.Environment.Application;
using BetterModules.Core.Web.Environment.Host;
using BetterModules.Core.Web.Modules.Registration;
using BetterModules.Mvc5.Sandbox;

[assembly : WebApplicationHost(typeof(SampleDefaultWebApplicationAutoHost), Order = 100)]
[assembly : WebApplicationHost(typeof(SampleWebApplicationHost), Order = 100)]
namespace BetterModules.Mvc5.Sandbox
{
public class SampleDefaultWebApplicationAutoHost : DefaultWebApplicationAutoHost
public class SampleWebApplicationHost : DefaultWebApplicationHost
{
public SampleWebApplicationHost(IWebModulesRegistration modulesRegistration, IMigrationRunner migrationRunner)
: base(modulesRegistration, migrationRunner)
{
}

HttpApplication SenderAsHttpApplication(object sender)
{
var application = sender as HttpApplication;
Expand Down

0 comments on commit e2a87a9

Please sign in to comment.