EnVisageOnline/Main/Source/EnVisage/Global.asax.cs

313 lines
12 KiB
C#

using System.Data.Entity.Validation;
using System.Text;
using EnVisage.Code;
using EnVisage.Models;
using NLog;
using jQuery.DataTables.Mvc;
using System;
using System.Data.Entity;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Web.Helpers;
using Microsoft.IdentityModel.Claims;
using System.Linq;
using Microsoft.IdentityModel.Web;
using EnVisage.Code.ModelBinders;
using EnVisage.Code.Session;
using EnVisage.Code.BLL;
using StackExchange.Profiling;
using StackExchange.Profiling.EntityFramework6;
using Z.EntityFramework.Extensions;
using Prevu;
using System.Web.Http;
namespace EnVisage
{
public class MvcApplication : HttpApplication
{
protected void Application_Start()
{
MiniProfilerEF6.Initialize();
AutofacConfig.Configure(GlobalConfiguration.Configuration);
Telerik.Reporting.Services.WebApi.ReportsControllerConfiguration.RegisterRoutes(GlobalConfiguration.Configuration);
Database.SetInitializer<ApplicationDbContext>(null);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
ModelBinders.Binders.Add(typeof(JQueryDataTablesModel), new JQueryDataTablesModelBinder());
ModelBinders.Binders.Add(typeof(ActivityCalendarSaveModel), new ActivityCalendarSaveModelBinder());
ModelBinders.Binders.Add(typeof(MixSaveModel), new MixSaveModelBinder());
ModelBinders.Binders.Add(typeof(MixCalendarModel), new MixCalendarModelBinder());
ModelBinders.Binders.Add(typeof(ScenarioDetailSnapshotRecalculationModel), new JsonModelBinderBase<ScenarioDetailSnapshotRecalculationModel>());
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
MongoMigrationConfig.RunMigration();
FederatedAuthentication.ServiceConfigurationCreated += FederatedAuthentication_ServiceConfigurationCreated;
var jsonFactory = ValueProviderFactories.Factories.FirstOrDefault(x => x is JsonValueProviderFactory);
if (jsonFactory != null)
ValueProviderFactories.Factories.Remove(jsonFactory);
ValueProviderFactories.Factories.Add(new AdvancedJsonValueProviderFactory());
WorkFlowEngine.Runtime(null);
AuditProxy.Initialize(Properties.Settings.Default.AuditServiceUrl, Properties.Settings.Default.TenantId.ToString(),
Properties.Settings.Default.TenantPassword, Properties.Settings.Default.DomainId.ToString());
// CHECK for default provider (SQL Server)
string licenseErrorMessage;
if (!LicenseManager.ValidateLicense(out licenseErrorMessage))
throw new Exception(licenseErrorMessage);
AuditProxy.InitializeAudit();
}
private void WSFederationAuthenticationModule_RedirectingToIdentityProvider(object sender, RedirectingToIdentityProviderEventArgs e)
{
if (Context.Request.RequestContext.HttpContext.Request.IsAjaxRequest())
{
e.Cancel = true;
}
}
private void FederatedAuthentication_ServiceConfigurationCreated(object sender, Microsoft.IdentityModel.Web.Configuration.ServiceConfigurationCreatedEventArgs e)
{
FederatedAuthentication.WSFederationAuthenticationModule.RedirectingToIdentityProvider += WSFederationAuthenticationModule_RedirectingToIdentityProvider;
FederatedAuthentication.WSFederationAuthenticationModule.SignedIn += WSFederationAuthenticationModule_SignedIn;
FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenReceived += SessionAuthenticationModule_SessionSecurityTokenReceived;
FederatedAuthentication.WSFederationAuthenticationModule.SessionSecurityTokenCreated += WSFederationAuthenticationModule_SessionSecurityTokenCreated;
FederatedAuthentication.WSFederationAuthenticationModule.SecurityTokenReceived += WSFederationAuthenticationModule_SecurityTokenReceived;
}
private void WSFederationAuthenticationModule_SessionSecurityTokenCreated(object sender, SessionSecurityTokenCreatedEventArgs e)
{
//var logger = LogManager.GetCurrentClassLogger();
//try
//{
// var currentToken = e.SessionToken;
// var validForDays = 150;
// e.SessionToken = new SessionSecurityToken(
// currentToken.ClaimsPrincipal,
// currentToken.Context,
// currentToken.EndpointId,
// DateTime.UtcNow,
// DateTime.UtcNow.AddDays(validForDays));
// e.SessionToken.IsPersistent = true;
// // logger.Debug(" current security token and set it to expire on "+ currentToken.ValidTo.ToString());
//}
//catch (Exception ds) { logger.Debug(ds.ToString()); }
}
private void SessionAuthenticationModule_SessionSecurityTokenReceived(object sender, SessionSecurityTokenReceivedEventArgs e)
{
}
private void WSFederationAuthenticationModule_SecurityTokenReceived(object sender, SecurityTokenReceivedEventArgs e)
{
}
private void WSFederationAuthenticationModule_SignedIn(object sender, EventArgs e)
{
//var logger = LogManager.GetCurrentClassLogger();
//if (logger != null)
// logger.Debug(HttpContext.Current.User.Identity.Name +" signed in to ADFS!");
//SecurityManager.tryLogin();
//if (HttpContext.Current.User.Identity.IsAuthenticated && HttpContext.Current.User.Identity.GetID() != Guid.Empty.ToString())
// logger.Debug(HttpContext.Current.User.Identity.GetUserName() + " signed in to Prevu!");
//else
//{
// logger.Debug(HttpContext.Current.User.Identity.Name + " is not signed in to Prevu!");
//}
}
protected void Application_Error(object sender, EventArgs e)
{
var exception = Server.GetLastError();
LogException(exception);
}
protected void Application_BeginRequest()
{
if (Request.IsLocal)
{
MiniProfiler.Settings.PopupRenderPosition = RenderPosition.BottomRight;
MiniProfiler.Start();
}
}
protected void Application_EndRequest()
{
MiniProfiler.Stop();
}
private void LogException( Exception exception)
{
if (exception == null)
return;
var sb = new StringBuilder();
sb.AppendLine($"{exception.GetType()}: {exception.Message}");
sb.AppendLine(exception.StackTrace);
var innerCount = 0;
var innerEx = exception;
while (innerEx.InnerException != null && innerCount++ < Constants.MAX_INNER_EXCEPTION_LOG_LEVEL)
{
if (innerEx.Message != innerEx.InnerException.Message)
sb.AppendLine("Inner Exception Message: " + innerEx.InnerException.Message);
innerEx = innerEx.InnerException;
}
var validationException = exception as DbEntityValidationException;
if (validationException != null)
{
sb.AppendLine();
foreach (var validationErrors in validationException.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
sb.AppendFormat("Property: {0} Error: {1}", validationError.PropertyName,
validationError.ErrorMessage);
}
}
sb.AppendLine(validationException.StackTrace);
}
if (HttpContext.Current != null)
{
try
{
sb.AppendLine();
sb.AppendLine($"URL: {HttpContext.Current.Request.Url}");
sb.AppendLine($"Referrer: {HttpContext.Current.Request.UrlReferrer}");
sb.AppendLine($"QueryString: {HttpContext.Current.Request.QueryString}");
sb.AppendLine($"UserHostAddress: {HttpContext.Current.Request.UserHostAddress}");
sb.AppendLine($"UserAgent: {HttpContext.Current.Request.UserAgent}");
if (HttpContext.Current.Request.Form.Count > 0)
{
sb.AppendLine();
sb.AppendLine("Form:");
foreach (string key in HttpContext.Current.Request.Form.Keys)
{
sb.AppendLine($"{key}: {HttpContext.Current.Request.Form[key]}");
}
}
}
catch (Exception ex) //HttpContext.Current.Request could throw exception
{
sb.AppendLine();
sb.AppendLine("Error while handling exception details from HttpContext.Current:");
sb.AppendLine(ex.ToString());
}
}
var httpContext = new HttpContextWrapper(Context);
IController errCtrl = new Controllers.ErrorController();
RouteData routeData = new RouteData();
routeData.Values.Add("controller", "Error");
var action = "Http500";
var httpException = exception as HttpException;
if (httpException != null && Context != null)
{
switch (httpException.GetHttpCode())
{
case 404:
action = "Http404";
routeData.Values.Add("url", httpContext.Request.Url.OriginalString);
break;
default:
action = "Http500";
break;
}
}
routeData.Values.Add("action", action);
//redirect to custom error page if possible
try
{
// Clear the error on server.
Server.ClearError();
Response.Clear();
// Avoid IIS7 getting in the middle
Response.TrySkipIisCustomErrors = true;
Response.ContentType = "text/html; charset=utf-8";
errCtrl.Execute(new RequestContext(httpContext, routeData));
}
catch (Exception ex) // Response could throw exception; App_Start could throw exception (e.g. if no mongo) before MVC initialized so redirection is not available yet
{
sb.AppendLine();
sb.AppendLine("Error while trying to redirect to Error page:");
sb.AppendLine(ex.ToString());
}
var logger = LogManager.GetCurrentClassLogger();
logger?.Fatal(sb.ToString());
}
// SA. ENV-502
protected void Session_OnStart()
{
//try
//{
// FileManager mngr = new FileManager(null);
// mngr.EmptyUserTempFolder();
//}
//catch (Exception d)
//{
// LogException(d);
//}
try
{
AbsoluteUrl.Initialize(Context);
}
catch (Exception d)
{
LogException( d);
}
try
{
using (var notificationManager = new NotificationManager(null))
{
notificationManager.ClearExpiredNotifications();
}
}
catch (Exception d)
{
LogException(d);
}
}
// SA. ENV-502
protected void Session_OnEnd()
{
try
{
using (EnVisageEntities dbContext = new EnVisageEntities())
{
FileManager mngr = new FileManager(dbContext);
// Remove user tempory files
mngr.EmptyUserTempFolder();
// Remove user unattached permanent files
//mngr.DeleteUserUnattachedPermanentFiles();
}
}
catch
{
}
}
}
}