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

Resize image on the fly with ASP.NET MVC

I built a piece of code sometime ago and today I decided to optimize it.

My use case is this: a user can upload some photos of his house for example. Image dimensions (height x width) are not restricted. The user can upload any photo as long as its size is less than or equal to 750 KB.

Then, I have a listing page (Index.cshtml) that has a WebGrid. The grid shows realties available for sell, rent, etc. In this grid I want to display just a thumbnail of a given photo (the first one I grab as per code bellow) for each realty. I placed a constraint such that the thumbnail dimensions must be 100x100 pixels. Of course one shouldn’t load the full size version of a photo just to show it on the grid. The grid has 10 rows per page and if the images are on the range of 500 KB, the load put on the user connection to transmit all those photos from the server to the client would be high: 10 x 500 KB ≃ 5 MB. This would be an unresponsive page! No doubt…

Googling a little bit I stumbled upon something I didn’t know yet. It’s called WebImage and comes in System.Web.Helpers just as the WebGrid I discussed earlier. With this little kid on the block, one can have a controller “action” that does something like this:

public void GetPhotoThumbnail(int realtyId)
{
// Loading photos’ info from database for specific Realty...
var photos = DocumentSession.Query<File>().Where(f => f.RealtyId == realtyId); if (photos.Any()) { var photo = photos.First(); new WebImage(photo.Path) .Resize(101, 101, false, true) // Resizing the image to 100x100 px on the fly... .Crop(1, 1) // Cropping it to remove 1px border at top and left sides (bug in WebImage) .Write(); } // Loading a default photo for realties that don't have a Photo new WebImage(HostingEnvironment.MapPath(@"~/Content/images/no-photo100x100.png")).Write(); }
Calling the .Write() method does the magic. As you can see, I’m not saving the thumbnail in the disk, that is, a new image is generated on the fly/dynamically and sent to the user’s browser. Amazing…
In a view using the Razor syntax one would have something like this to display the photo:
<img src="@Url.Action("GetPhotoThumbnail", new { realtyId = item.Id })" width="100" height="100"/>
Another useful variation/overload of the above action method is this one (even more dynamic):
public void GetPhotoThumbnail(int realtyId, int width, int height)
{
    // Loading photos’ info from database for specific Realty...
    var photos = DocumentSession.Query<File>().Where(f => f.RealtyId == realtyId);

    if (photos.Any())
    {
        var photo = photos.First();

        new WebImage(photo.Path)
            .Resize(width, height, false, true) // Resizing the image to 100x100 px on the fly...
            .Crop(1, 1) // Cropping it to remove 1px border at top and left sides (bug in WebImage)
            .Write();
    }

    // Loading a default photo for realties that don't have a Photo
        new WebImage(HostingEnvironment.MapPath(@"~/Content/images/no-photo100x100.png")).Write();
}
Then, in the view one would call the action passing the width and height variables as per requirement:
<img src="@Url.Action("GetPhotoThumbnail", new { realtyId = item.Id, width = 100, height = 100 })" />
There are a handful of available functions in a WebImage. You should really check them out.

You can find more insightful info about the WebImage class reading this post by Gunnar Peipman: ASP.NET MVC 3 Beta: Simple image manipulations using WebImage helper

Note: there really are better ways of handling this kind of situation (adding image caching, etc – see ImageResizer) but for the site I’m working on, the solution I show in this post is sufficient and pretty responsive right now.

Hope it helps.

Hide table column and colorize rows based on value with jQuery

This is a handy piece of code that I used last year in one of my projects. I had scheduled to post it but it was just after I saw this question at StackOverflow that I decided to write about it. So here it is…

Let’s say you want a nice UI experience and to achieve that you wanna colorize/highlight a table row according to a given value present in a column of this row.
This is a simple task when we use jQuery.

I use the WebGrid that comes with ASP.NET MVC to display data on a web page using an HTML <table> element. It’s available in the namespace System.Web.Helpers. The approach described in this post is useful not only with the WebGrid but with any framework/language you use to output HTML code since the manipulation is done on the client side with jQuery.

Take this screen as an example:

HTML table with last column Active to be hidden displaying values Yes and NoFigure 1 - HTML table with last column Active to be hidden displaying values Yes and No

We want hide the last column “Active” and color the row which has a value Yes in this same column.

The above statement can be accomplished with the following code:

(function ($)
{ hideColumnColorRow = function (column)
{ $(
'td:nth-child(' + column + '),th:nth-child( ' + column + ')').hide(); $('tr').find('td:nth-child(' + column + '):contains(Yes)').parent().css('backgroundColor', 'LightGreen'); // Could be an hexadecimal value as #EE3B3B };
})(jQuery);

The hideColumnColorRow function* takes the column number as a parameter. It hides the column <td> and its header <th> using jQuery’s supper useful nth-child selector. Then for each table row <tr> it traverses the row’s columns and looks at the value of each column using :contains selector. If it finds a value = ‘Yes’ it’ll assign a background color to the column’s parent, that in this case is the <tr> (the row) using its CSS backgroundColor property.

So, taking Figure 1 as an example, the above code can be used in an ASP.NET MVC view this way:

<script type="text/javascript">

    $(document).ready(function ()
{
hideColumnColorRow(5); // Hiding the 5th column and colorizing the row for which this column has a value = Yes
});
</script>

* I’ve placed the jQuery/JavaScript function inside a file named custom.js. It resides inside the Scripts folder of the sample app available here. There’s no need to reference this script file in the view page because with the introduction of ASP.NET 4.5 we now have an all new Bundling and Minification Support for CSS and JavaScript files.

When the the app is run, this is the result:

HTML table with column Active hidden and highlighted rows based on its valueFigure 2 - HTML table with column Active hidden and highlighted rows based on its value

This is a really interesting requirement that one can implement in no time thanks to the power of jQuery. jQuery is one of the most fascinating things when we talk about software development. Its creator “John Resig” should be awarded a Computer Science Nobel Prize if that existed. Well it could be the Turing Award.

Anyone should take a look at jQuery and start using it as early as possible. It’s a must have today. I simply love it! Coração vermelho

Source code
I’ve put together a sample ASP.NET MVC 4 (uses NET Framework 4.5) so that you can try this out. You can run the app using the recently launched Visual Studio 11 Beta. You can download the free Visual Studio 11 Express Beta for Web here and the app code here.

Hope it helps.

Installing Brazilian Portuguese dict. in Sublime Text 2

Today I downloaded one more dictionary to use with Sublime Text 2. Sublime Text is a multipurpose text and code editor. So far the best IMHO. I want to spell check my Portuguese texts of course. I followed the instructions described here to grab an additional dictionary.

From that page we have that:

Sublime Text uses Hunspell for its spell checking support. Additional dictionaries can be obtained from the OpenOffice.org Extension List

I then headed to OpenOffice.org to search for a pt-BR dictionary. I found it and then when I downloaded it from http://extensions.services.openoffice.org/en/project/Vero I got a file with a different extension (.oxt) of that used by Sublime Text 2. More on this bellow…

The file name is Vero_pt_BR_V208AOC.oxt.

Using Mac OS I tried to place this file inside this folder

/Users/leniel/Library/Application Support/Sublime Text 2/Packages/User

following the instructions given by Sublime Text 2 doc.

Closed Sublime Text 2 and reopened it. Went to the menu View > Dictionary and the new dictionary wasn’t there.

Well, something is plain wrong here. The already installed dictionaries that come with Sublime Text are present in this folder:

/Users/leniel/Library/Application Support/Sublime Text 2/Packages/Language - English/

Inside the above folder there are two English dictionaries with file extensions: .aff and .dic.

A little bit more thinking and I tried what could do the trick. I renamed the downloaded dictionary file from Vero_pt_BR_V208AOC.oxt to Vero_pt_BR_V208AOC.rar. Opened the compressed file and to my surprise there they were… extracted the files pt_BR.aff and pt_BR.dic. Easy as pie.

It turns out the .oxt file is just a wrapper…

I renamed the folder Language – English to just Languages and placed the files pt_BR.aff and pt_BR.dic in this folder. Closed Sublime Text 2 and reopened it. The new dictionary appeared:

Sublime Text 2 Dictionary menu option listing the pt_BR dictionary just addedFigure 1 - Sublime Text 2 Dictionary menu option listing the pt_BR dictionary just added

Hope it helps.