Inserting copyright notice/banner/header in all source code files with PowerShell script

I have a better version of this PowerShell script if you’re interested.
I suggest you read this post first (there’s a bonus point) then go take a look at the new one here:
Updated PowerShell script to insert copyright notice/banner/header in all source code files

Today my client asked for the source code of a project we worked together. He wants to submit it to patent review and he wanted to include a copyright notice in each C# code file (.cs).

I googled about a way of accomplishing this and found this post:

Use a Visual Studio Macro to Insert Copyright Headers into Source Files

It looked promising but as I’m working with Visual Studio 2012 I just hit a road block because it dropped the support for Macros. So I had to find some other way… in the meantime I asked a question at StackOverflow to see if someone had any good advice regarding this. Right now there’s one nice answer but it requires manual work. I’m really interested in an automated process (do the work in a batch fashion) because there are lots of .cs files in the Visual Studio solution comprised of 7 projects.

Some more Googling with the right words (read PowerShell) and I was able to find something that could do the work. Kishor Aher wrote about it Powershell – Copyright header generator script. Oh God, the internet is really amazing thingy! Remember to just search for the right words…

Now it was just a matter of adapting the PowerShell script to my needs. Here is it:

param($target = "C:\MyProject", $companyname = "My Company", $date = (Get-Date))

$header = "//-----------------------------------------------------------------------

// <copyright file=""{0}"" company=""{1}"">

// Copyright (c) {1}. All rights reserved.

// <author>Leniel Macaferi</author>

// <date>{2}</date>

// </copyright>

//-----------------------------------------------------------------------`r`n"

function Write-Header ($file)
{
    $content = Get-Content $file

    $filename = Split-Path -Leaf $file

    $fileheader = $header -f $filename,$companyname,$date

    Set-Content $file $fileheader

    Add-Content $file $content
}

Get-ChildItem $target -Recurse | ? { $_.Extension -like ".cs" } | % `
{
    Write-Header $_.PSPath.Split(":", 3)[2]
}

As you see above, the script will place the copyright notice in every .cs file that lies within the folder C:\MyProject. So let’s say you have a Visual Studio solution with various projects – the script will traverse all files placing the notice in every .cs file it finds along the way…

I named the script Copyright.ps1.

To make this work I just opened PowerShell command line, navigated to the folder where I placed the script file and typed .\Copyright.ps1 to run the script:

Executing Copyright PowerShell script using PowerShell command line toolFigure 1 - Executing Copyright PowerShell script using PowerShell command line tool

You’re done!

Enjoy.

Notes

  • Close Visual Studio solution before running the PowerShell script. Otherwise you may get some error message telling you that some file is in use.
  • Be sure to have your source code files commited in a source control repository before running the scripts so that if anything goes wrong you can just revert to the previous state.
  • Beware that if you run the script twice it'll add the copyright notice twice in each file.

A big thank you to Kishor for providing us the PowerShell script. I’m not that experienced with PowerShell but adapting existing scripts is something easy to do IMHO.

Bonus
To get support for PowerShell scripting in Visual Studio with syntax highlighting and IntelliSense, there’s an awesome and free product out there. It’s called PowerGUI. In order to use it, download PowerGUI here and then install its accompanying Visual Studio extension available here. As I’m using Visual Studio 2012 I had to install the alpha release available here.

See for yourself the awesomeness:

PowerGUI editing PowerShell script with full IntelliSense support and Code Highlighting
Figure 2 - PowerGUI editing PowerShell script with full IntelliSense support and Code Highlighting

string.Format with dynamic length left aligned text in C#

This post is about dynamic text alignment with C#.

Scenario: I wanted to implement a dropdownlist with list items left aligned based on a string format. This is the initial appearance of the dropdown with no text alignment applied:

DropDownList with Text not alignedFigure 1 - DropDownList with Text not aligned

See that because Hospital names that come before => have different lengths, it doesn’t look good. Start and End dates are not aligned due to this.

So I thought about adding some caring to this and remembered that C# supports what I want to do. It’s called Composite Formatting. This when used with the Alignment Component allows some nice implementations.

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Look at the following action method that lies within an ASP.NET MVC app. It’s responsible for adding list items to the dropdown show above…

[GET("Reports")]
public virtual ActionResult Index()
{
    ReportViewModel model = new ReportViewModel();

    // Getting the length of the lengthiest FictitiousName using Max query operator
    var maxLength = Database.Assessments.Max(a => a.Hospital.FictitiousName.Length);

    // Here’s the dynamic part: maxLength is used inside a format string to right align all strings, hence the minus sign. Doing this all strings will be equally left aligned (by maxLength) no matter their size.
    // {0}, {1} and {2} are positional parameters.
    string format = "{0, -" + maxLength + "} => {1} - {2}";

    List<SelectListItem> items = new List<SelectListItem>();

    foreach(Assessment a in Database.Assessments)
    {
        SelectListItem item = new SelectListItem();

        // Here's where the format string is used...
        item.Text = string.Format(format,
            a.Hospital.FictitiousName, a.StartDate.ToShortDateString(), a.EndDate.ToShortDateString());

        // This is necessary so that white spaces are respected when rendering the HTML code.
        item.Text = item.Text.Replace(" ", HttpUtility.HtmlDecode("&nbsp;"));

        item.Value = a.AssessmentId.ToString();

        items.Add(item);
    }

    model.Assessments = new SelectList(items.OrderBy(i => i.Text), "Value", "Text");

    return View(model);
}

With this code, now the result (really better to spot the dates) is this:

DropDownList with Text aligned using a format string dynamically builtFigure 2 - DropDownList with Text aligned using a format string dynamically built

maxLength in this case = 20. This is the length of “Unimed Volta Redonda” (the lengthiest string in the list) in this specific case. The format string uses this value to left align this and all other strings with smaller lengths “equally” adding white spaces to compensate the smaller strings.

One really import thing to take into consideration when doing what this post proposes is to use a monospaced font or fixed-width font, because its letters and characters each occupy the same amount of horizontal space. If you don’t use this kind of font, you won’t get the desired result.

This is the Razor view code:

<div id="reports">

@Html.LabelFor(m => m.Assessments)&nbsp; @Html.DropDownListFor(m => m.AssessmentId, Model.Assessments, string.Format(Localization.SelectValue2, Localization.Assessment), new { data_bind="value: selectedAssessment" } )

</
div>

So in order to make it work I added this CSS code:

#reports select
{
    font-family: 'Courier New'; /* well known monospaced font */
    width: auto;
}

Happy C# dynamic text aligning to everyone!

Debugging Microsoft Web Deploy Visual Studio publishing errors

This post is intended for starters with MS Web Deploy as is my case… Shifty

Microsoft Web Deploy is so awesome that I think it’s one of the best features one has at their disposal when developing with the .NET Framework and for the Web with ASP.NET MVC for example. It’s so powerful that it can even publish a database.

Once upon a time (let’s say before 2010) there was no Web Deploy and you had to FTP to the server to deploy the application. This was a tiresome task and led to many errors because one had to be extremely careful of what files needed to be updated, added, removed, etc while installing the application on the server. Backup methods should be in place in case something went wrong. I used to use compressed files (.zip or .rar) to send the app’s files to the server. It was still a big upload in some cases. I had to wait patiently. Once there I had to uncompress the file. Everything needed to be moved into place to make things easier. I even created a step by step readme file to help other peers do the deploy on the server. This readme detailed the workflow that should be followed in order to get things working.

Thanks God today there’s Web Deploy and it changed things drastically: only new or updated files are uploaded to the server. No more long waiting periods to start using the application. As a bonus you also have the option of removing additional files on the server (files/folders that aren’t used anymore). All this happens automatically (could we say automagically) with the click of a button inside Visual Studio 2010 or 2012. You can also run a .cmd file in the command line. This .cmd file is created as part of the Web Deploy Package publish method that you can choose once inside Visual Studio. There’s so many awesome features (read Preview menu option in Figure 4 bellow) that they would not fit in this post… To get a full understanding about Web Deploy look at this post: Visual Studio 2012 RC Deployment Docs.

Well, 2 weeks ago I tried to solve a problem related to Web Deploy. You can read the full history here:

Visual Studio 2012 Web Deploy to Windows Server 2008 R2 with IIS 7 and /msdeploy.axd 404 error

The above problem wasn’t solved but I can tell you that I learned a LOT about IIS administration during that weekend. As a result it was worth the effort. I think that a clean install of Windows Server 2008 is necessary in that case…

Today I was facing a different error (again working against Windows Server 2008 R2) and I followed a simple path to solve it. So here are the basic steps you need to follow to detect the problem’s origin:

Visual Studio 2012 Publish project with Web Deploy and Validate Connection errorFigure 1 - Visual Studio 2012 Publish project with Web Deploy and Validate Connection error

As you see when I clicked the Validate Connection button I got a message: ERROR COULD NOT CONNECT TO REMOTESVC.

If you click the error message, there’s some more info about the error but it doesn’t really tell you what’s causing the problem.  It’s kind of a generic message you get: go check the Web Management Service on your server… I think I don’t need to tell you that it’s started already! Steaming mad

Figure 2 - Visual Studio 2012 Publish project with detailed ERROR informationFigure 2 - Visual Studio 2012 Publish project with “detailed” ERROR information

To really get to the problem, you’ll need to access the server you’re trying to deploy to. Once there go to this folder:

C:\inetpub\logs\wmsvc\W3SVC1

This is the standard path where Web Management Service logs what’s going on…

When I opened the latest .log file I saw this:

#Software: Microsoft Internet Information Services 7.5
#Version: 1.0
#Date: 2012-07-26 15:50:30
#Fields: date time s-ip cs-method cs-uri-stem cs-uri-query s-port cs-username c-ip cs(User-Agent) sc-status sc-substatus sc-win32-status time-taken
2012-07-26 12:50:30 192.168.100.77 HEAD /msdeploy.axd site=Default%20Web%20Siste 8172 - 189.24.83.277 - 401 2 5 1918
2012-07-26 12:50:33 192.168.100.77 HEAD /msdeploy.axd site=Default%20Web%20Siste 8172 develop
189.24.83.277 - 550 0 0 2761

As you see highlighted in orange is my developer machine IP address. This let’s me know that my connection to server is working as expected. Port 8172 is not blocked by the firewall, etc.
Highlighted in yellow is a sc-status = 550. This is the key part while debugging errors related to web deploy on the server. Now it’s far easier to know what’s the problem. It’s only a matter of Googling about the 550 status code. The first post that mentions this status code was this one:

Status code 550 when using Msdeploy

The guy lost 1 day to find what was going on and it took me only 1 minute to figure out the error I had with his help. He talks about the site’s name displayed in IIS manager. So I went check mine and to my surprise I had a small mistake in the Site/application name field shown in Figure 1. I typed Default Web Siste instead of only Default Web Site. What a silly mistake!

This is the kind of error that can bother you more than it should… believe it or not. You can go the wrong way while trying to get things working as expected.

After correcting this mistyped named I clicked the Validate Connection button again and to my delight and surprise I got this beautiful green check mark:

Visual Studio 2012 Publish project with Web Deploy and successful connection validationFigure 3 - Visual Studio 2012 Publish project with Web Deploy and successful connection validation

Now if you desire select the Preview menu option to glance at what’s going to the server…

Visual Studio 2012 Publish project with Web Deploy and Previewing the changes
Figure 4 - Visual Studio 2012 Publish project with Web Deploy and Previewing the changes

You can select just the files you want to deploy. This is super useful let’s say when you discover a bug in production and want to change something in whatever file to correct that bug. You already have more changes to pull to the server but you just want to correct that bug. With the Preview tab you can do this: select just the file(s) you changed to correct the bug and deselect all the others. Isn’t this awesome? Of course it is!

If it’s OK, just hit the Publish button and you’re good to go.

I hope this simple post helps you find the root cause of what’s causing errors while you’re trying to deploy your application using MS Deploy.

References
Configuring a Web Server for Web Deploy Publishing (Remote Agent)

Installing and Configuring Web Deploy

Web Deploy error codes

Validating Date with MVC Foolproof Validation on the client side

This is a quick tip for something that I just tried with an ASP.NET MVC app and that worked as expected.

I use MVC Foolproof Validation to complement the standard validators that come with ASP.NET MVC in the System.ComponentModel.DataAnnotations assembly. Foolproof has some awesome validators like:

[Is]
[EqualTo]
[NotEqualTo]
[GreaterThan]
[LessThan]
[GreaterThanOrEqualTo]
[LessThanOrEqualTo]
[RequiredIf] [RequiredIfNot] [RequiredIfTrue] [RequiredIfFalse] [RequiredIfEmpty] [RequiredIfNotEmpty] [RequiredIfRegExMatch] [RequiredIfNotRegExMatch]

You can get it through a NuGet package here.

Let’s say you have a form with a DateTime field called “Show Until” that is part of a Notice object. This property stores a date value that should be in the future obviously. It makes no sense to set a date in the past for this field. So the question is: how can you get client side validation for this field without the need of going to the server to compare the date the user entered with today’s date?

This is what this post will show you…

This is the model property decorated with the respective data annotation GreaterThanOrEqualTo:

[Required(ErrorMessageResourceName = "Required", ErrorMessageResourceType = typeof(Localization))]
[Display(Name = "ShowUntil", ResourceType = typeof(Localization))]
[GreaterThanOrEqualTo("Today", ErrorMessageResourceName = "GreaterThanOrEqualTo", ErrorMessageResourceType = typeof(Localization))]
public DateTime ShowUntil { get; set; }

Pay attention to that "Today", string value. It tells Foolproof’s validator to compare the ShowUntil property with a property called Today (the dependent property). Wait a moment: the Notice object doesn’t have a property called Today since it’s not necessary. What’s the point? Confused smile

Now let’s add a partial class to extend the Notice class with a property called Today. This property returns Today’s date of course.

public partial class Notice
{
    public DateTime Today
    {
        get { return DateTime.Today; }
    }
}

Run the app now, enter a date in the past for the ShowUntil field and submit the form. You’ll see that a postback is made to the server and only after that the validation error message is shown to the user. Foolproof’s validator doesn’t know what’s the value of Today yet since it’s not part of the form data being edited. Remember: this kind of server side validation is not what we want. We want client side validation. We don’t want this data round-trip to the server just to validate one field in the form. So, how to solve this? It’s pretty simple…

Inside your form view (.cshtml file) since I’m using C# as the programming language and Razor view engine, add this hidden field:

@Html.HiddenFor(model => model.Today)

Now reload the page and try entering a date in the past like yesterday’s date. You’ll see that the user gets the validation error message instantly. Why? Because now Foolproof’s jQuery validator that is added to page has Today’s date value present in the form’s HTML output (that’s the purpose of the hidden field). If you look at the form/page source code in the browser (right click the browser window and select “View Page Source” in Firefox), you’ll se this value:

<input data-val="true" id="Today" name="Today" type="hidden" value="29/06/2012 00:00:00" />

That’s it. No date in the past is allowed when adding a new Notice to the system.

This use case can be considered a good use for Hidden fields. They serve a multitude of purposes…

Hope it helps.

Updated at 12:45 PM

You see how things are... after posting this I just discovered a really straightforward way of getting what I wanted (by chance) I can tell you. I wasn’t looking for this anymore when I hit this StackOverflow question. Looks like God took me there… Open-mouthed smile I happen to be using jQuery UI Datepicker control too. It has between its vast array of options a minDate property. So if you do this:

<script type="text/javascript">

    $(document).ready(function ()
    {
        $("#ShowUntil").datepicker('option', 'minDate', new Date());
    });

</script>

new Date() is Today in Javascript and so the datepicker won’t allow the selection of dates in the past. One word: AWESOME. One liner with jQuery help!

Leniel’s Software House (software customizado para seu negócio)

Windsor dependency injection in ASP.NET MVC filter attributes

I learn so much each day that I don’t have time to post about every interesting thing I discover.

Generally I get to these discoveries/solutions to overcome a wall that somehow appears while developing a given functionality.

I use Castle Windsor as my Inversion of Control [ IoC ] container. Recently I’ve been implementing some features that depend heavily on ASP.NET MVC action filter attributes and at some point I needed to get a reference to a service that hits the database for some data checking rules. Unfortunately one cannot ask a Windsor container to give back a dependency when inside an attribute because as Krzysztof Koźmic (the developer of Windsor) says in his answer for the question: Injecting dependency into CustomAttribute using Castle Windsor at StackOverflow:

You can't. Attributes are metadata. Putting behavior into them is wrong. Putting dependencies is even worse.

Although I understand the point I Googled a little bit more and found this great post by Dino Esposito called ASP.NET MVC: Resolve or Inject? That’s the Issue…. In this post Dino shows how to use ASP.NET MVC extension point called DependencyResolver that sits here System.Web.Mvc.DependencyResolver. It simplifies service location and dependency resolution…

With this I was able to do the following in a custom WindsorDependencyResolver.cs class:

public class WindsorDependencyResolver : IDependencyResolver
{
    private readonly IWindsorContainer _container;

    public WindsorDependencyResolver(IWindsorContainer container)
    {
        _container = container;
    }

    public Object GetService(Type serviceType)
    {
        return _container.Kernel.HasComponent(serviceType) ? _container.Resolve(serviceType) : null;
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        return _container.Kernel.HasComponent(serviceType) ? _container.ResolveAll(serviceType).Cast<object>() : new object[] { };
    }
}

The above code I took from this great question at StackOverflow: Castle Windsor Dependency Resolver for MVC 3. There’s an extensive list of useful info there.

In the container bootstrap code inside Global.asax file we put this class into use:

private static void BootstrapContainer()
{
    _container = new WindsorContainer().Install(FromAssembly.This());

    var controllerFactory = new WindsorControllerFactory(_container.Kernel);

    ControllerBuilder.Current.SetControllerFactory(controllerFactory);

    // Create and register the resolver
    var resolver = new WindsorDependencyResolver(_container);
    DependencyResolver.SetResolver(resolver);
}

See how we’re passing Windsor’s app container to the Dependency Resolver. This way when we ask the DependencyResolver for a service/repository/whatever it’ll get it from the container and we’ll take advantage of the container’s powerful capabilities. You can read about such awesome capabilities in this series of posts called Windsor tutorial - ASP.NET MVC 3 application (To be Seen) written by Windsor’s developer (Krzysztof Koźmic).

Now it’s just a matter of using the Dependency Resolver for our benefit:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        // Make sure the user is authenticated.
        if (httpContext.User.Identity.IsAuthenticated == false)
            return false;

        // If User has the "SuperUser" role he can surf all the app...
        if (httpContext.User.IsInRole(AccountController.SuperUser))
            return true;

        var permissionService = DependencyResolver.Current.GetService(typeof(PermissionService)) as PermissionService;

        return permissionService.UserHasPermission(httpContext);
    }
}

The real good thing about the Dependency Resolver is that once you set the resolver you can call it throughout your ASP.NET MVC…

OK. It diverges from Krzysztof’s main point that one should not put behavior in attributes, but it does the job and is working as expected in my case.

This has helped me to continue my development and I hope it’ll also help you.

User Password Expired filter attribute in ASP.NET MVC

A recent set of requirements I’ve been playing with deals with passwords. This one specifically handles password expiration.

Given that I’m working with ASP.NET MVC I know I can rest assured that there’s some great (read awesome) way of implementing a given requirement. This is exactly what happened and I want to show you how to have a clean and beautiful solution to this problem.

So my client’s requirement is the following:

Passwords should expire in 45 days.

I’m currently using the default ASP.NET membership provider. It gives you a database schema ready to manage users and roles. You just have to use ASP.NET Configuration Tool to create Roles and Users, decorate your Controllers/Actions with the Authorize attribute and you’re good to go most of the time. The default membership provider allows a fast project start – no doubt – but as always there’s something that must be done according to the infinitude of possible requirements that change project by project. One of these not contemplated things is a setting in the default provider for handling user’s password expiration. We have to roll our own code to manage this.

My friend Google told me that some folks have already done some work related to this and as always I borrow some of their code and adapt it to my specific case/technology.

First I created a PasswordExpiredAttribute that derives from/extends the AuthorizeAttribute. Here’s its code:

public class PasswordExpiredAttribute : AuthorizeAttribute
{
    private static readonly int PasswordExpiresInDays =
int.Parse(ConfigurationManager.AppSettings["PasswordExpiresInDays"]);

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        IPrincipal user = filterContext.HttpContext.User;
           
        if(user != null && user.Identity.IsAuthenticated)
        {
            MembershipUser membershipUser = Membership.GetUser();

            TimeSpan ts = DateTime.Today - membershipUser.LastPasswordChangedDate;

            // If true, that means the user's password expired
            // Let's force him to change his password before using the application
if (ts.TotalDays > PasswordExpiresInDays) { filterContext.HttpContext.Response.Redirect( string.Format("~/{0}/{1}?{2}", MVC.Account.Name, MVC.Account.ActionNames.ChangePassword, "reason=expired")); } } base.OnAuthorization(filterContext); } }

As you see, the code goes inside the OnAuthorization overridable method. I get the PasswordExpiresInDays setting from the Web.config <appSettings> section. This gives an easy way to change the requirement in the future without the need of recompiling the whole app.

<appSettings>
    <add key="PasswordExpiresInDays" value="45" />
</appSettings>

The code explains itself but let’s go through it:

1 - If the User is authenticated, let’s get his membership data;
2 - A TimeSpan is useful for getting the difference in days between Today and the last time the user changed his password ( LastPasswordChangedDate )
3 - Check if the TimeSpan.TotalDays is greater than the PasswordExpiresInDays setting we got from the Web.config file. If true the user must change his password and we redirect him to the ChangePassword view.

Note 1: I’m using T4MVC to retrieve the Controller and Action names in the code above. You should take a look at it! Really…

Note 2: See that "reason=expired" in the response redirect URL? I’m using this querystring as a route parameter inside the ChangePassword action method to display a message to the user informing him that he’s being asked to change the password because it has expired.

/// <summary>
/// This allows the logged on user to change his password.
/// </summary>
public virtual ActionResult ChangePassword(string reason)
{
    var viewModel = new ChangePasswordViewModel();

    if (reason != null)
    {
ShowMessage(Infrastructure.Notification.MessageType.Warning, Localization.PasswordExpired, true); } return View(viewModel); }

By the way: I use MvcNotification infrastructure by Martijn Boland to display beautiful messages to the user.

OK, getting back to the main point… now it’s just a matter of applying the PasswordExpiredAttribute filter to every controller of the app but the AccountController. With ASP.NET MVC 3 it’s easy to apply a filter to every controller and action using GlobalFilters. Instead of going controller by controller to add this attribute we can just register it as a global filter in the Global.asax file:

public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
    filters.Add(new HandleErrorAttribute());
filters.Add(new AuthorizeAttribute());
filters.Add(new PasswordExpiredAttribute()); }

Doing so the PasswordExpiredAttribute will be executed for every controller and action but there’s a problem with the above approach. Since it’s a global filter, it’ll be executed even for the AccountController. Remember: we don’t want it to be executed for the AccontController… How can we exclude a global filter from a single controller or action? To achieve this, there’s an awesome thing we can do: create a ExcludeFilterAttribute and a ExcludeFilterProvider. WOW, ASP.NET MVC has a Filter Provider that gives us even more power when working with filters. Look here for the complete story: Exclude a Filter by Ori Calvo. I’ve uploaded the source code files here: ExcludeFilterAttribute.cs and ExcludeFilterProvider.cs

Now it’s just a matter of decorating the AccountController with the ExcludeFilter attribute like this:

[ExcludeFilter(typeof(PasswordExpiredAttribute))]
public partial class AccountController : BaseController
{
...
}

The ExcludeFilter attribute explicitly tells the ASP.NET MVC runtime to ignore the PasswordExpiredAttribute for the AccountController.

With this in place, once the logged in user tries to access any part of the site and his password is expired, he'll be redirected to the ChangePassword view and won't be allowed access to anywhere else in the site until he changes the password. This is great and the requirement is implemented.

Of course in software there are multiple ways of doing the same thing. If you know of any better option, please share you knowledge in the comments.

Hope it helps.

Bonus
While working on this requirement I posted a question at StackOverflow regarding the use of Web.config settings as magic strings. I’ve found a nice way to let the code a little bit cleaner. So, if you want a nice way to access your Web.config app settings as properties with compile time checking and nice error handling, you can do as described here: T4MVC for Web.config <appSettings>

This is a much better/cleaner code IMO (see the AppSettings class that was automatically generated with the T4 template):

public class PasswordExpiredAttribute : AuthorizeAttribute
{
    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        IPrincipal user = filterContext.HttpContext.User;

        if (user != null && user.Identity.IsAuthenticated)
        {
            MembershipUser membershipUser = Membership.GetUser();

            TimeSpan ts = DateTime.Today - membershipUser.LastPasswordChangedDate;

            // If true, that means the user's password expired
            // Let's force him to change his password before using the system
            if (ts.TotalDays > int.Parse(AppSettings.PasswordExpiresInDays))
            {
                filterContext.HttpContext.Response.Redirect(
                    string.Format("~/{0}/{1}?{2}", MVC.SGAccount.Name, MVC.SGAccount.ActionNames.ChangePassword,
                    "reason=expired"));

            }
        }

        base.OnAuthorization(filterContext);
    }
}

References:
ASP.NET MVC Authentication - Global Authentication and Allow Anonymous by Jon Galloway

ASP.NET MVC Authentication - Customizing Authentication and Authorization The Right Way by Jon Galloway

Exclude a Filter by Ori Calvo

Introducing System.Web.Providers - ASP.NET Universal Providers for Session, Membership, Roles and User Profile on SQL Compact and SQL Azure by Scott Hanselman

Conditional Filters in ASP.NET MVC 3 by Phil Haack

T4MVC by David Ebbo