JQuery Validation Hooks – ASP.Net MVC
0ASP.Net MVC comes with some great JQuery validation features, but sometimes you need just a little more to accomplish your task. I recently was trying to take advantage of Twitter Bootstrap’s error highlighting. If you have used JQuery validation in MVC, you’ll notice that it only marks the input that failed to validate, but doesn’t do much else. This is great for highlighting the field, but I needed to highlight the label, the helping text, and the input that I have present in my form.
I knew JQuery has a feature to let you bind to events, but I wondered if someone had already run into my particular situation. Surely someone had, and they created a great addition to ASP.Net MVC unobtrusive file that let’s you bind to different events. It’s called jQuery Validate Hooks.
The library let’s you:
- Find out when our form’s client-side validation runs and do something custom, if it fails
- Find out when a particular element’s client-side validation runs and do something custom if it passes or fails
Check it out it’s awesome. jQuery Validate Hooks.
Ultimately my code to utilize this library looked like this:
$(function () {
// Validation
$('form').addTriggersToJqueryValidate().triggerElementValidationsOnFormValidation();
$('form').formValidation(function (element, result) {
$(element).find('input').each(function (index, value) {
markControlGroup(value);
});
});
$('form input').on('keyup', function () {
markControlGroup(this);
});
});
function markControlGroup(input) {
var el = $(input);
if (el.hasClass('input-validation-error')) {
el.parents('div.control-group').addClass('error');
} else {
el.parents('div.control-group').removeClass('error');
}
}
With the end result looking like this on my form.

That’s pretty cool, and the code above still leverages all the existing validation code that I have. I love JQuery and thanks to the author of this little script, because it is amazing. Also thanks to Twitter for Bootstrap.
Setting up ASP.Net MVC Error Pages
0My focus as a developer is to give the end user the best application I can. With the focus being on feature development and quick turn around, sometimes bugs get through, even with an extensive suite of unit tests. I also have to be mindful that my set of users includes bots: Google, Bing, and yes Yahoo.
Bots are important in helping your site thrive in the ever growing market of the internet. It is important to communicate correctly to them. Think of them as your official ambassadors to your community of users. If the bots are confused, then they will not portray the correct information to the real live people you want using your site.
Error pages are important in communicating what is a page I want indexed, or what is a page that can be disregarded. Bots normally only show pages that return a 200 (OK) status in results pages. Other statuses do not show up regularly at the top of a search results page.
Question: How do I ensure that my ASP.Net MVC pages are returning the correct status code?
Answer: Setup, Setup, Setup.
There is nothing glamorous about this post, but it is fundamental to security and the overall health of my site’s public image.
Step 1: Web.Config
Config is tricky for several reasons, you want to cover the major errors, and you want the status code to be correct when the page displays your nice error page.
<customErrors mode="RemoteOnly" redirectMode="ResponseRewrite" defaultRedirect="~/Error/500"> <error statusCode="403" redirect="~/Error/403" /> <error statusCode="404" redirect="~/Error/404" /> </customErrors>
Note: For IIS7 users (which should be everyone now), remember to put this in the system.webServer section. This forces IIS7 to let your application handle errors. Without this you’ll get the ugly gray error screens that are par for IIS7.
<httpErrors existingResponse="PassThrough" />
The thing to take away from the configuration above is that the redirectMode is set to ResponseRewrite. This insures that when a page errors on /hello/kitty, it stays on /hello/kitty. This tells the user that this page is borked, and also any bot that might have traveled their. The redirects are pointing to an error controller, but before we get to the controller let’s look at how the routes are set up.
Step 2: Route Setup
Routes are very important, I cannot stress this enough. If you are using the default route setup that comes with Asp.Net MVC then DON’T!!! The default catch all is terrible for many reasons, but the biggest reason is that it will catch urls that have no relevance in the application itself. This will confuse search engines, and ultimately users who see those crazy results in the search engine results.
After meticulously crafting your routes, you will need these two additional routes.
routes.MapRoute(
"Error",
"Error/{status}",
new { controller = "Error", action = "Index", status = UrlParameter.Optional }
);
routes.MapRoute(
"404",
"{*url}",
new { controller = "Error", action = "Index", status = 404 } // 404s
);
The first route should be familiar looking. It is what will catch the redirects from the configuration. The second route is a catch all. Yes I just admonished you for having a catch all route, but this one is different. We have a catch all for mistakes. Think of it as a safety net for a trapeze artist. It is important to have specifically defined you routes for this to work. The next step is create the controller.
Step 3: The Error Controller
public class ErrorController : Controller
{
public ActionResult Index(int? status)
{
var codes = Enum.GetValues(typeof (HttpStatusCode)).Cast<int>();
var httpCode = status.HasValue
? (int?)codes.FirstOrDefault(c => c == status.Value) ?? 500
: 500;
// insure response is the right code
Response.StatusCode = httpCode;
switch (httpCode) {
case 404:
ViewBag.Message = "The page you were looking for could not be found.";
break;
default:
ViewBag.Message = "An error occurred while processing your request.";
break;
}
return View("Error");
}
}
The thing to note here is the Response.StatusCode being set. It will ensure when you page is rendered that the resulting response is correctly tagged. Now you can craft a beautiful Error view and drop it in Shared or in the Error views folder. I usually drop mine in Shared.
Conclusion
Error pages are very important to get right, they communicate to your users and search engines that what they are currently looking at is a mistake and to ignore it. Hopefully they never see those pages, but when they do, they know that you are hard at work fixing the issue that caused them to see it in the first place.
Stay Code Thirsty My Friends.
Restful Routing – Documentation Site
0As a developer I always love finding projects that make my life easier. As a web developer I spend most of my time using ASP.Net MVC to do my development. If you’ve spent any time in an MVC framework, you know how cumbersome it can be to manage routes. With Restful Routing the thought and effort behind building your application’s routes is already done for you.
I’ve always loved Restful Routing and I am an active contributor to the project. This post is to try to get other developers excited about using this library.
The new documentation site was built using ASP.Net MVC 3 and RestfulRouting. It is a living guide of how to use the library to accomplish the different scenarios it affords.
Check it out @ RestfulRouting.com
Must Have NuGet Packages
0I am loving NuGet, and as it matures it just becomes more of a paradigm shift. How do you program without this thing? What was development like before it? So what are NuGet packages I am usually including in my projects. Here is a list of the them below, in no particular order.
- Depot (Common Caching)
- Dynamic Expression API (LINQ Extensions)
- ELMAH on XML (Error Logging)
- FileDB (a leap in storing files)
- SimpleMembership
- ValueInjecter
- WebActivator
- RhinoETL
- FluentMigrator
- RestfulRouting
- JQuery
- FluentValidation
- Entity Framework Code First
- NUnit
- Moq
- WaTin
- RestSharp
- MvcFlash (yes I am bias
)
Great respect goes out to these projects and their contributors, except MvcFlash cause I don’t want to strain my arm patting myself on the back
.
Update: How could I forget about MvcMailer.
How to Increase Decimal Precision in Entity Framework
0So you are saving your decimal values to the database, but you are noticing that they are being rounded. Not what you want, because you want to be as close as you can be. If you are using entity framework you just need to add this little snippet to your OnModelCreating method in your DataContext.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Address>()
.Property(m => m.Latitude)
.HasPrecision(19, 5);
modelBuilder.Entity<Address>()
.Property(m => m.Longitude)
.HasPrecision(19, 5);
}
The example above makes sure that my latitude and longitude at least have a precision of 5. Make sure you database reflects this precision.
Capitalize First Letter of Every Word (C#)
5I hate non uniform data, I really do. It’s one of those things that a client will enter into the system a thousand times incorrectly with no rhyme or reason. It is also followed by the eventual, can you fix these million records so they are correct. Ugh! What?!? Ok, so you can fix it in your database or create code at display time to fix it. I always opt for the second, since you can’t trust your users to stop doing what they have been doing. So here is code to nicely display peoples names, cities, or whatever needs to the first letter capitalized.
public static string CapitalizeFirst(this string input)
{
if (string.IsNullOrEmpty(input)) {
return input;
}
var words = input.Split(new [] {' '}, StringSplitOptions.RemoveEmptyEntries);
var result = words.Select(w => w[0].ToString().ToUpper() + w.ToLower().Remove(0, 1)).Aggregate((s,w) => s + ' ' + w );
return result.Trim();
}
Not rocket science, I know but still equally helpful.
LamdaComparer – A Must Have Snippet
1I found this blog post about LambdaComparer and it is a must have snippet if you are doing anything with LINQ. Check it out http://brendan.enrick.com/post/linq-your-collections-with-iequalitycomparer-and-lambda-expressions.aspx
Enums to SelectList
0So you have an Enum and you want to get a human readable SelectList. Well here is the code to do that. The caveat here is that your enum class must be decorated with a description attribute. T in this case is your type of enumeration. Use it like Eums.ToSelectList<InterestTypes>();
public static class Enums
{
public static SelectList ToSelectList<T>() {
var type = typeof (T);
if (type.IsEnum) {
var list = new List<object>();
var members = type.GetMembers(BindingFlags.Static | BindingFlags.Public | BindingFlags.GetField);
foreach (var memberInfo in members) {
var attribute = memberInfo.GetCustomAttributes(typeof (DescriptionAttribute), false).FirstOrDefault() as DescriptionAttribute;
var value = memberInfo.Name;
list.Add(attribute != null
? new {Text = attribute.Description, Value = value}
: new {Text = value, Value = value});
}
return new SelectList(list, "Value", "Text");
}
throw new Exception("this method is purely for enumerations.");
}
public static T Parse<T>(string input)
{
return (T)Enum.Parse(typeof (T), input, true);
}
}
public enum InterestTypes : int
{
[Description("Attractions")] Attraction = 1,
[Description("Events")] Event = 2,
[Description("Restaurants")] Restaurant = 4,
[Description("Schools")] SchoolDistrict = 5,
[Description("Featured Developments")] FeaturedDevelopment = 6,
[Description("Accommodations")] Accommodation = 7
}
I also threw in a generic enum parser helper for free, have fun.
MvcFlash – Quick Messages to Users
0At the early stages of NuGet I was worried. I was not about the idea since ruby gems is the core of Rails development, but because of the seemingly disjoint feeling of projects that were in the NuGet repository and the ones I wanted to use that were not in NuGet. Gladly the community has rallied, and now your favorite open source projects are just a click away from being in your solution. So I started looking at what I could do to contribute to this ecosystem. I sat down and looked at what I end up doing a lot and what other developers could benefit from. I also had never done a NuGet package, so this was a venture into that as well. Then it hit me, a simple flash messaging API that let’s you pass messages to your users in an ASP.NET web application. MvcFlash was born and I use it all the time now.
What it can do:
well it can flash specific kinds of messages that are helpful to your users. Below is an example of the calls you can make. Notice the simple interface, you just push a string in, but you can get fancy and push a contextual object in for that particular message. The cool thing about this as well is that you can pass anonymous objects up to the view and it will be handled correctly.
Flash.Notice("Hey, what's up?")
Flash.Error("oh no!");
Flash.Warning("sucks");
Flash.Success("WooHoo!");
Flash.Push(new {CrazyProperty = "I'm a mad man!"});
When you are ready to flash this message in your view, you just need to call.
@Html.Flash()
Simple enough, but you can get crazy with this if you need to divide your messages up into different sections.
// In The Razor View
// Simple Flash
@Html.Flash() // Flash everything, default template: "Flash"
@Html.Flash("MyOwnTemplate") // Flash evertying, custom template
@Html.Flash((ctx) => Html.Partial("Flash", ctx)) // Flash everything, lambda
// Flash Only
@Html.FlashOnly("success") // pass in the type
@Html.FlashOnly(new [] {"success", "error"}) // pass in many types
@Html.FlashOnly(x => x.Type == "success" || x.Type == "error") // pass in a lambda
// Flash Select
@Html.FlashSelect("success") // pass in the type, default template: "Flash"
@Html.FlashSelect(x => x.Type == "success") // pass in a lambda
@Html.FlashSelect("success", "template") // pass in the type filter, and the template name
@Html.FlashSelect(x => x.Type == "success", (ctx) => Html.Partial("Flash", ctx) ) // pass in a lambda
This is very flexible and you can do very cool things with it.
What it looks like:
MvcFlash comes with a default css file and images that give you amazing looking flash messages right out of the box. If you think they look gross, then you have the ability to style them anyway you want cause MvcFlash depends on a partial view and not embeded HTML code. You have full control over the output.
What to Expect:
At it’s core MvcFlash uses Session, so these messages are resilient when it comes to redirects. They will stick around as long as you haven’t Flashed them yet. In addition, you can replace your session provider with something like the AppFabric and get flash messaging across servers (I haven’t tried this yet). My goal was to make a flexible but instantly useful API here, so you can start using it as soon as you add this package to your solution. No time to setup, or do config mashing.
Conclusion:
Download this and give it a try, you might like it. If you do like it, rate it on NuGet. If you find a bug, please file it on GitHub.
Better Mapping with ValueInjecter
2I recently received an email from a Simon Gorski asking where the AutoMapper code went, and sad to say I deleted it from GitHub. Why did I do that, you may ask? Well after many moons of using AutoMapper I have moved on to better frameworks that can do this far easier for me. I didn’t want anyone using that code because it would be painful for them (it was for your own good, I promise). Currently I use ValueInjecter which is a convention based mapping framework and helps make mapping a negligible part of my work day. Oh the early days of my career, where I thought mapping was all there really was to do in programming. I’ve wised up and now I’m going to show you how you can spend almost no time doing your own mappings.
The code to this sample can be found on GitHub at https://github.com/khalidabuhakmeh/ValueInjecter-Sample
My sample is pure POCO, but I currently use the code first approach with Entity Framework in real world projects and this would also work with most ORMs. My sample is also written in an ASP.NET MVC application, so I’ll be making mention of controllers and actions, but this would work easily as nicely in any .NET application.
Let’s start with the final look and feel of your controller, how will this feel when you are developing with it?
Person Current {
get { return Session["Person"] as Person; }
set { Session["Person"] = value; }
}
[HttpGet]
public ActionResult Index() {
var model = Current.ToViewModel<PersonViewModel>();
return View(model);
}
[HttpPost]
public ActionResult Index(PersonViewModel model) {
Current = model.ToDomain(Current).Audit();
return RedirectToAction("Index");
}
The mapping code is one line in both my actions: From a domain model (EF, Linq2SQL, POCO) to a view model, from a viewmodel back to a domain model. Now if you are familiar with what happens originally with AutoMapper then you are dreading seeing the mapping classes that make this happen. Fear not, I’ll show you this in a second but you will see that there really isn’t much to it.
public static class Extensions
{
public static T ToDomain(this object source, T domain = default(T))
where T: class, new()
{
if (domain == null)
domain = new T();
if (source == null)
return domain;
domain.InjectFrom(source)
.InjectFrom<IgnoreAudit>(source)
.InjectFrom<FlatLoopValueInjection>(source)
.InjectFrom<UnflatLoopValueInjection>(source);
return domain;
}
public static T ToViewModel(this object source, T viewmodel = default(T))
where T : class, new()
{
if (viewmodel == null)
viewmodel = new T();
if (source == null)
return viewmodel;
viewmodel.InjectFrom(source)
.InjectFrom<FlatLoopValueInjection>(source)
.InjectFrom<UnflatLoopValueInjection>(source)
.InjectFrom<NullablesToNormal>(source)
.InjectFrom<NormalToNullables>(source)
.InjectFrom<IntToEnum>(source)
.InjectFrom<EnumToInt>(source);
return viewmodel;
}
public static T Audit( this IAudit<T> target, string user = "system")
{
if (!target.CreatedAt.HasValue) {
target.CreatedAt = DateTime.UtcNow;
target.CreatedBy = user;
}
target.UpdatedAt = DateTime.UtcNow;
target.UpdatedBy = user;
return (T) target;
}
}
I know, how boring. That’s it?!? Yes it is, this is all the code you will need to map from complex objects to your view models. Never again will you have to do trivial mapping (unless you like that sort of thing). I do also want to show you one more thing about the Audit method.
When you say Audit() on your objects you want to make sure that it doesn’t overwrite the previous values, even if there are values coming from somewhere else. These are read only values and the mapping should respect that. So I wrote a specific convention to make sure that these properties retain their original value regardless of what happens.
public class IgnoreAudit : ConventionInjection
{
private static readonly string[] AuditNames = typeof (IAudit).GetProperties().Select(p => p.Name).ToArray();
protected override bool Match(ConventionInfo c) {
var result = AuditNames.Contains(c.TargetProp.Name);
return result;
}
protected override object SetValue(ConventionInfo c) {
// don't override these values
return c.TargetProp.Value;
}
}
So it’s that easy to make sure those original values are respected.
My revelation when it comes to mapping is that I follow a lot of conventions and by doing so I save myself a ton of time coding. You can use this same technique to cut a lot of noise out of your own code base and make your intentions clearer. So here you go Simon (and anybody else). Hope this helps out. Please feel free to ask any questions.
The code to this sample can be found on GitHub at https://github.com/khalidabuhakmeh/ValueInjecter-Sample
