using System; using System.Data.Entity.Validation; using System.Text; using System.Web; using System.Web.Mvc; using EnVisage.Code; using NLog; using EnVisage.Code.Session; using System.Web.Routing; using EnVisage.Code.Attributes; namespace EnVisage.Controllers { [PrevuAuthorize] [Authorize] public abstract class BaseController : Controller { private EnVisageEntities _dbContext; protected EnVisageEntities DbContext => _dbContext ?? (_dbContext = new EnVisageEntities()); protected static readonly Logger Logger = LogManager.GetCurrentClassLogger(); #region Error handling public void LogError(ExceptionContext exceptionContext) { Logger.Fatal(exceptionContext.Exception); } public void LogError(string message) { Logger.Fatal(message); } public void LogException(Exception ex) { var sb = new StringBuilder(); sb.AppendLine($"{ex.GetType()}: {ex.Message}"); sb.AppendLine(ex.StackTrace); var innerCount = 0; var innerEx = ex; 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 dbEntityValidationException = ex as DbEntityValidationException; if (dbEntityValidationException != null) { foreach (var validationErrors in dbEntityValidationException.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { sb.AppendFormat("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } sb.AppendLine(dbEntityValidationException.StackTrace); } if (System.Web.HttpContext.Current != null) { sb.AppendLine(); sb.AppendLine($"URL: {System.Web.HttpContext.Current.Request.Url}"); sb.AppendLine($"Referrer: {System.Web.HttpContext.Current.Request.UrlReferrer}"); sb.AppendLine($"QueryString: {System.Web.HttpContext.Current.Request.QueryString}"); sb.AppendLine($"UserHostAddress: {System.Web.HttpContext.Current.Request.UserHostAddress}"); sb.AppendLine($"UserAgent: {System.Web.HttpContext.Current.Request.UserAgent}"); if (System.Web.HttpContext.Current.Request.Form.Count > 0) { sb.AppendLine(); sb.AppendLine("Form:"); foreach (string key in System.Web.HttpContext.Current.Request.Form.Keys) { sb.AppendLine($"{key}: {System.Web.HttpContext.Current.Request.Form[key]}"); } } } // log error using NLog Logger.Fatal(sb.ToString()); } public void LogDebugMessage(string message) { Logger.Debug(message); } protected override void Dispose(bool disposing) { if (disposing) { DbContext.Dispose(); } base.Dispose(disposing); } [Obsolete("Use EnVisage.Code.Validation.JsonResultBase and inherited classes to handle ajax requests.")] protected virtual void SetErrorScript(string title = Constants.ERROR_GENERAL_TITLE_TEMPLATE, string message = Constants.ERROR_GENERAL_MESSAGE_TEMPLATE) { ViewBag.StartUpJS = string.Format("showErrorModal('{0}','{1}');", title.Replace("'", "''"), message.Replace("'", "''")); } protected override void HandleUnknownAction(string actionName) { // If controller is ErrorController dont 'nest' exceptions if (this.GetType() != typeof(ErrorController)) this.InvokeHttp404(HttpContext); } public ActionResult InvokeHttp404(HttpContextBase httpContext) { IController errorController = new ErrorController(); var errorRoute = new RouteData(); errorRoute.Values.Add("controller", "Error"); errorRoute.Values.Add("action", "Http404"); errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString); errorController.Execute(new RequestContext(httpContext, errorRoute)); return new EmptyResult(); } public ActionResult InvokeHttp500(HttpContextBase httpContext) { IController errorController = new ErrorController(); var errorRoute = new RouteData(); errorRoute.Values.Add("controller", "Error"); errorRoute.Values.Add("action", "Http500"); errorRoute.Values.Add("url", httpContext.Request.Url.OriginalString); errorController.Execute(new RequestContext(httpContext, errorRoute)); return new EmptyResult(); } #endregion protected BaseController() { ViewBag.GlobalVariables = string.Format("var _isLockCheckIntervalMs = {0};{1}var _periodOfInactivity = {2};var _USR_PREF_ISHOURS_KEY = '{3}'; var _USR_PREF_AVG_KEY = '{4}'; var _warningInterval = {5};", Properties.Settings.Default.JSLockCheckInterval, Environment.NewLine, Properties.Settings.Default.LockerAPIInactivityTimeout, Constants.USER_PREFERENCE_UOMHOURSMODE, Constants.USER_PREFERENCE_AVGMODE, Properties.Settings.Default.LockerAPIWarningInterval); if (SessionManager.Exists(Constants.USERVOICE_SSO_TOKEN)) { ViewBag.ssoToken = SessionManager.GetValue(Constants.USERVOICE_SSO_TOKEN); } else { if (System.Web.HttpContext.Current.Request.Cookies[Constants.USERVOICE_COOKIE_CONTEXT] != null) { ViewBag.ssoToken = System.Web.HttpContext.Current.Request.Cookies[Constants.USERVOICE_COOKIE_CONTEXT][Constants.USERVOICE_SSO_TOKEN]; } } } protected ActionResult RedirectToAccessDenied() { return RedirectToRoute(new RouteValueDictionary(new { controller = "Home", action = "AccessDenied" })); } protected JsonResult BigJson(object data) { return BigJson(data, JsonRequestBehavior.DenyGet); } protected JsonResult BigJson(object data, JsonRequestBehavior behavior) { return new JsonResult() { Data = data, MaxJsonLength = int.MaxValue, JsonRequestBehavior = behavior }; } // TEMPLATE FOR ANY GET METHOD //public ActionResult Index() //{ // try // { // // check permission to get this info // if (!HtmlHelpers.CheckSecurityObjectPermission(null, "Fiscal Calendar", "Area", User.Identity.GetID())) // return Redirect("/"); // // load data from DB using BLL object // var manager = new FiscalCalendarManager(DbContext); // var model = manager.LoadFiscalCalendarSettings(); // // return model filled with data from DB // return View(model); // } // catch (BLLException blEx) // handle any system specific error // { // // display error message if required // if (blEx.DisplayError) // SetErrorScript(message: blEx.Message); // else // if display not requried then display modal form with general error message // { // LogException(blEx); // SetErrorScript(); // } // } // catch (Exception exception) // handle any unexpected error // { // LogException(exception); // SetErrorScript(); // } // // return empty model with validation message (if any) // return View(new FiscalCalendarModel()); //} // TEMPLATE FOR ANY POST METHOD //[HttpPost] //[ValidateAntiForgeryToken] //public ActionResult Edit(FiscalCalendarModel model) //{ // // remove whitespaces from string model properties // model.TrimStringProperties(); // Example of logging object //var sb = new StringBuilder(); //sb.AppendLine("Model of the Edit method (post):"); //model.DebugObjectProperties(sb); //Logger.Debug(sb); // if (ModelState.IsValid) // { // try // { // // save data from model to the DB // var manager = new FiscalCalendarManager(DbContext); // manager.SaveFiscalCalendarSettings(model); // DbContext.SaveChanges(); // // remove content lock // ContentLocker.RemoveLock("SystemSettings", model.TypeSettingId.ToString(), User.Identity.GetUserName()); // // refresh the page on successful result // return RedirectToAction("Index"); // } // catch (BLLException blEx) // handle any system specific error // { // // display error message if required // if (blEx.DisplayError) // ModelState.AddModelError(string.Empty, blEx.Message); // else // if display not requried then display modal form with general error message // { // LogException(blEx); // SetErrorScript(); // } // } // catch (Exception exception) // handle any unexpected error // { // LogException(exception); // SetErrorScript(); // } // } // // return empty model with validation message (if any) // return View(model); //} } }