using System; using System.Collections.Generic; using System.Data.Entity.Validation; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using EnVisage.Code; using NLog; namespace EnVisage.Controllers { [Authorize] public abstract class BaseController : Controller { protected readonly EnVisageEntities DbContext = new EnVisageEntities(); protected static readonly Logger Logger = LogManager.GetCurrentClassLogger(); 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(string.Format("{0}: {1}", 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(string.Format("URL: {0}", System.Web.HttpContext.Current.Request.Url)); sb.AppendLine(string.Format("Referrer: {0}", System.Web.HttpContext.Current.Request.UrlReferrer)); sb.AppendLine(string.Format("QueryString: {0}", System.Web.HttpContext.Current.Request.QueryString)); sb.AppendLine(string.Format("UserHostAddress: {0}", System.Web.HttpContext.Current.Request.UserHostAddress)); sb.AppendLine(string.Format("UserAgent: {0}", 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(string.Format("{0}: {1}", key, System.Web.HttpContext.Current.Request.Form[key])); } } } // log error using NLog Logger.Fatal(sb.ToString()); } protected override void Dispose(bool disposing) { if (disposing) { DbContext.Dispose(); } base.Dispose(disposing); } 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 BaseController() { ViewBag.GlobalVariables = string.Format("var _isLockCheckIntervalMs = {0};{1}var _periodOfInactivity = {2};", Properties.Settings.Default.JSLockCheckInterval, Environment.NewLine, Properties.Settings.Default.UnlockInterval); } // TEMPLATE FOR ANY GET METHOD //public ActionResult Index() //{ // try // { // // check permission to get this info // if (!HtmlHelpers.CheckSecurityObjectPermission(null, "Fiscal Calendar", "Area", User.Identity.GetUserId())) // 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.Name); // // 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); //} } }