Hey there,

My blog has moved… and changed flavor.  

My career has been becoming more and more UI and UX oriented, so in reflection of my job title of UI/UX architect, my new site will reflect blog posts about the ever-changing veneer over the machinery…

http://boilingplastic.com

67 Essential OSX Apps and Utilities

There are not really 67 utilities I’m going to list for you (or am I?). Instead I thought it was a catchier name.  There is one thing the internet has taught me… and that is “Cheaters always prosper”  :D

  • Function Flip
    http://kevingessner.com/software/functionflip/
    Free

    This little gem lives in your system preferences and lets you configure your function keys to be either an F-Key or the Action key (brightness, volume, etc).  It also lets you configure your laptop’s keyboard differently to your external keyboard.
     
  • Better Touch Tool
    http://blog.boastr.net/?page_id=1722
    Free

    Allows you to configure and override advanced gestures on your touchpad. One extra thing I LOVE about it.. is Windows-mode edge snapping.. that is.. drag your application window to the top of your screen and it will expand to fill the screen.
     
  • Handbrake
    http://sourceforge.net/projects/handbrake/
    Free

    I use Quicktime a lot to record screen recordings so I don’t have to keep teaching new hires the same thing again and again.  The trouble is, that a 20 minute tutorial can easily be over a gigabyte.  I use handbrake to downsize my media to a more storable size.

  • VLC
    http://sourceforge.net/projects/vlc/
    Free

    On OSX or Windows, VLC is one of my first-to-install programs.  Always fast, reliable and free!  It will play almost any media file you throw at it.

This list will grow as I add and try out more things.. stay tuned.

Showing 2x images in a web browser for Macbook Pro Retina

So on my current project (can’t talk about details)  at Apple, I have to devise a way to dynamically serve double sized (or 2x) images for people running Chrome or Safari on their Macbook Pro Retina. (Currently the only two browsers that support it).

The hardest part to understand is this:

On a retina display, the pixels are not actually pixels but virtual pixels (a.k.a. “points”).  The REAL pixels are actually much denser (twice) than are being reported.

In practice the following is true:

On a normal display.. when you have an <img> and you set its dimensions in css to be 100px by 100px in size, you need to use an image that is 100px by 100px.

On a retina display.. when you have an <img> and you set its dimensions in css to be 100px by 100px in size, you need to use an image that is 200px by 200px!

It requires twice an many pixels to fill the same space.

BUT HOLD ON..  how do non-optimized webpages still work?  Well the image is scaled in your browser, which is why on a retina display, non-retina-optimized images and text can appear blurry.

Next:  Once I know for sure I’m not telling lies, I will post an article on how to actually dynamically respond to a retina display in javascript with window.devicePixelRatio and css3’s @media.

1 note

Boolean Javascript Arrays

A fellow tinkerer pondered this question…

(4:18:48 PM) Joe: when you use true/false as indices to an array, they cast to 1/0 respectively, yes?

To which I replied:

(4:19:16 PM) Me: they might actually store as true and false

(4:19:41 PM) Me: i don’t know

So I decided to find out! And it turns out it does!  Good boy javascript!  Good doggie!

If I declare the following javascript:

var test = [];
test[true] = 'a';
test[false] = 'b';

It won’t cast the boolean values to string or integer.. it will keep them as true and false!  Huzzah!

The Proof:

document.write('test[true]=', test[true], '<br />');
document.write('test[false]=', test[false], '<br />');
document.write('test[!true]=', test[!true], '<br />');
document.write('test[!false]=', test[!false], '<br />');

Renders as:

test[true]=a
test[false]=b
test[!true]=b
test[!false]=a

Note! That while the javascript compiler will run this code, it will throw warnings… especially if you declare your array like this:

var test = { true : 'a', false : 'b' };

1 note

Using QUnit to Unit Test my Javascript Masks for Textboxes

Well after boasting that is COULD be unit tested in my previous article, I decided to show how I did unit test it using the very easy QUnit javascript unit testing library from jQuery.

To create a QUnit Test you will need a few things:

  1. Blank webpage
  2. Javscript in its own file
  3. Blank javascript unit test file

SETUP YOUR TEST PAGE

So i set my page that will run the tests in the following way:

  • Included qunit files
  • Included jquery
  • Included my javascript file that contains the masking code (TempMember.ascx.js)
  • Included my unit test javascript file (TempMember.Test.js)
  • Created the QUnit placeholder <div>s and <ol>
  • Added my UI controls that I will be testing my Masks against
<!DOCTYPE html>
<html>
<head>
	<link rel="Stylesheet" href="../include/qunit.css" />
	<script type="text/javascript" src="../include/qunit.js"></script>
	<script type="text/javascript" src="../include/qmock.js"></script>
	<script type="text/javascript" 
		src="../../../../../Source/MyProject/include/jquery.js"></script>
	<script type="text/javascript" 
		src="../../../../../Source/MyProject/TempMember.ascx.js"></script>
	<script type="text/javascript" src="TempMember.Test.js"></script>
	<title>Temp Member Tests</title>
</head>
<body>
	<div id="qunit-header"></div>
	<div id="qunit-banner"></div>
	<div id="qunit-testrunner-toolbar"></div>
	<div id="qunit-userAgent"></div>
	<ol id="qunit-tests"></ol>

    <div style="display:none;">
        <input type="text" id="NumericMaskTest" 
            onkeydown="maskFiltration.CaptureForMask(this, 
		maskFiltration.masks.numericOnly)" 
            onchange="maskFiltration.ApplyMask(this, 
		maskFiltration.masks.numericOnly)"
        />
        <input type="text" id="AlphaMaskTest" 
            onkeydown="maskFiltration.CaptureForMask(this, 
		maskFiltration.masks.alphaOnly)" 
            onchange="maskFiltration.ApplyMask(this, 
		maskFiltration.masks.alphaOnly)"
        />
        <input type="text" id="FourCharNumericTest" 
            onkeydown="maskFiltration.CaptureForMask(this, 
		maskFiltration.masks.fourDigitMax)" 
            onchange="maskFiltration.ApplyMask(this, 
		maskFiltration.masks.fourDigitMax)"
        />
    </div>

</body>
</html>

CREATE YOUR JAVSCRIPT UNIT TESTS

So we are ready now to write some tests!  Some of my colleagues like to write their javascript test as anonymous functions.  But I find declared functions significantly easier to debug.

// Three groups of tests ///////////
var MaskTests =
{
    NumericTest: function () {
        var test1 = jQuery('#NumericMaskTest')
        test1.val('1234');
        test1.keydown();
        test1.change();
        same(test1.val(), "1234", "Result should be 1234");

        test1.val('123sss4');
        test1.keydown();
        test1.change();
        same(test1.val(), "1234", "Result should be 1234");

        test1.val('123456');
        test1.keydown();
        test1.change();
        same(test1.val(), "123456", "Result should be 123456");

    },

    AlphaTest: function () {
        var test1 = jQuery('#AlphaMaskTest')
        test1.val('aBcD');
        test1.keydown();
        test1.change();
        same(test1.val(), "aBcD", "Result should be aBcD");

        test1.val('123ssS4');
        test1.keydown();
        test1.change();
        same(test1.val(), "aBcD", "Result should be aBcD");

        test1.val('aBcDeFg');
        test1.keydown();
        test1.change();
        same(test1.val(), "aBcDeFg", "Result should be aBcDeFg");

    },

    FourCharNumericTest: function () {
        var test1 = jQuery('#FourCharNumericTest')
        test1.val('1234');
        test1.keydown();
        test1.change();
        same(test1.val(), "1234", "Result should be 1234");

        test1.val('123a');
        test1.keydown();
        test1.change();
        same(test1.val(), "1234", "Result should be 1234");

        test1.val('12345');
        test1.keydown();
        test1.change();
        same(test1.val(), "1234", "Result should be 1234");

        test1.val('123');
        test1.keydown();
        test1.change();
        same(test1.val(), "123", "Result should be 123");
    }
};

// The function to run before each test is executed
function ResetMock()
{
	jQuery('#NumericMaskTest').val("");
	jQuery('#AlphaMaskTest').val("");
	jQuery('#FourCharNumericTest').val("");
}

// Give QUnit the function pointer
QUnit.testStart = ResetMock;

// Declare a section header (module)
module("Mask Filtration Test");

// Execute Each group of tests
test("Testing numeric", MaskTests.NumericTest);
test("Testing alpha", MaskTests.AlphaTest);
test("Testing 4 char numeric", MaskTests.FourCharNumericTest);

Now to run the unit tests, you can simply view the web page, and the test will execute.   With more setup you can make the test results be captured by your automated build server.

QUnit Result!

Simple Javascript Masks for Textboxes

Ok,

So here is my disclaimer:  I HATE masked text edits.  Hate them with a passion.  And this is why:

  1. They are often coded poorly - Coders will make an acceptable character list and then forget to include backspace or delete key
  2. They are BAD usability! - To all of you who use masked text boxes for phone numbers, please stop!  They are horrible!  They don’t allow users to paste in phone numbers easily.
  3. They often will block a keypress without showing the user the character.. so the user thinks their keyboard or (even worse!) your web page is broken.

So that being said I was directed to make a masked edit for a web page I was working on, and being the dutiful contractor proceeded to do so, but in the best way possible.

The following method doesn’t block keypresses but instead remembers the last good value that was entered, and if the input does not pass validation on change, then it will restore the text to it’s previous value.  

It’s also unit testable and uses supports dependency injection. See this article regarding unit testing.

var maskFiltration = 
{
    captureForMaskValue : [],
    masks : 
    {
        numericOnly : /^[0-9]*$/,
        alphaOnly : /^[a-z]*$/i,
        alphaNumericOnly : /^[a-z0-9]*$/i
        /* Add your own types here! */
    },

    Init : function()
    {
        this.captureForMaskValue = [];
    },

    CaptureForMask : function(obj, regObj)
    {
        if (obj != null && obj.id && obj.id.length > 0 && obj.value)
        {
            if (regObj.test(obj.value))
            {
                // passed validation.. backup value
                this.captureForMaskValue[obj.id] = obj.value;
            }
        }
    },

    ApplyMask : function(obj, regObj)
    {
        if (obj != null && obj.id && obj.id.length > 0 && obj.value)
        {
            if (regObj.test(obj.value) == false)
            {
                // failed validation.. reset value
                if (this.captureForMaskValue[obj.id] == null)
                {
                    //previous "good" value is unknown
                    obj.value = "";
                }
                else
                {
                    obj.value = this.captureForMaskValue[obj.id];
                }
            }
        }
    }
};

And apply to a text box in the following way:

<asp:textbox id="txtNumberOnly" 
	onkeydown="maskFiltration.CaptureForMask(
		this, maskFiltration.masks.numericOnly)" 
	onchange="maskFiltration.ApplyMask(
		this, maskFiltration.masks.numericOnly)" 
/>

Note: there is a lot of room for making the objects register themselves with the maskFiltration object, but for this example.. Simple is Better!

1 note

Parse JSON Date into a javascript Date object

I’m recording this here so I don’t ever have to look for this solution again.  It works perfectly with .net date json serialization and +400  timezones as well!

var date = new Date(parseInt(jsonDate.substr(6)));

The substr strips out the leading “Date” meta text.

1 note

Linq : Converting a List<> to a List<SelectListItem>

Just like when I was learning regular expression, I find that I’m using Linq to do more and more with my data objects the more I use it.  

Also with regular expression I’m wary of using it because it’s still not in the “everyday developer’s” skill set and if said developer ever has to debug my work, they might find it a steep learning curve.

This example however I think this code for converting a List<> to a List<SelectListItem> is pretty neat and self explanatory:

List<SelectListItem> SelectListItemList =
    (        
        from rec in myReadList  
        select new SelectListItem
            {
                Text = rec.Value,
                Value = rec.Key
            }
     ).ToList();

However, for those who DO want an explanation, this is what is happening:

  1. each item of a List<> named myReadList is read one-at-a-time into a variable called “rec”
  2. for each “rec” item a new “SelectListItem” object is made and the values rec.Value and rec.Key are read into the SelectListItem’s .Text and .Value properties
  3. Inside the brackets this will be returned as IEnumerable<SelectListItem> however I want it as a List<SelectListItem> so I call .ToList() afterwards.

For those who find the example above too long, here is the short-hand version. (It’s just one line, but broken so it wraps well)

List<SelectListItem> SelectListItemList =  
    myReadList.Select(
    rec => new SelectListItem 
    { Text = rec.Value, Value = rec.Key }).ToList();

UPDATE: For those wishing to set a default or selected item can find a solution (as chosen) at StackOverflow.

Detecting nested exceptions (because of CSLA)

CSLA is a pretty good middle-tier framework (though not without it’s complexity or problems).  A colleague and I were discussing that for small organisations, it’s just not worth implementing it if you’re not going to be running the factory methods on one server and the executions method on another server…. but that is not what I’m here to talk about!

So my problem with CSLA today is that when I want to invoke an exception from the bowels of an internal method, it is wrapped up nicely in a CSLA defined exception.  This means I can’t catch my exception like this:

try
{
    user = UserCsla.GetById(userId);
}
catch (DataNotFoundException dNFExc) // !!! THIS WON'T WORK !!!
{
    //user not found
    user = new User();
}

I know my exception is in there somewhere, but I don’t want to catch ALL exceptions in case something unexpected happens.  In that case I want the exception to keep bubbling.

My solution is to write an extension method for class Exception, that will recursively plumb the depths of .InnerException and see if it contains a certain type.

Extension Method:

public static class ExceptionExtender
{
    /// 
    /// Recurses Inner Exceptions and returns true if 
    /// the exception type is found in the stack
    /// 
    public static bool Contains(this Exception exception, 
                                Type exceptionType)
    {
        if (exception.GetType().Equals(exceptionType))
        {
            return true;
        }
        if (exception.InnerException != null)
        {
            return exception.InnerException
                               .Contains(exceptionType);
        }
        return false;
    }
}

Using it:

try
{
    user = UserCsla.GetById(userId);
}
catch (Exception exc)
{
    if (exc.Contains(typeof(DataNotFoundException)))
    {
        //user not found
        user = new User();
    }
    else
    {
        throw;
    }
}

Extra Note: I am aware that a better way to consume this data would be to have .GetById(userId) return a null value if the user isn’t found.  The method was created by another developer with that behaviour intentionally, and to consume it, I had to live by its rules.

Lightweight javascript graphics using SVN Vectors

Over at my favourite design website, they are discussing how to make a table of data gracefully upgrade itself from a table to a graph.. but to still be available as a table to non-supported browsers and spider-bots.

http://www.alistapart.com/articles/svg-with-a-little-help-from-raphael/

NOTE: Be aware, that at the time of writing, there is a bug that orders pie chart items by the highest to lowest value.  You can track the bug (and the fix) at the repository at GitHub.

NOTE: Be also aware that if you have values with a large difference (one is 1,000,000 and the other is 10), that it currently has a rendering issue that prevent the whole graph from loading. You can track the bug (and the fix) at the repository at GitHub.

Getting Started with NHibernate

A 6+ part series of “How-To’s” on getting started and mastering NHibernate.

Link to Article 1

1 note

Versioning CSS and Javascript Files

I was reading a hints article regarding MVC and I came across a novel way of ensuring that you never have to ask a client to “Try clearing your cache”.

All you have to do is:

  1. Implement auto version numbering on your application
  2. Append the version number to the url for the .css or .js resource

So your resources will be cached until your version rebuilds, when the resource url will change!

This is actually getting into my next blog post, but figure out a way to version your JavaScript and CSS.  This really isn’t MVC specific, you should do this in almost any project.  The key reason is to help you with a browser’s cache.  You know you have a problem when the first thing someone tells you, when asking for help, is that they cleared their cache already.   My thought on this is your web app’s dll should have a version number, set the project to auto version, and then pop that onto the end of the css/javascript file call.  So it might look like this:  ”http://myapp/…/file.css?version=1.0.0.256″.   In my sample code, when in development I stick a timestamp on the file in the same way.

Using jQuery with Greasemonkey (and including javascript files from javascript)

Since my recent, torrid love affair with all things jQuery, I decided to go back to Greasemonkey and see if I could integrate it with jQuery to make selection and manipulation jsut THAT much easier.. and guess what? …it is!

If you use the following script.. jQuery will be registered from Google’s CDN and then the code will loop until the script is included in the DOM and then execute the doReady() function.

Use this template for all your jQuery / Greasemonkey scripting pleasures:

// ==UserScript==
// @name           jQuery include template
// @namespace      evildonald.net
// @include        http://the.pagedomain.com/
// ==/UserScript==

// include an external javascript file
function include(filename)
{
var head = document.getElementsByTagName('head')[0];

script = document.createElement('script');
script.src = filename;
script.type = 'text/javascript';

head.appendChild(script);

checkJQueryLoaded();
}

// Check if jQuery is loaded
function checkJQueryLoaded()
{
if (typeof unsafeWindow.jQuery == 'undefined')
{
window.setTimeout(checkJQueryLoaded, 100);
}
else
{
$ = unsafeWindow.jQuery;
$(document).ready(doReady);
}
}

// initialize the page
function doReady()
{
alert($); // this proves jQuery is loaded
}


include('http://ajax.googleapis.com/ajax/libs/jquery' +
'/1.3.2/jquery.min.js');


Many thanks go to Joan Peidra for their invaluable method for testing if jQuery is loaded

2 notes

Online Unix Banner Generator

Sometimes you really want something to stand out.  Unix banners are a great universal way of marking up text with an important message, but not having access to a Unix system, I couldn’t generate one!

Fortunately, this site has come up with the goods and will let you generate banners in a myriad of “fonts”.  The example below was generated in “Letters” font.

 OOOOO  BBBBB    SSSSS   OOOOO  LL      EEEEEEE TTTTTTT EEEEEEE 
OO   OO BB   B  SS      OO   OO LL      EE        TTT   EE      
OO   OO BBBBBB   SSSSS  OO   OO LL      EEEEE     TTT   EEEEE   
OO   OO BB   BB      SS OO   OO LL      EE        TTT   EE      
 OOOO0  BBBBBB   SSSSS   OOOO0  LLLLLLL EEEEEEE   TTT   EEEEEEE 

UPDATE: My co-worker Brandon was auditing/refactoring all stored procedures and seemed to really like the OBSOLETE headers. It made his job easier being able to see straight away that he didn’t need to process that proc.

Handling multiple submit buttons in MVC v1

A lot of forms have input fields with multiple action buttons that act on that data.  MVC doesn’t immediately offer an ability to detect which submit button was clicked.

One solution is to use different forms that are tagged with action labels that will invoke a method in a controller. The following works:

<% using (Html.BeginForm("Action1", "ControllerName")) { %>
<%= Html.TextBox("Id") %>
<input type="submit" value="Save" />
<% } // end form %>

<% using (Html.BeginForm("Action2", "ControllerName")) { %>
<%= Html.TextBox("Id") %>
<input type="submit" value="Save" />
<% } // end form %>

But what if you want to use the same input fields for both submit buttons? A submit will only POST back the named fields that are in the same form as it.  You might consider the following solution, but it will not work:

<% using (Html.BeginForm() { %>
<%= Html.TextBox("Id") %>
<% } // end form %>

<% using (Html.BeginForm("Action1", "ControllerName")) { %>
<input type="submit" value="Save" />
<% } // end form %>

<% using (Html.BeginForm("Action2", "ControllerName")) { %>
<input type="submit" value="Save" />
<% } // end form %>

As a better solution, I like to name all the submit buttons with the same name, and have each button have it’s own value.

<% using (Html.BeginForm()) {%>

<%= Html.TextBox("Id") %>

<input type="submit" value="Action1" name="SubmitButton" />
<input type="submit" value="Action2" name="SubmitButton" />

<% } // end form %>

Then all I need to do is capture the value of the POST item “SubmitButton” and I can perform business logic on what value is returned!

Here is a sample Model:

[Serializable]
public class MyModel
{
public int Id { get; set; }
public string SubmitButton { get; set; }
}

Here is a sample Controller:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DoSomething(MyModel model)
{
if (model.SubmitButton.Equals("Action1",
StringComparison.OrdinalIgnoreCase))
{
return RedirectToAction("Action1", new { id = model.Id });
}
else if (model.SubmitButton.Equals("Action2",
StringComparison.OrdinalIgnoreCase))
{
return RedirectToAction("Action2", new { id = model.Id });
}
return View();
}