ASP.NET MVC

Don’t Moq it Up

0

So today I was going through my regular google reader list and came up Hadi Hariri’s Blog post on how to use mocking to unit test your controllers. Here is the post. I was reading it and thought it was a great way to use Moq and the right way to use Moq. If you are using Moq, you should read that post.

I’ve realized like any other tool, you need to use Moq sparingly or else your unit tests will become hellishly difficult to manage. So how do I unit test today? I unit test by getting back to basics.

Virtual Is Your Friend!

I’m sure this isn’t big news to anybody, but protected virtual is the best way to unit test your code. If you start yelling at me about code smell then I implore you to look at any of the fancy ORM tools you are using. They all use virtual to sneak in dynamic proxies and do what I am about to show you.

So you have a controller / class that has some strange external dependency and you just need a single value from this dependency. You don’t want anything more than a string value. Let’s look at what we have below.

public class HomeController : Controller {
	public ActionResult Index() {
		var urlReferer = Request.UrlReferer;

		return View("Index", new { urlReferer =  });
	}
}

Oh jeez, what are we going to do about that Request object? We could use Moq and get into a mess, or we can look at what we are actually trying to do. We just want the UrlReferer. So let’s do that, we will just get that value. Time to refactor.

public class HomeController : Controller {
protected virtual string UrlReferer {
get { return Request.UrlReferer; }
}

public ActionResult Index() {
return View("Index", new { urlReferer = UrlReferer });
}
}

Notice we moved the UrlReferer into its own property and we reduced the size of our index method. Next step is to write our unit test. I Use XUnit, but you can use any framework you like since there is no dependency on any particular library.

public class HomeControllerTests {

	[Fact]
	public void Can_test_home_index() {
		var test = new TestHomeController() { TestUrlReferer = "http://www.google.com" };
		var value = test.Index();
		Assert.IsNotNull(value);
	}

	public class TestHomeController : HomeController {
		public string TestUrlReferer {get;set;}
		protected override string UrlReferer { get { return TestUrlReferer; } }
	}

}

We have to inherit from HomeController and create a TestHomeController class. We override the UrlReferer property to inject our test value. Our final step is to write our unit test without having to worry about a crazy mocking library getting in the way.

The nice thing about this method is you can use it for any external dependency and it will always work. It also keeps your tests clear and doesn’t add a lot of overhead to your original classes. So go forward and unit test, and don’t let mocking get in your way.

JQuery Validation Hooks – ASP.Net MVC

0

ASP.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.

Form Validation

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

0

My 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

0

As 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

Enums to SelectList

0

So 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

0

At 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

2

I 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&lt;T&gt; 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

JavaScript Views for Easier Ajax (with JQuery)

2

I tweeted Phil Haack a while ago asking for a new feature in Asp.Net MVC 3. That feature was JavaScript views. What the heck is a JavaScript View? Well first, let’s define what the problem is and then you will see how JavaScript views can be very helpful. Let’s look at how we make an ajax request in JQuery


$.ajax({
  url: "test.html",
  cache: false,
  success: function(html){
    $("#results").append(html);
  }
});

Do you see a problem? You might not, because this is a valid statement. The problem is with the url property. It is hard coded to be “test.html” which might be ok for simple applications, but this can be problematic as your application gets larger.

Asp.Net 4 (or 3.5) to the Rescue

If you’ve been keeping up with Asp.Net then you know there is something new called routing. It allows you to define friendly urls. It is integral to Asp.Net MVC. From this point on, I will assume you know about Asp.Net MVC and routing. I have a complex site that has actions, several of which are purely for Ajax. The issue is that my routing scheme is still very experimental and I am still deciding on how to get the prettiest urls I can. What is very solid is the functionality each of these actions perform. So what is the challenge.

How do I dynamically inject urls into JavaScript by utilizing the Routes I have already defined?

Luckily the solution is very straightforward and easy to implement. Let’s look at how your JavaScript file might look like.

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>

$(document).ready(function() {
  $(".button").click(function() {
        $.ajax({
            type: "POST",
            url: "<%= Url.Action("Ajax","Home") %>",
            success: function(response){
            $(".result").html(response.message);
            }
        });
  });
});

Sweet right! Well it isn’t that easy. You have to set somethings up in your MVC project before this works.

Step 1 – Create a Controller

Create a controller specifically for handling dynamic JavaScript views.


public class JsController : Controller    {

public ViewResult Index(string file)        {

return View(file);

}

}

Step 1 is complete. We need a controller so that a RequestContext is passed to our JavaScriptView, without this our views will bomb. Let’s move on to Step 2.

Step 2 – Specify the Route


routes.MapRoute(

"JavascriptViews",

"js/{file}.js",

new { controller = "Js", action = "Index", file = UrlParameter.Optional });

We need this route, so that MVC handles requests and points them to our controller.

Step 3 – Create Your JavaScript View and Link it

 

Add a new view under a “Js” folder under the “Views” folder. That’s it! All you need now. You can start utilizing the tools inside of Asp.Net MVC to start generating routes. Technically, you could do a lot more than just generate routes, but I wouldn’t go crazy with using C# to generate your JavaScript files.


<script src="js/master.js" type="text/javascript"> </script>

Conclusion

This is a great way to manage the Urls in your JavaScript files without the concern of worrying about modifying all your JavaScript files just because you want a different route. Download my sample and see if you like it or you think I’ve gone completely insane.

JavascriptViewExample

FluentSitemap: Build Sitemaps for Asp.Net MVC

0

Building your site is only half the battle. Getting people to know it exists is the other half. If you are creating a public facing site, or even an intranet that utilizes an in-house search server then I have created a library just for you. The library is FluentSitemap. This library is designed to help you easily build sitemaps to be utilized by major search engines. The great thing about this library is that utilizes all your existing routes and controllers to build a sitemap even for the most complex Asp.Net MVC sites.

The FluentSitemap library can be found at GitHub Here.

How to use you, Let me count the ways

There are several ways you can utilize this library. The first is to specify each node manually. Let’s look at how that looks.

           // You can pass in a HttpContext from anywhere
            // in you application
            ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);

            // create sitemap node and set
            ISitemap sitemap = configurator.Create()
                .WithLocation("http://localhost.com/")
                .WithPriority(0.3)
                .WithChangeFrequency(ChangeFrequencyType.Never)
                .Set().Export();

The second is to use a controller/action pair.

        // You can pass in a HttpContext from anywhere
            // in you application
            ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);

            // Add From a controller and action
            ISitemap sitemap = configurator.Add("Home", "Index")
                .Add("Home", "About").Export();

The third is to use a route

       // You can pass in a HttpContext from anywhere
            // in you application
            ISitemapConfigurator configurator = new SitemapConfigurator(HttpContext);

            // Add From a controller and action
            ISitemap sitemap = configurator
                // Add From a Route
                .AddFromRoute("Default", new {id = "2"}).Export();

The last is to use the ISitemetadata. This is specifically there for IoC.

public class HomeControllerSitemapMetadata : ISitemapMetadata
    {
        private const string Home = "Home";

        #region ISitemapMetadata Members

        public void Create(ISitemapConfigurator sitemap)
        {
            sitemap.Add(Home, "Index")
                .Add(Home, "Scanner")
                .Add(c =&gt; c.Metadata());
        }

        #endregion
    }

    public class OtherControllerSitemapMetadata : ISitemapMetadata
    {
        private const string Other = "Other";

        #region ISitemapMetadata Members

        public void Create(ISitemapConfigurator sitemap)
        {
            sitemap.Add(Other, "Index")
                .Add(c =&gt; c.Test(1, "dude"));
        }

        #endregion
    }
            // An example, you'll probably use your favorite
            // IoC container to resolve all the metadata classes
            var metadata = new List
                               {new HomeControllerSitemapMetadata(), new OtherControllerSitemapMetadata()};

            ISitemap sitemap = new SitemapConfigurator(HttpContext).FromMetaData(metadata).Export();

There is more API sugar, so go download it and give it a try.

MVC Turbine – A Great Platform

0

I love Asp.Net MVC, that isn’t a secret. Although the framework isn’t perfect, it is a great leap in the right direction. When I start an Asp.Net MVC project there are things I always have to do just to jump into the meat of the new site. These things include replacing the ControllerFactory with a IoC enabled ControllerFactory, changing routing, and other boiler plate actions. This is where MVC Turbine comes in, and I am liking it more and more the deeper I dive into it. Javier Lozano, the creator, defines MVC Turbine as

MVC Turbine is a plugin for ASP.NET MVC that has IoC baked in and auto-wires controllers, binders, view engines, http modules, etc. that reside within your application. Thus you worry more about what your application should do, rather than how it should do it.

image

If you consider ASP.NET MVC as a stock Nissan 370z, then MVC Turbine is the Nissan 370z with the Nismo package. Ultimately the same car, but the tweaks make the ride so much more fun to drive. Everyday I find something cool in this framework, but these are my favorite features so far.

Services Registration and IoC

I love IoC, because it makes testing your applications easier and shrinks your code base over the long run. What I hate is having to wire it up every time I start a new project. With MVC Turbine, it is already handled for you. Just create classes that implement the IServiceRegistration interface. You will be passed your favorite IoC and you can do what you need to do to register your services.

Inferred Actions

If your controller actions just return a view, then you are going to love this. You can create a controller class with no actions, and MVC Turbine will look in your views folder and display that view. Check it out here.

Route Registration

When you have a large Asp.Net MVC application, then you’ll probably have a lot of routes. MVC Turbine allows a great facility for registering routes, while keeping you project clean.

I can definitely get behind MVC Turbine and I recommend you check it out.

Go to Top