Thursday, March 17, 2011

How to use multiple login pages in MVC

When you only have one login page, then it's easy to add the authorize attribute to your action and you'll automatically be directed to the login page in your web.config


[Authorize(Roles = "Administrator")]
public ActionResult EditCategory(int id)
{
   return View();
}
On my sites, I have a separate login page for the Administrative area, so I needed to create a custom attribute.

[CustomAuthorization(LoginPage = "~/Admin/LogOn", Role = "Administrator")]
public ActionResult EditCategory(int id)
{
   return View();
}
/// <summary>
/// Allows you to specify the Login Page and Role with an attribute:  [CustomAuthorization(LoginPage="~/Admin/LogOn",Role="Administrator")]
/// </summary>
/// <param name="filterContext"></param>
public class CustomAuthorization : AuthorizeAttribute
{
   public string LoginPage { getset; }
   public string Role { getset; }
 
   public override void OnAuthorization(AuthorizationContext filterContext)
   {
      //Send the return url to the login page
      LoginPage += "?ReturnUrl=" + filterContext.HttpContext.Request.RawUrl;
      if (!filterContext.HttpContext.User.Identity.IsAuthenticated)       {          filterContext.HttpContext.Response.Redirect(LoginPage);       }       else       {          if (Role != null)          {             if(!filterContext.HttpContext.User.IsInRole(Role))                filterContext.HttpContext.Response.Redirect(LoginPage);          }       }       base.OnAuthorization(filterContext);    } }

Wednesday, March 9, 2011

How to calculate age in Excel

This formula will calculate a person's age in excel (assuming date of birth is in cell A1)


=IF(MONTH(TODAY())>MONTH(A1),YEAR(TODAY())-YEAR(A1),
 IF(AND(MONTH(TODAY())=MONTH(A1),DAY(TODAY())>=DAY(A1)),
 YEAR(TODAY())-YEAR(A1),(YEAR(TODAY())-YEAR(A1))-1))