<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>www.hackification.com &#187; Coding</title>
	<atom:link href="http://www.hackification.com/category/coding/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hackification.com</link>
	<description></description>
	<lastBuildDate>Sat, 05 Jun 2010 11:16:35 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>Designing a VS2010 Color Scheme &#8211; Consistency, Consistency, Consistency</title>
		<link>http://www.hackification.com/2010/05/16/designing-a-vs2010-color-scheme-consistency-consistency-consistency/</link>
		<comments>http://www.hackification.com/2010/05/16/designing-a-vs2010-color-scheme-consistency-consistency-consistency/#comments</comments>
		<pubDate>Sun, 16 May 2010 19:05:53 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Design]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[colors]]></category>
		<category><![CDATA[highlighting]]></category>
		<category><![CDATA[syntax]]></category>
		<category><![CDATA[visual studio]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=481</guid>
		<description><![CDATA[I recently found StudioStyles, a collection of Visual Studio 2010 color schemes, and it inspired me to create my own. I&#8217;ve never bothered customizing my editor colors before, but since VS2010 has an overall darker look, I thought I&#8217;d have a bash at creating a matching dark editor scheme. Looking through some of the submissions [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-503" style="margin-right: 10px;" title="Colors" src="http://www.hackification.com/wp-content/uploads/2010/05/Colors.png" alt="" width="160" height="110" />I recently found <strong><a href="http://studiostyles.info/" target="_blank">StudioStyles</a>, a collection of Visual Studio 2010 color schemes</strong>, and it inspired me to create my own. I&#8217;ve never bothered customizing my editor colors before, but since VS2010 has an overall darker look, I thought I&#8217;d have a bash at creating a matching dark editor scheme.</p>
<p><span id="more-481"></span>Looking through some of the submissions on the site, I was struck by how&#8230; well&#8230; random most of them are. Without meaning to be rude, they just look like someone went through the list, randomly assigning colors. Many many programmers believe coding and graphic design are polar opposites &#8211; that if you&#8217;re a coder, you must necessarily suffer from &#8220;programmer art&#8221;, and hence that it&#8217;s pointless to ever try to learn better design skills. <strong>I completely disagree with this diagnosis.</strong></p>
<p>I&#8217;m going to use only one design rule for this color scheme &#8211; consistency: <strong>keep similar things similar, and make different things different</strong>.</p>
<h3>Basics</h3>
<p>I&#8217;ve already decided to create a &#8220;dark&#8221; theme, so the background will be black. I also want to highlight important or dangerous elements of the source, and downplay incidental aspects. This idea will modify each of the colors chosen, and help suggest colors where there is no clear choice. Each choice will be reflected as far as is possible across many file types &#8211; for example, a C# comment should probably be the same color as an XML one, a JavaScript one, etc.</p>
<p>I&#8217;m also going to make use of color shades. I know Visual Studio has to cater for people using low-color displays, remote desktop, and those with reduced vision, but its use of primary colors leaves it looking a little dated. Color shades can be used to bring the look a little more up-to-date, and to group related elements, while still being able to distinguish between them.</p>
<h3>Comments &#8211; Green</h3>
<p>Comments have always been green in Visual Studio, and I&#8217;m going to keep them that way &#8211; a vibrant green, made bold, to catch the eye. (If comments aren&#8217;t important, then why are you writing them?) Comment hyperlinks and the text in #region blocks also match.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-483" style="border: 8px solid #000000;" title="Comments" src="http://www.hackification.com/wp-content/uploads/2010/05/Comments.png" alt="" width="400" height="128" /></p>
<h3>Literals &#8211; Blue</h3>
<p>String literals are red in the standard Visual Studio color scheme, but I wanted to reserve that color for errors and the like. In my mind strings are blue (don&#8217;t ask me why) so I&#8217;ve chosen a light blue for strings.</p>
<p>With consistency in mind, what else should match this?</p>
<ul>
<li>String literals are blue, so why not other literals, such as integers? The common color will highlight &#8220;magic values&#8221; in code.</li>
<li>We&#8217;ll need to colorize XML and HTML, so we can make attribute values blue too.</li>
<li>JavaScript and SQL obviously have literals.</li>
<li>I&#8217;ve also chosen to see CSS values as literals &#8211; they go blue too. (You could easily argue the toss about that though).</li>
</ul>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-485" style="border: solid 8px #000;" title="Code Literals" src="http://www.hackification.com/wp-content/uploads/2010/05/Literals1.png" alt="" width="400" height="66" /></p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-486" style="border: 8px solid #000000;" title="CSS Literals" src="http://www.hackification.com/wp-content/uploads/2010/05/Literals2.png" alt="" width="400" height="34" /></p>
<h3>Keywords &#8211; Gray</h3>
<p>Since the background is black, &#8216;unadorned&#8217; text will be white &#8211; a nice easy choice. How about keywords?</p>
<p>I want to make them a different color &#8211; so I can tell when I&#8217;ve typed &#8216;retrun&#8217; for the billionth time &#8211; but I don&#8217;t consider them to be &#8220;core&#8221; code. I think of them as scaffolding around my identifiers. (Perhaps I&#8217;m a LISPer at heart). I&#8217;ve chosen to keep them a neutral color, but a dimmer shade, so they fade out &#8211; hence gray.</p>
<h3>Types &#8211; Yellow/Orange</h3>
<p>Colorizing types is handy as it again allows me to see when I&#8217;ve mis-typed something. I want them to stand out (so a dim color is out), and I don&#8217;t want them confused with anything else &#8211; so reds, greens, and blues are gone. Yellows and light oranges seem a good choice &#8211; close enough to the normal white text, but sufficiently different to catch the eye. I&#8217;ve chosen a light orange for types, and highlighted interface types as yellow. (I figure that looking at how interfaces are defined and used is often a good way to understand the structure of a body of code &#8211; hence the slightly more eye-catching color).</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-493" style="border: 8px solid #000000;" title="Types" src="http://www.hackification.com/wp-content/uploads/2010/05/Types.png" alt="" width="400" height="104" /></p>
<p>(Oddly enough, this doesn&#8217;t seem to work for types in C++ &#8211; they always seem to come out white. Not sure why.)</p>
<h3>Errors, Warnings, and Oddities &#8211; Red</h3>
<p>This was an easy color to choose &#8211; red (for me) means stop and think. There are a few code constructs that I wanted to highlight as either dangerous or needing attention:</p>
<ul>
<li>Compiler errors and warnings;</li>
<li>Preprocessor directives;</li>
<li>Breakpoints.</li>
</ul>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-495" style="border: 8px solid #000000;" title="Errors" src="http://www.hackification.com/wp-content/uploads/2010/05/Errors.png" alt="" width="400" height="271" /></p>
<h3>Editor Overlays &#8211; Purple/Dark Blue</h3>
<p>Visual Studio now highlights parts of the source depending on where youyr cursor is &#8211; it highlights matching braces, and will also display all usages of the symbol at the caret. These display can change rapidly, so shouldn&#8217;t be too distracting. I&#8217;ve chosen a dark purple, which is subtly visible, but which blends in with the black background.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-498" style="border: 8px solid #000000;" title="Overlays" src="http://www.hackification.com/wp-content/uploads/2010/05/Overlays.png" alt="" width="400" height="113" /></p>
<p>We need a related color for the selection too, so I&#8217;ve chosen dark blue.</p>
<p style="text-align: center;"><img class="aligncenter size-full wp-image-510" style="border: 8px solid #000000;" title="Selection" src="http://www.hackification.com/wp-content/uploads/2010/05/Selection.png" alt="" width="400" height="71" /></p>
<h3>Omissions</h3>
<p>There&#8217;s still quite a few entries in the colors list I haven&#8217;t filled out &#8211; the main areas being:</p>
<ul>
<li>VB.NET;</li>
<li>XSLT</li>
<li>IntelliTrace</li>
<li>Test Coverage</li>
</ul>
<p>If you fancy addressing these omissions and sending me back an updated settings file, I&#8217;ll be happy to credit you.</p>
<h3>Conclusion &amp; Download</h3>
<p>So there you go. Obviously color schemes are very personal (and contentious). I think I&#8217;ve done a pretty good job; you might well think otherwise. Even if you don&#8217;t like this particular scheme, I hope you&#8217;ll agree that setting a few design principles in place before assigning colors can help you choose (and use) the colors effectively.</p>
<p>Sadly there&#8217;s no way to upload my settings to StudioStyles, and I&#8217;m too lazy to re-do all the work by hand. Until they allow that option, I&#8217;ll host the settings from here:</p>
<blockquote><p><strong>Download <a href="http://www.hackification.com/downloads/hackification.vssettings" target="_blank">hackification.vssettings</a></strong></p></blockquote>
<p>Save this file somewhere, then use Tools -&gt; Import and Export Settings&#8230; to merge them in.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2010/05/16/designing-a-vs2010-color-scheme-consistency-consistency-consistency/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick Tip: Avoid Enums If Possible</title>
		<link>http://www.hackification.com/2009/12/01/quick-tip-avoid-enums-if-possible/</link>
		<comments>http://www.hackification.com/2009/12/01/quick-tip-avoid-enums-if-possible/#comments</comments>
		<pubDate>Tue, 01 Dec 2009 18:16:43 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[architecture]]></category>
		<category><![CDATA[enums]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[tip]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=330</guid>
		<description><![CDATA[One of the &#8220;anti-patterns&#8221; I come across from time to time is over-use of enumerations for control flow. This article describes why I consider it an anti-pattern, and how to counteract it. Let&#8217;s suppose we want to represent an arithmetic operation on two numbers &#8211; such as plus, minus, multiply, etc. We could represent that [...]]]></description>
			<content:encoded><![CDATA[<p>One of the &#8220;anti-patterns&#8221; I come across from time to time is over-use of enumerations for control flow. This article describes why I consider it an anti-pattern, and how to counteract it.</p>
<p><span id="more-330"></span>Let&#8217;s suppose we want to represent an arithmetic operation on two numbers &#8211; such as plus, minus, multiply, etc. We could represent that operation as an enum (although to be clear &#8211; I don&#8217;t think you should):</p>
<pre>enum ArithmeticOperation
{
  Add,
  Subtract,
  Multiply,
  Divide
}</pre>
<p>We could then define a function to apply this operation to two numbers (highlighting will be explained later):</p>
<pre>int ApplyOperation(ArithmeticOperation op, int x, int y)
{
  switch(op)
  {
    <span style="color: #ffff00;">case ArithmeticOperation.Add: return x + y;</span>
    case ArithmeticOperation.Subtract: return x - y;
    case ArithmeticOperation.Multiply: return x * y;
    case ArithmeticOperation.Divide: return x / y;
    default: throw new InvalidOperationException();
  }
}</pre>
<p>That&#8217;s&#8230; sort of fine &#8211; but what happens when we want to extend it?</p>
<p><strong>Adding Operators: No Compile-Time Checking</strong></p>
<p>Let&#8217;s consider what happens if we want to add another operator &#8211; say exponentiation. If we add the enum value but forget to implement the switch case value, everything compiles fine. It&#8217;s only once we come to run the code, and actually hit that code path, that we discover the mistake, giving a run-time exception.</p>
<p><strong>Adding Methods: Bad Code Organisation</strong></p>
<p>Next, imagine what happens if we need to add more methods that switch on this enum. We might need a method returning the operator symbol, and another returning the operator precedence.</p>
<pre>string GetOperatorSymbol(ArithmeticOperation op)
{
  switch(op)
  {
    <span style="color: #ffff00;">case ArithmeticOperation.Add: return "+";</span>
    case ArithmeticOperation.Subtract: return "-";
    case ArithmeticOperation.Multiply: return "*";
    case ArithmeticOperation.Divide: return "/";
    default: throw new InvalidOperationException();
  }
}

int GetOperatorPrecedence(ArithmeticOperation op)
{
  switch(op)
  {
    <span style="color: #ffff00;">case ArithmeticOperation.Add: return 10;</span>
    case ArithmeticOperation.Subtract: return 10;
    case ArithmeticOperation.Multiply: return 20;
    case ArithmeticOperation.Divide: return 20;
    default: throw new InvalidOperationException();
  }
}</pre>
<p>I&#8217;ve highighted the relevant code for the &#8220;add&#8221; operator. Notice how it&#8217;s spread all over the place. Switch statements might group by operation, but they split by concept &#8211; and that&#8217;s the exact opposite of what&#8217;s usually intended with OO coding.</p>
<p><strong>A Better Way</strong></p>
<p>I&#8217;d suggest a better way of approaching this problem is to use an abstract class.</p>
<pre>abstract class ArithmeticOperation
{
  abstract int ApplyOperation(int x, int y);
  abstract string GetSymbol();
  abstract int GetPrecendence();
}

class AddArithmeticOperation : ArithmeticOperation
{
  override int ApplyOperation(int x, int y)
  {
    return x + y;
  }

  override string GetSymbol()
  {
    return "+";
  }

  override int GetPrecedence()
  {
    return 10;
  }
}

// ...and so forth for the other operators.</pre>
<p>That way, all the code for each operator sits in the same place, and adding any new methods for an operator requires all operators to be implemented before the code will even compile.</p>
<p><strong>When to Use Enums</strong></p>
<p>So if enums should be avoided, why do most languages include them? Personally I&#8217;d be happy without them,  but I can think of one possible reason you might want to use an enum. If you&#8217;re defining a public interface designed for consumption by other coders, you could argue that simplifying the interface at the expense of the code inside is a valid trade-off.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/12/01/quick-tip-avoid-enums-if-possible/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Debug.Assert Considered Pointless</title>
		<link>http://www.hackification.com/2009/06/10/debug-assert-considered-pointless/</link>
		<comments>http://www.hackification.com/2009/06/10/debug-assert-considered-pointless/#comments</comments>
		<pubDate>Wed, 10 Jun 2009 20:26:24 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Links]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[assert]]></category>
		<category><![CDATA[debug]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=214</guid>
		<description><![CDATA[One thing I was told as a young programmer was to make good use of assertions for checking code. As time goes by however, I can see less and less use for assertions. I&#8217;m starting to think they&#8217;re pretty useless. (I&#8217;m going to use C# in my examples here: some of these points might not [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-225" style="margin-left: 10px; margin-right: 10px;" title="Debug Assert Stop" src="http://www.hackification.com/wp-content/uploads/2009/06/stop.png" alt="Debug Assert Stop" width="96" height="96" />One thing I was told as a young programmer was to make good use of assertions for checking code. As time goes by however, I can see less and less use for assertions. I&#8217;m starting to think they&#8217;re pretty useless.</p>
<p><span id="more-214"></span></p>
<p>(I&#8217;m going to use C# in my examples here: some of these points might not apply to all languages. By default, an assertion will not fire in a C# release build, and furthermore, the code inside will not even be executed).</p>
<p><em>Update 2009-06-11: I probably haven&#8217;t been clear enough, but luckily various commenters have picked up on this: I&#8217;m not advocating removing assertions and replacing them with nothing! In general, I think assertions should be replaced with a stronger check that also runs (or can run) in a release build.</em></p>
<p><strong>1. Pointless Guard Checking</strong></p>
<p>Unfortunately in my coding travels I see quite a bit of code like this:</p>
<pre>void Foo(Bar bar)
{
  Debug.Assert(bar != null);

  bar.DoSomething();
}</pre>
<p>What&#8217;s the point? If bar is null, then using it will throw an exception anyway. Why add unnecessary lines of code that make reading harder?</p>
<p><strong>2. Bad Argument Checking</strong></p>
<p>But, you&#8217;re thinking, what if the usage is separated from the assignment?</p>
<pre>class Foo
{
  public Foo(Bar bar)
  {
    Debug.Assert(bar != null);

    _bar = bar;
  }

  public void Method()
  {
    _bar.DoSomething();
  }

  private Bar _bar;
}</pre>
<p>True, you want to catch the error as it happens, not later on in the method. But shouldn&#8217;t you be throwing an ArgumentNullException instead?</p>
<p><strong>3. Difficult Detective Work</strong></p>
<p>So now you&#8217;re telling me that you&#8217;re not writing component code, and the only client of this class will be the application it&#8217;s embedded in. Why not save some effort and skimp on the checking code, and make it debug-only?</p>
<p>Fine idea&#8230; until you get a crash report from one of your users, and the stacktrace points to a NullReferenceException in Method(). Now you have to figure out where the null value got passed to the constructor&#8230; a potentially much more difficult task.</p>
<p><strong>4. Differences Between Debug and Release</strong></p>
<p>If you&#8217;re like me, you generally run the applications in debug. Your customers however, run in release. Why make the differences between these two versions any bigger? Even if you don&#8217;t intend your debug statements to change program state, it&#8217;s all too easy to accidentally do so:</p>
<ul>
<li>Running lazy-initializers or singleton constructors;</li>
<li>Loading data from the database via an ORM;</li>
<li>Moving data in or out of a cache;</li>
<li>Running static constructors.</li>
</ul>
<p><strong>5. Too-Shy Sanity-Checking</strong></p>
<p>Sometimes, despite the above warning, you really do have sanity-checking code that you&#8217;d like to run in a development or test environment to catch regressions, but which is too slow to give to general users. (I read somewhere that Excel has two computation engines: a simple, slow, reference one, and a fast, parallel, release one. Testers can run the two in parallel, and any differences are automatically flagged as errors).</p>
<p>So you might be tempted to do something like:</p>
<pre>Debug.Assert( SlowlyAndCarefullyVerifyInternalState() );</pre>
<p>The problem I have with this is that the debug/release division is way too blunt.</p>
<ul>
<li>Suppose a tester wants to test a release build, but also perform the sanity-checking?</li>
<li>Suppose a customer finds a bug in a complex calculation, and you want them to run the checks?</li>
<li>Suppose a developer wants to debug performance issues in the non-checked code?</li>
</ul>
<p>I would suggest you move the conditionals for code like this to a (possibly hidden) configuration setting. Someone wants to run in slow-and-safe mode? No problem, just tell them the registry setting (or whatever). By all means, change the splash screen or title bar or whatever so it says &#8220;test mode&#8221;.</p>
<p>The advantages of this method are:</p>
<ul>
<li>Anyone can turn it on and off;</li>
<li>Sanity-checking can be controlled at a much finer granularity than all-on / all-off.</li>
</ul>
<p><strong>6. Is It Recoverable, Or Not?</strong></p>
<p>The final argument against debug assertions concerns just exactly what an assertion means.</p>
<p>To my mind, an assertion is different to a simple flow-control test (&#8220;did the user enter a valid number?&#8221;), which is something the program can (should) handle. By definition, an assertion is checking for a disallowed state. An assertion doesn&#8217;t check for incorrect data; it checks for an incorrect program. Continuing after an assertion leads to undefined behaviour.</p>
<p>So how can you continue? More to the point, why should a user even be allowed to continue? If the state really is unrecoverable, then fail. Fail fast, log the error, and bail (possibly trying to allow the user to save work, or whatever). Having a release-build application continue after what would have been an assertion is just plain wrong.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/06/10/debug-assert-considered-pointless/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Learning? Me? But I&#039;m An Expert</title>
		<link>http://www.hackification.com/2009/05/05/learning-me-but-im-an-expert/</link>
		<comments>http://www.hackification.com/2009/05/05/learning-me-but-im-an-expert/#comments</comments>
		<pubDate>Tue, 05 May 2009 11:56:15 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[learning]]></category>
		<category><![CDATA[quotes]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=167</guid>
		<description><![CDATA[You&#8217;ve been a coder for a few years now, maybe even decades. You&#8217;ve got a successful job, making enough money. You know the &#8220;respectable&#8221; technologies that the recruiters look for: C++, C#, Java, whatever. There&#8217;s no need to learn anything new. Stay in your comfort zone. Take it from these guys: &#8220;I think there’s a [...]]]></description>
			<content:encoded><![CDATA[<p><img class="alignleft size-full wp-image-176" style="margin-left: 8px; margin-right: 8px;" title="Dinosaur" src="http://www.hackification.com/wp-content/uploads/2009/05/dinosaur.png" alt="Dinosaur" width="124" height="100" />You&#8217;ve been a coder for a few years now, maybe even decades. You&#8217;ve got a successful job, making enough money. You know the &#8220;respectable&#8221; technologies that the recruiters look for: C++, C#, Java, whatever. There&#8217;s no need to learn anything new. Stay in your comfort zone. Take it from these guys:</p>
<p><span id="more-167"></span></p>
<blockquote><p><strong>&#8220;I think there’s a world market for about 5 computers.&#8221;</strong><br />
<em></em></p>
<p><em>- Thomas J. Watson, Chairman of the Board, IBM, circa 1948</em></p></blockquote>
<blockquote><p><strong>&#8220;It would appear that we have reached the limits of what it is possible to achieve with computer technology, although one should be careful with such statements, as they tend to sound pretty silly in 5 years.&#8221;</strong><br />
<em></em></p>
<p><em>- John Von Neumann, circa 1949</em></p></blockquote>
<blockquote><p><strong>&#8220;But what is it good for?&#8221;</strong><br />
<em></em></p>
<p><em>- Engineer at the Advanced Computing Systems Division of IBM, commenting on the microchip, 1968</em></p></blockquote>
<blockquote><p><strong>&#8220;There is no reason for any individual to have a computer in his home.&#8221;</strong><br />
<em></em></p>
<p><em>- Ken Olson, President, Digital Equipment Corporation, 1977</em></p></blockquote>
<p>Wise words indeed.</p>
<p>You need to learn when you know you don&#8217;t know enough, sure. It&#8217;s easy to pick up a book when you&#8217;re feeling clueless. The more dangerous time is when you think you do know enough. Coding (and computer science) is like the <a href="http://en.wikipedia.org/wiki/Red_Queen%27s_race" target="_blank">Red Queen&#8217;s Race</a>: you need to run as fast as you can just to stay still.</p>
<ul>
<li>When was the last time you bought or borrowed a technical book?</li>
<li>When was the last time you bought or borrowed a technical book, and then <em>actually </em><em>read it</em>?</li>
<li>When was the last time you bought or borrowed a technical book, and read it, <em>where it was of no immediate use to your job</em>?</li>
</ul>
<p><strong>Leave your comfort zone. Admit your ignorance. Learn something new. Learn something useless. Because next year, you might be kicking yourself for calling it useless. Don&#8217;t tell me that what you know now is all you&#8217;ll ever need to know. Don&#8217;t get quoted in next year&#8217;s list.</strong></p>
<p><em>If you liked the quotes above, you might also be interested in &#8220;<a title="Permanent Link: A Double Handful of Programming Quotes" rel="bookmark" href="../2008/12/23/a-double-handful-of-programming-quotes/">A Double Handful of Programming Quotes</a>&#8220;.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/05/05/learning-me-but-im-an-expert/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Forcing The Browser To Cache Dynamic Content In ASP.NET</title>
		<link>http://www.hackification.com/2009/05/01/forcing-the-browser-to-cache-dynamic-content-in-aspnet/</link>
		<comments>http://www.hackification.com/2009/05/01/forcing-the-browser-to-cache-dynamic-content-in-aspnet/#comments</comments>
		<pubDate>Fri, 01 May 2009 09:14:41 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[caching]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=143</guid>
		<description><![CDATA[Usually, you don&#8217;t want the browser doing any kind of caching on dynamic content served from a generic handler (.ASHX) in ASP.NET &#8211; afterall, the content is usually changing (dynamic). Sometimes however, it&#8217;s handy to use a handler to serve content that effectively never changes. Here&#8217;s how. One common example (that we make use of [...]]]></description>
			<content:encoded><![CDATA[<p>Usually, you don&#8217;t want the browser doing any kind of caching on dynamic content served from a generic handler (.ASHX) in ASP.NET &#8211; afterall, the content is usually changing (dynamic). Sometimes however, it&#8217;s handy to use a handler to serve content that effectively never changes. Here&#8217;s how.</p>
<p><span id="more-143"></span>One common example (that we make use of heavily in <a title="EasyAs123Web.com" href="http://www.easyas123web.com" target="_blank">EasyAs123Web.com</a>) is using a handler to serve and generate images on-the-fly. Our user images are stored in the database, and are immutable &#8211; they never change. Hence we&#8217;d like the client browser to cache the image returned.</p>
<p><strong>Example Handler</strong></p>
<p>Let&#8217;s start with the shell of a generic handler, MyHandler.ashx.cs:</p>
<pre>public class MyHandler : IHttpHandler
{
  public void ProcessRequest( HttpContext context )
  {
    ...
  }

  public bool IsReusable
  {
    get
    {
      return true;
    }
  }
}</pre>
<p>Further code will go where I&#8217;ve marked with ellipses.</p>
<p><strong>Reponse Headers</strong></p>
<p>For some reason, ASP.NET automatically adds headers that stop the browser from caching the content, and you can&#8217;t just override them. Instead, you&#8217;ll need to clear them all out first:</p>
<pre>context.Response.ClearHeaders();</pre>
<p>Next we want to mark the content as fully cacheable, and expiring at some date in the future:</p>
<pre>context.Response.Cache.SetValidUntilExpires( true );
context.Response.Cache.SetCacheability( HttpCacheability.Public );
context.Response.Cache.SetExpires( DateTime.Now.AddMonths( 1 ) );
context.Response.Cache.SetLastModified( DateTime.Now.AddMonths( -1 ) );</pre>
<p>(I&#8217;ve marked the content as expiring in a month, but you could easily add a year or ten years or whatever).</p>
<p>If you are able to calculate some form of hash for your content (which you should be able to do pretty easily), you can add an <a href="http://en.wikipedia.org/wiki/HTTP_ETag" target="_blank">ETag</a>:</p>
<pre>Guid hash = ...;

context.Response.Cache.SetETag( "\"" + hash.ToString().Replace( "-", "" ) + "\"" );</pre>
<p>Finally, there&#8217;s one more trick which is incredibly useful for allowing browsers to avoid re-downloading the content.</p>
<p>Browsers may include the <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.25" target="_blank">&#8220;If-Modified-Since&#8221; request header</a>. If you ignore this header, no problems occur: you just send the content as usual. However, you can use it to inform the browser that your content hasn&#8217;t changed since the last time it was requested.</p>
<p>If your content really hasn&#8217;t changed, instead of sending a &#8220;200 OK&#8221; response with all the content, you can send back a &#8220;304 Not Modified&#8221; without any content whatsoever:</p>
<pre>var textIfModifiedSince = context.Request.Headers["If-Modified-Since"];

if( !string.IsNullOrEmpty( textIfModifiedSince ) )
{
  context.Response.Status = "304 Not Modified";
  context.Response.End();

  return;
}</pre>
<p>So instead of sending back a potentially large piece of content, you can send back just the tiny response headers.</p>
<p>You can do a similar trick with <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.26" target="_blank">&#8220;If-None-Match&#8221;</a> &#8211; I&#8217;ll leave that as an exercise.</p>
<p><strong>Debugging</strong></p>
<p>Making these changes is all very well, but can you be sure that your changes are actually having the desired effects?</p>
<p>There are two great tools you can use to actually view the requests sent by the browser, and the response sent from your web-app:</p>
<ul>
<li>For debugging with Firefox: <a href="https://addons.mozilla.org/en-US/firefox/addon/3829" target="_blank">Live HTTP Headers</a>.</li>
<li>For Internet Explorer: <a href="http://www.fiddler2.com/fiddler2/" target="_blank">Fiddler 2</a>.</li>
</ul>
<p>If you care about the speed and bandwidth usage of your ASP.NET application, I&#8217;d say that these two are pretty much indispensable. You&#8217;ll want to test with both: different browsers make subtly different requests, and interpret the responses differently.</p>
<p>You might also want to use <a href="https://addons.mozilla.org/en-US/firefox/addon/5369" target="_blank">YSlow</a> for Firebug: this has some nice graphical displays of page assets.</p>
<p><strong>Example &#8211; Content Not In Cache</strong></p>
<p>Request and response, some lines omitted for clarity.<strong><br />
</strong></p>
<pre>GET /!!/_Serving/StaticFile/Style/Pro/Images/HomeCreate.jpg HTTP/1.1
Host: www.easyas123web.com</pre>
<pre>HTTP/1.x 200 OK
Cache-Control: public
Content-Type: image/jpeg
Expires: Mon, 01 Jun 2009 08:58:36 GMT
Last-Modified: Wed, 01 Apr 2009 08:58:36 GMT
Etag: "45403f772717d1c63c0b8774e4a124b7"
Content-Length: 20696
... 20K of content here ...</pre>
<p><strong>Example &#8211; Content In Cache</strong></p>
<p>Request and response, some lines omitted for clarity.<strong><br />
</strong></p>
<pre>GET /!!/_Serving/StaticFile/Style/Pro/Images/HomeCreate.jpg HTTP/1.1
Host: www.easyas123web.com
If-Modified-Since: Wed, 01 Apr 2009 08:58:36 GMT</pre>
<pre>HTTP/1.x 304 Not Modified
Cache-Control: public
Expires: Mon, 01 Jun 2009 09:03:51 GMT
Last-Modified: Wed, 01 Apr 2009 09:03:51 GMT
Etag: "45403f772717d1c63c0b8774e4a124b7"</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/05/01/forcing-the-browser-to-cache-dynamic-content-in-aspnet/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Consolas: Visual Studio&#039;s Hidden Gem</title>
		<link>http://www.hackification.com/2009/04/16/consolas-visual-studios-hidden-gem/</link>
		<comments>http://www.hackification.com/2009/04/16/consolas-visual-studios-hidden-gem/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 11:44:45 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[consolas]]></category>
		<category><![CDATA[fonts]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=112</guid>
		<description><![CDATA[Out of the box, Visual Studio uses the Courier New font for displaying code. While that&#8217;s an acceptable font for programming, it&#8217;s hardly modern or easy on the eye. Did you know that Microsoft supply a much more readable alternative, for free? Courier New has been around since 1955 &#8211; and that it&#8217;s been around [...]]]></description>
			<content:encoded><![CDATA[<p>Out of the box, Visual Studio uses the Courier New font for displaying code. While that&#8217;s an acceptable font for programming, it&#8217;s hardly modern or easy on the eye. Did you know that Microsoft supply a much more readable alternative, for free?</p>
<p><span id="more-112"></span>Courier New has been around since 1955 &#8211; and that it&#8217;s been around so long is a testament to its readability. However since then, display technology has radically changed &#8211; I&#8217;d be amazed if you weren&#8217;t reading this article on some form of TFT panel, and if using Windows, with ClearType enabled.</p>
<p>Enter Consolas.  For the release of Office 2007, Microsoft commissioned a set of modern fonts, designed to be highly readable on screens that use ClearType: Calibri, Candara, Cambria, Consolas, Constantia and Corbel. Of that set, Consolas makes an <em>excellent </em>monospaced code font.</p>
<p><strong>Here&#8217;s Courier New:</strong></p>
<p><img class="alignnone size-full wp-image-115" title="Courier New Example" src="http://www.hackification.com/wp-content/uploads/2009/04/couriernew.png" alt="Courier New Example" width="350" height="256" /></p>
<p><strong>And here&#8217;s Consolas:</strong></p>
<p><img class="alignnone size-full wp-image-116" title="Consolas Example" src="http://www.hackification.com/wp-content/uploads/2009/04/consolas.png" alt="Consolas Example" width="306" height="241" /></p>
<p>To my eyes, that&#8217;s a big improvement. You&#8217;ll notice as well that Consolas is slightly narrower, enabling you to fit a bit more text on the screen.</p>
<p><strong>So where can you get it?</strong></p>
<p>If you have Visual Studio, you can download it directly from Microsoft:</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=22e69ae4-7e40-4807-8a86-b3d36fab68d3&amp;displaylang=en" target="_blank">http://www.microsoft.com/downloads/details.aspx?familyid=22e69ae4-7e40-4807-8a86-b3d36fab68d3&amp;displaylang=en</a></p>
<p>Or if not, it comes as part of the free Powerpoint viewer:</p>
<p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=048DC840-14E1-467D-8DCA-19D2A8FD7485&amp;displaylang=en" target="_blank">http://www.microsoft.com/downloads/details.aspx?familyid=048DC840-14E1-467D-8DCA-19D2A8FD7485&amp;displaylang=en</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/04/16/consolas-visual-studios-hidden-gem/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Using WPF To Generate Web Images</title>
		<link>http://www.hackification.com/2009/04/10/using-wpf-to-generate-web-images/</link>
		<comments>http://www.hackification.com/2009/04/10/using-wpf-to-generate-web-images/#comments</comments>
		<pubDate>Fri, 10 Apr 2009 21:27:37 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Experiments]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[Tutorials]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[images]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=95</guid>
		<description><![CDATA[Recently I needed to display rotated graphics within a web-page. Since there&#8217;s no way to do that cross-browser using CSS, I needed to auto-generate a collection of pre-rotated images that could be displayed as CSS sprites. I&#8217;ve found that WPF (Windows Presentation Foundation) is great for generating batches of images suitable for use in web [...]]]></description>
			<content:encoded><![CDATA[<p>Recently I needed to display rotated graphics within a web-page. Since there&#8217;s no way to do that cross-browser using CSS, I needed to auto-generate a collection of pre-rotated images that could be displayed as CSS sprites. I&#8217;ve found that WPF (Windows Presentation Foundation) is great for generating batches of images suitable for use in web apps.</p>
<p><span id="more-95"></span></p>
<p>Let&#8217;s start with an example graphic, Arrow.xaml:</p>
<pre>&lt;UserControl x:Class="WebImagesGenerator.Graphics.Arrow"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  Height="64" Width="64"&gt;
  &lt;Canvas Width="64" Height="64"&gt;
    &lt;Polygon Points="32,4 60,32 42,32 42,60 22,60 22,32 4,32"
      Fill="Red" Stroke="Black"
      StrokeThickness="3" StrokeLineJoin="Round" /&gt;
  &lt;/Canvas&gt;
&lt;/UserControl&gt;</pre>
<p>That&#8217;s just a standard XAML file, nothing fancy there.</p>
<p>Rendering WPF content to an image is really easy; you use the RenderTargetBitmap class. I wanted to be able to produce a strip of images, all the same except rotated, that can be used as CSS sprites. For my actual web application, I have a quick console application that generates the images as a batch. If I ever change the XAML files, I can quickly re-generate all the auto-generated images in my project just be running my console application.</p>
<p>Let&#8217;s get started on the console application:</p>
<pre>[STAThread]
static void Main( string[] args )
{
  var arrow = new Graphics.Arrow();

  SaveStrip( arrow, GenerateSeries( 0, 360, 10 )
           , "..\\..\\Testing\\arrows.png" );
}</pre>
<p>WPF must be run in a [STAThread] context. I create an instance of my graphic, then call my SaveStrip routine. GenerateSeries simply returns an array of integers:</p>
<pre>static int[] GenerateSeries( int start, int end, int step )
{
  var series = new List&lt;int&gt;();

  for( var v = start; v &lt; end; v += step )
  {
    series.Add( v );
  }

  return series.ToArray();
}</pre>
<p>The real magic happens in SaveStrip:</p>
<pre>static void SaveStrip( FrameworkElement fe, int[] angles, string filename )
{
  var outer = new Canvas();

  outer.Width = fe.Width * angles.Length;
  outer.Height = fe.Height;

  outer.Children.Add( fe );

  outer.Arrange( new Rect( 0, 0, outer.Width, outer.Height ) );

  var bmp = new RenderTargetBitmap
    ( (int) fe.Width * angles.Length
    , (int) fe.Height, 96, 96, PixelFormats.Pbgra32 );

  for( var i = 0; i &lt; angles.Length; ++i )
  {
    var transforms = new TransformGroup();

    transforms.Children.Add
      ( new RotateTransform( angles[i], fe.Width / 2, fe.Height / 2 ) );

    fe.RenderTransform = transforms;
    fe.SetValue( Canvas.LeftProperty, i * fe.Width );

    // The following line is VITAL!
    outer.Arrange( new Rect( 0, 0, outer.Width, outer.Height ) );

    bmp.Render( fe );
  }

  var encoder = new PngBitmapEncoder();

  encoder.Frames.Add( BitmapFrame.Create( bmp ) );

  using( var stream = File.Create( filename ) )
  {
    encoder.Save( stream );
  }
}</pre>
<p>When I first tried this technique, all my output bitmaps were completely blank. After debugging for a while, I realised that all my graphics were of zero size. You MUST call Arrange() on your elements before calling Render(), otherwise they won&#8217;t have been laid out properly.</p>
<p>When run, this console app produces the following (reduced in size to fit):</p>
<p><img class="alignnone size-full wp-image-102" title="WPF-Generated Images" src="http://www.hackification.com/wp-content/uploads/2009/04/arrows1.png" alt="WPF-Generated Images" width="580" height="15" /></p>
<p>Fantastic! To get a better idea of how such images might appear in a web-page, I&#8217;ve created a little HTML+jQuery demo to see a very quick example of the images in use:</p>
<blockquote><p><strong><a href="http://www.hackification.com/jquery-examples/test-wpf-images.htm" target="_blank">View Demo</a></strong></p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/04/10/using-wpf-to-generate-web-images/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>My JavaScript Code Organization Journey (So Far)</title>
		<link>http://www.hackification.com/2009/03/01/my-javascript-code-organization-journey-so-far/</link>
		<comments>http://www.hackification.com/2009/03/01/my-javascript-code-organization-journey-so-far/#comments</comments>
		<pubDate>Sun, 01 Mar 2009 19:09:37 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[JavaScript]]></category>
		<category><![CDATA[namespaces]]></category>
		<category><![CDATA[private]]></category>
		<category><![CDATA[public]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=83</guid>
		<description><![CDATA[If you&#8217;ve been reading this blog, you&#8217;ll know that I&#8217;ve been doing more and more JavaScript coding recently. One aspect that&#8217;s very different to C# coding is that there&#8217;s no explicit notion of &#8216;public&#8217; or &#8216;private&#8217; methods. This article explains my own journey towards implementing these concepts in JavaScript. Stage One: No Access Control, Massive [...]]]></description>
			<content:encoded><![CDATA[<p>If you&#8217;ve been reading this blog, you&#8217;ll know that I&#8217;ve been doing more and more JavaScript coding recently. One aspect that&#8217;s very different to C# coding is that there&#8217;s no explicit notion of &#8216;public&#8217; or &#8216;private&#8217; methods. This article explains my own journey towards implementing these concepts in JavaScript.</p>
<p><span id="more-83"></span></p>
<p><strong>Stage One: No Access Control, Massive Pollution</strong></p>
<p>My first JavaScript files looked a lot like this:</p>
<pre>function myPrivateMethod()
{
  ...
}

function myPublicMethod()
{
  ...
  myPrivateMethod();
  ...
}
</pre>
<p>My functions were just dumped straight into the global context, &#8220;polluting&#8221; it, and there was no kind of access control &#8211; all methods could be called from anywhere.</p>
<p><strong>Stage Two: Coding-Convention Access Control, Minimal Pollution</strong></p>
<p>My next strategy for defining function was to create a single object in the global scope, then add functions as properties of that object. I still hadn&#8217;t figured out access control, other than by using a naming convention:</p>
<pre>if (typeof MyNamespace == 'undefined') {
  MyNamespace = {};
}

MyNamespace._privateMethod = function() {
  ...
}

MyNamespace.publicMethod = function() {
  ...
  MyNamespace._privateMethod();
  ...
}
</pre>
<p>While this is better than before, it&#8217;s still not true access control.</p>
<p><strong>Stage Three: Access Control, Plus Namespaces<br />
</strong></p>
<p>The latest way I&#8217;ve <a href="http://www.dustindiaz.com/javascript-private-public-privileged/" target="_blank">discovered</a> for arranging code gives namespaces and true access control.</p>
<pre>var MyNamespace = window.MyNamespace || {};

MyNamespace.MyModule = function() {

  var privateMethod = function() {
    ...
  };

  return {

    publicMethod : function() {
      ...
      privateMethod();
      ...
    }

  };
}();
</pre>
<p>I&#8217;d seen examples like the above back when I first started coding JavaScript, but I don&#8217;t like cargo-cult-copy-paste code: if I don&#8217;t understand code, I don&#8217;t use it. It&#8217;s taken me this long to understand every line in the above. Now that I do, I can start to refactor my existing code where necessary to use this pattern.</p>
<p>The interesting points in the above code example are:</p>
<ul>
<li>The first line is a much more compact way of determining whether the single global variables is defined already (for example from another code file), and if it&#8217;s not, creating it.</li>
<li>The &#8216;module&#8217; property is assigned from the immediate invocation of an anonymous function. This anonymous function returns an object whose properties are the functions we want to make public.</li>
<li>The private functions are created as inner functions of the outer anonymous function. The public functions retains access to these private functions via the magic of closures.</li>
</ul>
<p>It continually amazes me how the JavaScript langauge manages to allow a developer so many features (in this article I&#8217;ve covered public/private and namespaces), without needing to include them as first-class keywords in the langauge.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/03/01/my-javascript-code-organization-journey-so-far/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Closures: Simplify Event Handling Code</title>
		<link>http://www.hackification.com/2009/02/20/closures-simplify-event-handling-code/</link>
		<comments>http://www.hackification.com/2009/02/20/closures-simplify-event-handling-code/#comments</comments>
		<pubDate>Fri, 20 Feb 2009 14:56:36 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Coding]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[c#]]></category>
		<category><![CDATA[ajax]]></category>
		<category><![CDATA[closures]]></category>
		<category><![CDATA[javascrip]]></category>
		<category><![CDATA[jquery]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=82</guid>
		<description><![CDATA[Closures are a really useful programming construct, but as they&#8217;re only just appearing in the C-family languages, they&#8217;re relatively new to me. In this article I show how they can be used to vastly simplify event-handler code in web development. One problem I&#8217;ve had with this subject is the rather mathematical explanations given. Wikipedia says [...]]]></description>
			<content:encoded><![CDATA[<p>Closures are a really useful programming construct, but as they&#8217;re only just appearing in the C-family languages, they&#8217;re relatively new to me. In this article I show how they can be used to vastly simplify event-handler code in web development.</p>
<p><span id="more-82"></span></p>
<p>One problem I&#8217;ve had with this subject is the rather mathematical explanations given. <a href="http://en.wikipedia.org/wiki/Closure_(computer_science)" target="_blank">Wikipedia</a> says that &#8220;<em>&#8230;a <strong>closure</strong> is a <span class="mw-redirect">function</span> that is evaluated in an environment containing one or more <span class="mw-redirect">bound variables</span>. When called, the function can access these variables</em>&#8220;. Unfortunately that doesn&#8217;t exactly &#8216;speak&#8217; to me, so I thought I&#8217;d present a code-based example.</p>
<p><strong>The Problem</strong></p>
<p>Let&#8217;s say we have a web-page, containing a table, where the rows are identified by an identifier. (This is pretty common &#8211; displaying one row on the webpage for each row in a database table). On each row are delete links, and when clicked, they open an AJAX dialog in the webpage, confirming the deletion. When the user clicks &#8216;OK&#8217; in the dialog, the row with that ID is deleted.</p>
<p>Pretty standard stuff hopefully. I&#8217;m going to omit loads of details to make this shorter &#8211; the dialog isn&#8217;t even vaguely modal, and there&#8217;s no cancel button, and the deleting won&#8217;t work.</p>
<p><strong>ASP.NET AJAX</strong></p>
<p>So let&#8217;s start with an ASP.NET AJAX solution. Here&#8217;s my ASPX page (minus the boilerplate stuff like the UpdatePanel):</p>
<pre>&lt;asp:Repeater runat="server" ID="_repeater"&gt;
  &lt;HeaderTemplate&gt;
    &lt;table&gt;
      &lt;tbody&gt;
  &lt;/HeaderTemplate&gt;
  &lt;ItemTemplate&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;asp:Label runat="server"
                Text='&lt;% #Container.DataItem %&gt;' /&gt;&lt;/td&gt;
          &lt;td&gt;&lt;asp:LinkButton runat="server" Text="Delete"
                OnClick="_deleteLink_Click"
                CommandArgument='&lt;% #Container.DataItem %&gt;' /&gt;&lt;/td&gt;
        &lt;/tr&gt;
  &lt;/ItemTemplate&gt;
  &lt;FooterTemplate&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/FooterTemplate&gt;
&lt;/asp:Repeater&gt;

&lt;div runat="server" id="_dialog" visible="false"&gt;
  &lt;asp:Button runat="server" Text="OK" OnClick="_okButton_Click" /&gt;
&lt;/div&gt;</pre>
<p>And here&#8217;s some of the code-behind:</p>
<pre>protected void Page_Load( object sender, EventArgs e )
{
  _repeater.DataSource = new[] { 1, 2, 3, 4, 5 };
  _repeater.DataBind();
}

protected void _deleteLink_Click( object sender, EventArgs e )
{
  var linkButton = (LinkButton) sender;
  var id = int.Parse( linkButton.CommandArgument );

  _dialog.Visible = true;

  <strong>// <span style="color: #ffff00;">Store 'id' somehow</span>.</strong>
}

protected void _okButton_Click( object sender, EventArgs e )
{
  _dialog.Visible = false;

  <strong>// <span style="color: #ffff00;">Retrieve 'id' somehow</span> and delete the row.</strong>
}</pre>
<p><strong>The problem occurs between the event handler for the delete link, and the event handler for the OK button.</strong> Getting the ID from the row is easy, but we need to get the value to the handler for the OK button.</p>
<p>There are solutions of course &#8211; we could store it in a hidden field of the dialog, or in the view state &#8211; but there&#8217;s a big disconnect there. The scope of the OK button click handler is completely different to the scope of the delete link handler.</p>
<p><strong>jQuery AJAX</strong></p>
<p>I&#8217;m now starting to feel that ASP.NET AJAX is great for quick intranet applications, but for &#8220;real-world&#8221; internet applications, it&#8217;s better to do more of the work client-side, &#8216;by hand&#8217;.</p>
<p>The ASPX I&#8217;d use is very similar to the previous example &#8211; instead of ASP.NET click handlers, I&#8217;d add classes and ids to attach metadata to the table:</p>
<pre>&lt;asp:Repeater runat="server" ID="_repeater"&gt;
  &lt;HeaderTemplate&gt;
    &lt;table&gt;
      &lt;tbody&gt;
  &lt;/HeaderTemplate&gt;
  &lt;ItemTemplate&gt;
        &lt;tr&gt;
          &lt;td&gt;&lt;asp:Label runat="server"
                Text='&lt;% #Container.DataItem %&gt;'
                CssClass="data-id" /&gt;&lt;/td&gt;
          &lt;td&gt;&lt;a class="action-delete" href="#"&gt;Delete&lt;/a&gt;&lt;/td&gt;
        &lt;/tr&gt;
  &lt;/ItemTemplate&gt;
  &lt;FooterTemplate&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;
  &lt;/FooterTemplate&gt;
&lt;/asp:Repeater&gt;

&lt;div id="delete-dialog" style="display: none;"&gt;
  &lt;input type="button" value="OK" id="delete-dialog-ok" /&gt;
&lt;/div&gt;</pre>
<p>(Of course you could generate the appropriate HTML with any HTML templating system).</p>
<p>Before I get to the interesting jQuery bit, I also need to define a handler &#8211; Delete.ashx &#8211; which will process the jQuery AJAX call:</p>
<pre>public class Delete : IHttpHandler
{
  public void ProcessRequest( HttpContext context )
  {
    var id = int.Parse( context.Request["id"] );

    // Delete the row here.

    context.Response.ContentType = "application/json";
    context.Response.Write( "{}" );
  }
}</pre>
<p>That is admittedly more work than hooking an ASP.NET event handler. (You&#8217;d probably want to check the request was a POST somewhere in there too).</p>
<p>Now for the interesting jQuery bit:</p>
<pre>$(function() {

    <span style="color: #ccffcc;">//
    // When the user clicks a delete link...
    //
</span>
    $('.action-delete').click(function() {

        <span style="color: #ccffcc;">//
        // Find the ID in the row,
        //</span>
        <span style="color: #ffff00;">var <strong>rowId</strong></span> = $(this).closest('tr').find('.data-id').text();

        <span style="color: #ccffcc;">//
        // Show the delete dialog,
        //</span>
        $('#delete-dialog').show();

        <span style="color: #ccffcc;">//
        // And attach a click handler to the OK button,
        // and when that is clicked...
        //</span>
        $('#delete-dialog-ok').click(function() {

            <span style="color: #ccffcc;">//
            // Initiate an AJAX POST, and when it succeeds...
            //</span>
            $.post('Delete.ashx', { <span style="color: #ffff00;">id: <strong>rowId</strong></span> }, function() {
                <span style="color: #ccffcc;">//
                // Unbind the OK button click, and hide the dialog.
                //</span>
                $('#delete-dialog-ok').unbind('click');
                $('#delete-dialog').hide();
            }, 'json');
        });
    });

});</pre>
<p>That&#8217;s real magic. The &#8216;rowId&#8217; local was created on the first &#8216;delete link&#8217; click, but it remains available to the handler for the second OK button click.</p>
<p>The interesting thing here is that I haven&#8217;t had to pass or manually store the ID anywhere. When the user clicks on an &#8216;action-delete&#8217; link, I find the ID value, show the dialog, and then just attach a &#8216;click&#8217; handler to the dialog OK button. Because the &#8216;click&#8217; handler is inline, it has access to the variables in its parent&#8217;s scope.</p>
<p>The other advantage to doing this this way, which has nothing to do with closures, is that the manual jQuery AJAX version doesn&#8217;t talk to the server with every click, only on the final one. ASP.NET AJAX will chat to the server as the user clicks the delete links, giving a slightly slower feel.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/02/20/closures-simplify-event-handling-code/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Deadlines vs. Estimates</title>
		<link>http://www.hackification.com/2009/02/02/deadlines-vs-estimates/</link>
		<comments>http://www.hackification.com/2009/02/02/deadlines-vs-estimates/#comments</comments>
		<pubDate>Mon, 02 Feb 2009 21:21:45 +0000</pubDate>
		<dc:creator>Stu Smith</dc:creator>
				<category><![CDATA[Coding]]></category>
		<category><![CDATA[Opinion]]></category>
		<category><![CDATA[Tips]]></category>
		<category><![CDATA[deadlines]]></category>
		<category><![CDATA[estimates]]></category>

		<guid isPermaLink="false">http://www.hackification.com/?p=65</guid>
		<description><![CDATA[I spotted a question over on StackOverflow the other day that piqued my interest &#8211; &#8220;How do you handle scheduling/deadlines around programmers?&#8221; &#8211; and I thought I&#8217;d note down my thoughts since I&#8217;ve noticed that a lot of people either confuse deadlines with estimates, or feel there&#8217;s some sort of battle between programmers and managers. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="None"><img class="alignleft size-full wp-image-74 left-image" style="float: left;" title="Deadline" src="http://www.hackification.com/wp-content/uploads/2009/02/deadline.jpg" alt="" width="123" height="81" /></a>I spotted a question over on StackOverflow the other day that piqued my interest &#8211; &#8220;<a href="http://stackoverflow.com/questions/381089/how-do-you-handle-schedulingdeadlines-around-programmers">How do you handle scheduling/deadlines around programmers?</a>&#8221; &#8211; and I thought I&#8217;d note down my thoughts since I&#8217;ve noticed that a lot of people either confuse deadlines with estimates, or feel there&#8217;s some sort of battle between programmers and managers.</p>
<p><span id="more-65"></span></p>
<p>The basic difference is this:</p>
<ul>
<li>Deadlines come from <strong>external sources</strong>, for example, &#8220;Feature X needs to be ready for the summer trade show&#8221;.</li>
<li>Estimates come from <strong>internal sources</strong>, for example, &#8220;Feature X will take me N weeks to complete&#8221;.</li>
</ul>
<p>Generally, the sales/marketing department will create deadlines, and the development team should create estimates. Note that word &#8216;should&#8217; there &#8211; I&#8217;ll talk about what happens if that&#8217;s not the case in a moment.</p>
<p>Generally, problems only occur if the deadline is shorter than the estimate. Let&#8217;s face it, if the deadline is six months away, and you estimate the task will take three months, then so long as your estimate is roughly accurate, then there&#8217;s not going to be too much stress. (Of course, you really ought to use the remaining spare months constructively).</p>
<p>If the deadline is shorter than the estimate however, then that&#8217;s when the problems start. Here&#8217;s a few hints to help ease this situation:</p>
<p><strong>1. Hint for managers: Let the person doing the work create the estimate</strong></p>
<p>In many programming environments, the same person creates both deadlines and estimates: the programmer is given a task with the words &#8220;you have N weeks to complete this&#8221;. This is bad for two reasons: one, the task is unlikely to be completed in the allocated time, thus missing the deadline, and two, the programmer is likely to feel stress and loss of motivation. Basically, you&#8217;re fooling yourself, and telling the developer you don&#8217;t think they&#8217;re capable of estimating.</p>
<p>If you&#8217;re the sort of manager who does this, it&#8217;s important to understand that even if you don&#8217;t let the programmer give a formal estimate, they will have an informal one in their head anyway, so they&#8217;ll know from the outset whether they feel able to hit the deadline. Impossible goals are demotivating and lead to reduced performance.</p>
<p><strong>2. Hint for managers: Don&#8217;t override an estimate with a deadline</strong></p>
<p>If you ask for an estimate (and you should), and it isn&#8217;t what you want, don&#8217;t just overrule it by saying something like &#8220;well it has to be done sooner&#8221;. This is another sure route to demotivation. If you don&#8217;t like the answer, the only real options are:</p>
<ul>
<li>Ask the developer for a more accurate estimate (but this is only an option if you have reason to believe the estimate is inaccurate &#8211; see points 3 and 5 below);</li>
<li>Ask (or force) the developers to work overtime;</li>
<li>Trim features;</li>
<li>Or of course, miss the deadline.</li>
</ul>
<p>If these options all seem a little confrontational, that&#8217;s because they are: you can either admit that, and work towards a compromise in a professional manner, or you can pretend otherwise, and end up in an abusive, passive-aggressive, or just plain nasty stance.</p>
<p><strong>3. Hint for developers: Respect for your estimates only flows from accurate estimates</strong></p>
<p>If you&#8217;re a programmer in the situation above, the best way to convince management that you should be making the estimates (and that they&#8217;re worth anything) is to provide accurate estimates. If you always significantly over- or under- estimate the time required, there&#8217;s no incentive for the manager to stop providing their own (inaccurate) estimates.</p>
<p><strong>4. Hint for developers: Accurate estimates come from tiny tasks</strong></p>
<p>Use divide-and-conquer to estimate times. The finer-grained the tasks are, the more accurate the estimates are. Split the entire task into sub-tasks of no bigger than a day. This forces you to really think about what&#8217;s involved in coding each task. The shorter the task, the more accurate your estimate will be. If each of your sub-tasks are a week (or longer) in length, you&#8217;ll likely be way out.</p>
<p><strong>5. Hint for developers: Review your estimates after the event</strong></p>
<p>Don&#8217;t just &#8220;fire and forget&#8221; your estimates. At the completion of the task, review what areas you were and weren&#8217;t accurate with. Make a note of your ongoing accuracy: when your boss challenges your latest estimate you&#8217;ll have cold hard evidence that your estimates are accurate.</p>
<p><strong>6. Hint for marketing: Explain the reason for the deadline</strong></p>
<p>So often, a deadline comes down from on high with no reason, with no added explanation other than a threat should the deadline be missed. Developers wonder what all the fuss is about, and management can&#8217;t understand why the programmers aren&#8217;t working extra hard. Result: no-one is happy.</p>
<p>Hopefully, there&#8217;s a good reason for the deadline &#8211; so tell everyone. If you&#8217;re worried you&#8217;ll lose a big sale if the new version isn&#8217;t ready soon, then explain that. If the only thing stopping a major customer using your product is one or two last features, then explain the situation: X thousand dollars profit if the features are coded in a timely manner, or no extra profit if your competitor gets there first.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hackification.com/2009/02/02/deadlines-vs-estimates/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
