Jul 20
Consistent modal dialogs, the easy way
icon1 Darrell Mozingo | icon2 Web | icon4 July 20th, 2011| icon3No Comments »

So we all know the default alert dialog box visually sucks. Any of the hundreds of jQuery modal plugins work wonderfully for replacing it with something a bit snazzier (although putting the information on the page for a user is even better, but that’s for another post). The biggest problem with most of those dialogs are either the setup cost, or the memory cost:

  • Setup cost: having to set heights, widths, button names, text & title fields, yada, yada, yada. A lot of that can be skinned through CSS, and a lot of plugins reduce that noise to virtually nil, but many leave a lot on your pages. It’s ugly to look at in your code, and ugly to configure. Not to mention all those config settings spreads through your code base like the freakin’ ground ivy is spreading through my lawn as I type this. Want to change the widths for a new redesign, or localize the button names? Good luck!
  • Memory cost: relates to the Pit of Success. Do you really want the burden of always remembering to use that modal dialog instead of alert? What about the new guy, is he going to know or remember? Sure, forgetting isn’t that big of a deal, but given enough slip ups and your nice consistent UI goes to hell. Tests checking for calls to alert are also possible via straight searching through files or through UI tests some how, but I can see a future of false positives ahead of that idea.

How about a better way? With some very slight Javascript-foo, you can override the default alert and confirm dialogs so not only is there nothing to copy & paste between pages, but you don’t even have to remember to use your nifty modal boxes – it’ll just happen. We’ll use the jQuery UI Dialog plugin inside a stock ASP.NET MVC app, though this is easily transferable to any other platform or with any other modal plugin.

First we’ll override the default alert method on the window object, calling the dialog function from jQuery UI and setting some default parameters:

window.alert = function (message) {
	$("#dialog")
	.html("")
	.html('<span class="ui-icon ui-icon-alert custom-ui-icon"></span>' + message)
	.dialog({
		autoOpen: true,
		resizable: false,
		height: 200,
		width: 350,
		title: "Alert!",
		modal: true,
		buttons: {
			"OK": function () {
				$(this).dialog("close");
				return;
			}
		}
	});
};
 
alert("Error!!!");

The HTML is cleared out and a default alert icon (from jQueryUI) is added via the class attribute ui-icon-alert. This allows us to create a standard <div id="dialog"></div> in our master page with nothing inside it, and reuse it for alert/confirm/prompt boxes. Then a standard alert call, like the one at the bottom, gives us:

Alert modal dialog vs
Default alert

Similarly, we can override the default confirmation box. Here’s a version that’ll take the title, a message to show, and a callback function to execute if the user clicks “OK”:

window.confirm = function(title, confirmMessage, successCallback) {
	$("#dialog")
		.html("")
		.html('<span class="ui-icon ui-icon-help custom-ui-icon"></span>' + confirmMessage)
		.dialog({
				autoOpen: true,
				resizable: false,
				height: 200,
				width: 350,
				title: title,
				modal: true,
				buttons: {
					"Yes": function() {
						$(this).dialog("close");
						successCallback();
						return;
					},
					"No": function() {
						$(this).dialog("close");
						return;
					}
				}
			});
};
 
confirm("Are you sure?", "Are you sure you want to create a confirm?", function() { alert("Sweet, all done!"); });

Again, compare the results (the first question mark is an icon from jQuery UI, which can also be changed with the class written out in the confirm method above):

Modal Confirm vs
Default Confirm

Pretty neat, if you ask me. This whole thing is very DRY, as everything you need is referenced in your master page (the dialog div, the javascript & css files, etc) and your individual pages don’t need to include anything – just call away. You also don’t have to remember to call special methods (or at least terribly special ones in confirm‘s case). It just works.

It’s not too hard to imagine extending this system to override the default prompt box either. Just pass in a callback that’ll set whatever string you need, similar to how confirm works above. Closures work wonders.

You can grab the code used in this post right here.

Jun 26
The Pit of Success
icon1 Darrell Mozingo | icon2 Design Principles | icon4 June 26th, 2011| icon31 Comment »

Pit of Success

I’m a huge believer in the Pit of Success. Quite a few have written about it before, though not always in development terms. Put simply, there’s two pits you can create in your application through conventions, infrastructure, culture, tools, etc: success and failure. I obviously choose the former.

The Pit of Success is when you and the other developers on your team have to think less about the mundane stuff and when there’s only one easy development path to follow. Less thinking about crap = more thinking about business problems = faster software with less bugs. In general, if I see something that’s going to be in a lot of classes/pages and it has a decent bit of setup and baggage for it, I instantly picture another developer forgetting to bring all that along when they start new features or refactor. If things break (visually or programatically) when that happens, there’s a problem. Same goes for huge chunks of documentation explaining how to use a certain feature elsewhere in the system – time to make it easier to use! Here’s a few examples of how we’ve dug out a Pit of Success on our current project:

  • Need to create a new schedule task? Drop in a class and implement a simple interface. That same principal goes for a slew of other areas – missing information checks for users, HTTP handlers, sample data for geographic areas, etc. You don’t have to go hunting down a master class to add these new things to, just create the class and you’re golden.
  • Security in our system isn’t that complex yet, so we’re able to consolidate everything in a nice tidy ActionFilter. It’s applied to our custom controller, and we have a unit test that makes sure all Controllers in the system inherit from that custom one. So by following the rules (on your own or with the help of a broken test), you get security handled for you auto-magically.
  • We continuously deploy with our build server, so it takes care of not only making sure all our unit/integration tests pass, but that all the needed debug settings are flipped, sites are pre-compiled, everything still works once it’s live, etc. That saves us from remembering to do all that every time we push live, which is almost constantly these days.
  • We completely agree with Chad Myers, Jeremy Miller, et al: if we’re working with a static language, make the best of it. Everything in our system is strongly typed, from text box ids in HTML/Javascript/UI tests to URLs and help points. You shouldn’t have to remember to go hunting and pecking through the whole system when you want to rename something, just rename it with ReSharper and move on. Same with finding where something is being referenced. The harder it is to rename things, the less they get renamed, and the crustier the system gets.
  • We started creating one off modal dialogs to present information to the user. They looked great, but needed a lot of baggage and duplication to do it, so we overrode the default alert and confirm dialogs with our modal ones. Now there’s not only nothing to add to your page to get this, but in most cases you don’t even have to remember we’re overriding it! There’s a forthcoming post that’ll cover what we did in more detail.
  • We have a unit test that’ll scan through all of our test files (which end with *Fixture), and make sure there’s a file name that matches (sans the Fixture part) in the corresponding directory structure in the main assembly. We constantly move files around when refactoring, and forgetting to move or rename their test files is a pain, so this test gently reminds us. Note we don’t always follow a one-class-per-fixture setup, but even when we don’t, we stick them in a matching fixture class for easy grouping and ReSharper discoverability.

It’s worth noting we didn’t set out from day one to build all this stuff. Its all grown over time as the project and our stakeholder’s needs have changed. We always strive to keep KISS in mind (even if it is hard) and not build anything until it’s absolutely needed. Don’t try to create infrastructure to handle everything for you when a project’s in its infancy. Harvest it out later.

There’s also exceptions to all of these rules. Is automatic security always the right thing to do? No – if you need highly configurable security, put it out in the open and remember to set it on each request. Don’t force things into the infrastructure if they’re fighting you and have lots of exception cases. Perhaps there’s another route of attack that’ll solve the problem and still keep you circling around the Pit of Success.

You’ll create your own Pit of Success on your project just by falling into the bigger Pit of Success that is the SOLID principals. The majority of the examples up there were arrived at by just adhering to the Open/Closed Principal or the Single Responsibility Principal. They create a sort of recursive pit, I suppose.

What have you done on your projects to help create a Pit of Success?

May 27
Canton Software Craftsmanship
icon1 Darrell Mozingo | icon2 Events | icon4 May 27th, 2011| icon3No Comments »

Just a quick reminder about the next Canton Software Craftsmanship meeting on June 6th. It’s the usual 6pm at Stark State College with free pizza and drinks, and sponsored by Synergy Data Systems this month (who’s coincidentally looking for another junior C# developer, if you’re interested). Asher McCune will be giving a talk on the Open/Closed Principle (the O in SOLID) and we’ll be doing more katas together, trying to push the pairing aspect and getting everyone to work with different partners.

Hope everyone can make it! Please don’t forget to register right here so we have a head count for pizza.

May 24
Code Katas
icon1 Darrell Mozingo | icon2 Misc. | icon4 May 24th, 2011| icon3No Comments »

I added a page listing a bunch of code katas, mostly for my own reference, but I guess you guys can mooch off of it too.

Let me know if I’m missing any. I’ll expand the page as I stumble across more.

May 9
StirTrek: Thor Edition
icon1 Darrell Mozingo | icon2 Events | icon4 May 9th, 2011| icon3No Comments »

thor

I went with a few co-workers to Stir Trek this past Friday. They’ve put an event on for the past two years, but this was the first one I’ve been to. It was an excellent event. Good talks, very well planned out, and a pretty decent movie to boot! Here’s the talks I went to:

  • Are You Satisfied With Your Tests? (Jim Weirich) – Jim gave a good overview of testing (do it, make them fast, etc.) and tips (clear naming, refactoring, when to combine/split tests, etc.). Overall pretty good. My co-workers gave a laugh as I harp on many of these points all the time already.
  • Node.js – Show and Tell (Leon Gersing) – A neat explanation of this async javascript framework. Leon gave a demo of a simple client/server chat setup, and a run down of a slightly more advanced website. I hadn’t seen any Node.js stuff other than very broad overview articles, so it was cool to get the explanation of when/where to use it, and look at working examples. Unfortunately he ran out of time before getting to the testing examples, but I guess that give me a place to start in my personal learning.
  • Testable Object-Oriented JavaScript (Jon Kruger) – One of the better talks I attended, as it tilted more towards the intermediate/advanced level than others. Jon walked through a live demo of building out a simple Twitter client by test-driving the javascript with Jasmine to run the tests, and his custom JS View framework to fake out the HTML. Pretty darn neat, and I’m looking forward to digging into it a bit more for our new features, as they’ll be far more client-side dependent than previous ones, and we haven’t gotten to the UI part just yet.
  • Getting Started with User Research: DIY Quick Course (Carol Smith) – Carol went over the basics of user research via interviews, observance, and card sorting, which helps you structure you application’s layout to match how users would expect it to be. Very helpful for a high-level overview talk, and gave me a few tips to pursue with getting information on our application.
  • Testing Web Applications with Selenium (Jim Holmes) – I was definitely looking forward to this talk the most, and it didn’t disappoint. We use Watin at work and have only dabbled once in Selenium, so seeing how he structures his tests was helpful. Unfortunately he spent 80% of the time going over a basic UI test and overview of Selenium. By time he got to the lessons he’s learned from running 14,000 some-odd UI tests, he ran out of time. Booo. It was actually quite comical… “OK, now the most important things you need to know… I’m out of time, aren’t I?”. A few of the database/browser handling tips will come in handy for our UI test suite though, and I’m looking forward to giving them a shot.

I really wanted to hit up the GitHub talk, executable requirements, and a mobile talk or two, but I guess there’s always next year. Overall it was an excellent conference, and the peeps that ran it did a great job. Thor itself turned out to be pretty decent flick, too.

They already scheduled next year’s version in May: StirTrek Avenger’s Edition. Looking forward to it!

Apr 11
Know your tools
icon1 Darrell Mozingo | icon2 Musings | icon4 April 11th, 2011| icon34 Comments »

Tools

How many carpenters do you think don’t know about kerf widths? How many plumbers don’t know the difference between MAPP and propane for soldering? Probably not many.

Masters of their craft know their tools inside and out. They don’t just skirt by barely knowing how to use them, and end up taking longer to complete a job because of that. We have the same situation in our craft. We use tools day in and day out – our IDE’s, debugging tools (for our main languages and web based ones), OS, browsers, websites, etc. They’re all tools of our trade. Learning how to really use them is just another stepping stone on the path to being a craftsman.

The best way to really make use of your tools and increase your programming speed is to ditch the mouse. Use the keyboard as much as possible, which can be almost everything. Really get good with the keyboard and you’ll be amazed at how much more efficiently you can pump out code and navigate around.

I use Windows and Visual Studio, so I’ll use that as an example. Visual Studio itself has a metric ton of built-in keyboard shortcuts, but add ReSharper to the mix, and you’re golden. Check out the keyboard shortcut cheat sheet, it’s ridiculous, and overwhelming. Pick one or two shortcuts you think you’ll use, then use those exclusively for a week. Make sure to purposely use them as much as possible until they become muscle memory. It won’t take long.

Look at Tools -> Settings -> Keyboard. There’s lots of stuff you can key bind on your own that doesn’t come setup by default. Create a key combination to run your unit tests rather than reaching for the mouse. If a default key combo feels unnatural for you, rebind it. Find something that works for you, and don’t be afraid to experiment.

Start learning keyboard shortcuts in other programs you use on a regular basis. There’s cheat sheets for GMail and Google Reader. For your mouse-free text editing needs (and IDE needs if you’re super experimentative and working with .NET) there’s the grand-daddies themselves: VIM and Emacs. There’s even plugins for Firefox (Vimperator) and Chrome (Vimium) to make each browser navigable in a VIM-esque way, and other plugins for each browser to simply add more keyboard navigation tricks. Heck, there’s even a few VIM plugins for Visual Studio itself if you want to go all the way, including ViEmu (paid) and VsVim (free).

It’s also super helpful to get a keystroke launcher on your box, such as Executor (my personal favorite) or Launchy. These guys basically give you the standard Windows Run dialog on steroids – letting you make custom launch commands and scripts. Definitely play around with one of these and work it into your normal workflow. I find myself leaning on it all the time.

So start practicing with a keyboard-only setup today. Disable your mouse driver and force yourself. It’ll kill your productivity in the short term for sure, but it’ll pay dividends every day for the rest of your career once you get used to it. You’ll thank me in a few weeks. Seriously, I’m marking my calendar.

Mar 31
Canton Software Craftsmanship
icon1 Darrell Mozingo | icon2 Events | icon4 March 31st, 2011| icon3No Comments »

The next Canton Software Craftsmanship meeting is this Monday. We’ll be going over TDD basics by having everyone follow us along on simple exercises.

Register here if you’e interested.

Hope to see you there!

Mar 8

Thanks to everyone that attended the first Canton Software Craftsmanship meeting this past Monday. It was a great turn-out (around 33 people?) and everyone seemed genuinely excited to see where this goes, myself included. Good food and good discussions all around. Sign up for the next meeting on April 4th if you haven’t already, and be sure to spread the word to anyone that might be interested. Remember, we’re about the practices, not the language, so everyone’s welcome.

I’d also like to thank Brandon Joyce and John Hoover for doing a great job with the logistics needed to get this group off the ground. Great job guys!

Mar 4
Taskie runner is now bundled
icon1 Darrell Mozingo | icon2 Taskie | icon4 March 4th, 2011| icon3No Comments »

The latest version of Taskie (which is available on NuGet) now comes bundled with a console runner. Simply implement ITaskieServiceLocator with your IoC container of choice, and put your compiled assembly with that implementation in the same directory as Taskie.exe. Taskie will pick up on the implementation and use it like normal.

This should reduce the usage overhead if you don’t feel like creating a virtually empty console project in your application, and lower the getting started barrier even more. If you’d still like to host your own console application for Taskie, that option will continue to be supported and its usage hasn’t changed.

Mar 2

The problem

We try to strongly type everything in our MVC project, especially URLs. It’s pretty easy to do using all the build in functionality of ASP.NET MVC along with some lovin’ from MvcContrib, but the one situation we’ve always had problems with was client-side javascript. If it’s a basic action call with no arguments, we’re golden (using <%= Html.BuildUrlFromExpression(x => x.MyAction()) %>). It gets tricky when we have a slightly more complex action though:

[AcceptAjax]
public string DoSomethingComplex(int id, string accountNumber, int amount)
{
	return string.Format("id = {0}, accountNumber = {1}, amount = {2}", id, accountNumber, amount);
}

If we wanted to do an AJAX call to this bad boy, we’d unfortunately have to resort to string concatenation to build up the URL:

// get these values from form fields or something...
var id = 3;
var accountNumber = "123456";
var amount = 325;
 
var ugly_url = "/Home/DoSomethingComplex/" + id + "?accountNumber=" + accountNumber + "&amount=" + amount;

Booo creepy magic strings. Renaming the action name or any of the parameter names left us relying on either ReSharper’s ability to catch the change, manual search and replace, or hoping we had a UI test hitting the page to catch it. Basically, nothing too terribly reliable to keep our app in working order. The more you worry about small changes breaking your application, the less likely you are to refactor it. The less you refactor, the faster your application degrades into nastiness (code not matching up with current business conventions, etc), and the slower you are to respond to change. Not cool.

The solution

Before I go further, I should probably throw up this disclaimer: We use the default routes for everything. The application is behind a login page, and we have no need for fancy SEO friendly URLs, so the solution I’m about to show caters to that scenario. If your application leverages custom routes, you’ll either have to tweak this solution to your needs, or figure out something else. Sorry.

In a nutshell

You’ll end up being able to build the URL above like this:

var beautiful_url = "<%= Html.UrlTemplate<HomeController>(x => x.DoSomethingComplex(Any<int>.Arg, Any<string>.Arg, Any<int>.Arg)) %>"
						.substitute(id, accountNumber, amount);

This’ll produce a URL template like "/Home/DoSomethingComplex/{0}?accountNumber={1}&amount={2}" on the client. You then plug in the template’s holes with your client-side values. Pretty simple, really.

There’s a few server and client-side pieces to this puzzle.

Server-side portion

The heart of this solution (and the biggest chuck of code) is the actual building of the URL template.

private static bool onlyTakesInSingleViewModel(string[] routeValues)
{
	return (routeValues.Length == 3 && routeValues[2].ToLower().EndsWith("viewmodel"));
}
 
public static string UrlTemplateFor<CONTROLLER>(Expression<Action<CONTROLLER>> action) where CONTROLLER : Controller
{
	var routeValues = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression(action);
	var actionPath = string.Format("/{0}/{1}", routeValues["Controller"], routeValues["Action"]);
 
	if (routeValues.Count > 2)
	{
		var routeValuesKeysArray = routeValues.Keys.ToArray();
 
		if (onlyTakesInSingleViewModel(routeValuesKeysArray))
		{
			return actionPath;
		}
 
		if (routeValuesKeysArray[2] == "id")
		{
			actionPath += "/{0}";
		}
		else
		{
			actionPath += "?" + routeValuesKeysArray[2] + "={0}&";
		}
 
		var placeHolderCounter = 1;
 
		if (routeValues.Count > 3)
		{
			if (actionPath.Contains("?") == false)
			{
				actionPath += "?";
			}
 
			for (var i = 3; i < routeValues.Count; i++)
			{
				actionPath += routeValuesKeysArray[i] + "={" + placeHolderCounter++ + "}&";
			}
		}
 
		actionPath = actionPath.TrimEnd('&');
	}
 
	return actionPath;
}

This method (which has unit tests in the sample project provided at the end of the post) basically builds up the URL template by leaning on a method inside the MVC Futures assembly to get the controller, action, and parameter names. This is the portion you’d have to tweak if you use different routing rules.

Then it’s simply a matter of wrapping the UrlBuilder call with an HTML Helper extension method:

public static class HtmlHelperExtensions
{
	public static string UrlTemplate<CONTROLLER>(this HtmlHelper htmlHelper, Expression<Action<CONTROLLER>> action) where CONTROLLER : Controller
	{
		return UrlBuilder.UrlTemplateFor(action);
	}
}

Looking at the example of using this method above, you can see all the parameters in the UrlTemplate call replaced with calls to an Any class. Technically speaking, whatever values you put in the expression passed to UrlTemplate will be ignored. You can put in nulls for references & nullable types, 0’s for value types, etc. I decided to drive home the point to anyone looking at the code that we don’t care what value they provide by making a very slim class that provides the default value for whatever type is needed:

public class Any<T>
{
	public static T Arg
	{
		get { return default(T); }
	}
}

It drives home that whole not caring point pretty well, but it’s also a bit wordy, especially if there’s 3 or 4 parameters that need specified. You can omit using the Any class and just give dummy values if you want. Your choice.

Client-side portion

There’s not a whole lot to the client-side portion. Basically a very simple version of the .NET Framework’s string.Format method (which you’ll probably want to put in an external js file and reference as needed). It’s written as an extension on the string type to make reading the final product a bit more natural:

String.prototype.replaceAll = function (patternToFind, replacementString) {
	return this.replace(new RegExp(patternToFind, "gi"), replacementString);
}
 
String.prototype.substitute = function () {
	var formatted = this;
 
	for(var i = 0; i < arguments.length; i++) {
		formatted = formatted.replaceAll("\\{" + i + "\\}", arguments[i]);
	}
 
	return formatted;
}

That’s it. Using all these pieces together gives us the final product:

var beautiful_url = "<%= Html.UrlTemplate<HomeController>(x => x.DoSomethingComplex(Any<int>.Arg, Any<string>.Arg, Any<int>.Arg)) %>"
						.substitute(id, accountNumber, amount);

You can provide the values for the URL template from client-side code, or from your ViewModel by just outputting the value in the proper spot (i.e. use <%= Model.Id %> rather than the client-side id property). This setup has proven very helpful and quite versatile for us so far.

Potential pitfalls

Having shown all this, there are a few potential pitfalls you need to be aware of:

  1. The building of the URL template is pretty rudimentary. It also relies on a method inside the MVC Futures assembly, which I haven’t checked to see if it even exists in MVC3, let alone in future versions. I couldn’t find anything in the main MVC assembly or MvcContrib to fill my needs. Having said that, it’s isolated to one location and we could always get the controller, action, and parameter names by hand with a little expression tree walking, especially since we’re already limited to the default route setup and therefore know where they’d be with pretty good certainty.
  2. This allows you to rename controller, action, and parameter names with complete confidence. However, if you switch parameter positions around, especially if they’re the same type, you might run into a problem. In my usage example above, for instance, switching the id and amount parameters around would still compile and technically run, but the Javascript would continue passing the id in for the amount parameter and vise-versa. You don’t usually switch around parameters for no reason, but it’s worth noting, as you’d have to do a find usages and make sure all the calls are updated properly. At least you’d be able to find all the usages with certainty, though.

Conclusion

Next time you find yourself needing to concatenate strings on the client-side to call URLs, think about using this technique (or something similar) to keep it all strongly typed. If you’re going to work in a static language like C#, you might as well leverage it as much as possible. Strong typing lets you refactor with full confidence that no references to the rename will get left behind by mistake.

You can grab a copy of the source code for the project right here (built with MVC2). Give it a spin and let me know if you have any problems, or if you know a better way to do this without building the URLs by hand.

« Previous Entries Next Entries »