using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Web.Mvc; using MileageTraker.Web.Attributes; using MileageTraker.Web.DAL; using MileageTraker.Web.Models; using MileageTraker.Web.Utility; using MileageTraker.Web.ViewModels.Account; namespace MileageTraker.Web.Controllers { [UserActivity] public class ControllerBase : Controller { protected readonly DataService DataService = new DataService(); protected override void Dispose(bool disposing) { DataService.Dispose(); base.Dispose(disposing); } protected override void OnException(ExceptionContext filterContext) { if (filterContext != null && filterContext.Exception != null) { var controller = filterContext.RouteData.Values["controller"].ToString(); var action = filterContext.RouteData.Values["action"].ToString(); var loggerName = string.Format("{0}Controller.{1}", controller, action); log4net.LogManager.GetLogger(loggerName).Error(string.Empty, filterContext.Exception); } base.OnException(filterContext); } public string RenderRazorViewToString(string viewName, object model) { ViewData.Model = model; using (var sw = new StringWriter()) { var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName); var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw); viewResult.View.Render(viewContext, sw); viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View); return sw.GetStringBuilder().ToString(); } } protected string GetCookieValue(string key) { return HttpContext.Request.Cookies[key] != null ? HttpContext.Request.Cookies[key].Value : null; } protected void SetCookieValue(string key, string value) { var cookies = HttpContext.Response.Cookies; var httpCookie = cookies[key]; if (httpCookie == null) return; httpCookie.Value = value; httpCookie.Expires = DateTime.MaxValue; } protected string LinkForUrlAction(string urlAction) { return string.Format("{0}://{1}{2}", Request.Url.Scheme, Request.Url.Authority, urlAction); } protected string ResetPassword(User user) { // don't make a new one if they already have an active token var passwordResetToken = user.PasswordResetToken ?? Algorithms.GenerateToken(); var url = LinkForUrlAction( Url.Action("NewPassword", "Account", new NewPasswordViewModel { UserId = user.UserId, PasswordResetToken = passwordResetToken })); user.PasswordResetToken = passwordResetToken; DataService.UpdateUser(user); return url; } protected SelectList GetPurposeTypesSelectList() { var selectList = new SelectList(DataService.GetPurposeTypes(), "PurposeTypeId", "Purpose"); return selectList; } protected static IEnumerable GetModelStateErrorList(IEnumerable> modelStateDictionary) { var errorList = from kvp in modelStateDictionary where kvp.Value.Errors.Any() let errors = string.Join(", ", kvp.Value.Errors.Select(e => e.ErrorMessage)) let msg = kvp.Key + ": " + errors select msg; return errorList; } } }