<?xml version="1.0" encoding="UTF-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>Technical Musings</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/" />
    <link rel="self" type="application/atom+xml" href="http://www.safnet.com/writing/tech/atom.xml" />
    <id>tag:www.safnet.com,2011-11-05:/writing/tech//3</id>
    <updated>2013-06-07T02:17:47Z</updated>
    
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type 5.12</generator>

<entry>
    <title>Active Directory and WCF Configuration Woes Resolved</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2013/06/active-directory-and-wcf-configuration-woes-resolved.html" />
    <id>tag:www.safnet.com,2013:/writing/tech//3.506</id>

    <published>2013-06-07T02:10:46Z</published>
    <updated>2013-06-07T02:17:47Z</updated>

    <summary> Configuring a WCF service across security boundaries can be a tricky business, or so I learned recently. Testing went well, but the move to production failed for a WCF client/server scenario, with the client application encountering an error: SOAP...</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="c" label="c#" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="clientserver" label="client/server" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="wcf" label="WCF" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="webservices" label="web services" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p>
Configuring a WCF service across security boundaries can be a tricky business, or so I learned recently. Testing went well, but the move to production failed for a WCF client/server scenario, with the client application encountering an error: <code>SOAP security negotation with '&lt;myEndpointAddress&gt;' for target '&lt;myEndpointAddress&gt;' failed. See inner exception for more details.</code> Inner exception: <code>The Security Support Provider Interface (SSPI) negotation failed.</code>
</p>
]]>
        <![CDATA[<p>
The solution was simple in the end, but required a good deal of research to find and understand. But before we get to that, let's talk a bit more about the setup. The actual production setup is more complicated than this, but the simplified model will suffice for the example. Because the client is in fact a second WCF service, both the client and server are on Windows Server 2008 R2 boxes, both in secure but distinct subnets. As they are both custom .Net applications, we were able to utilize netTcpBinding for increased performance and simpler security, in comparison to httpBinding and wsHttpBinding. But as we shall see, that decision had an unforeseen consequence.
</p>
<div style="width: 237px; height: 113px; margin: auto;  box-shadow: 1px 1px 3px 3px #ccc;">
<img alt="wcfClientServer1.png" src="http://www.safnet.com/writing/tech/images/wcfClientServer1.png" width="237" height="113" />
</div>
<p>
TCP binding with either Message or Transport is secured by Kerberos tokens issued by Active Directory in a Windows network, whereas wsHttpBinding uses a certificate/SSL to encrypt the communication. Thus the TCP route has lower setup overhead, in that you do not need to purchase a certificate or alternately manage a certificate server in-house. As a business-oriented programmer, I've never needed to understand Kerberos. But from my Unix sysadmin days, I knew that Kerberos was developed at MIT and provided a means for authenticating a client and server, for instance when connecting to a network file share over the SMB protocol. Thus in hindsight the problem is not at all surprising, but admittedly I did not know enough about WCF to recognize the implications at the time.
</p>
<p>
In the test environment, both servers were in the same network segment and the WCF services ran under the same service account. I was mildly concerned that I had not tested across a subnet boundary, but it turned out this was not even the problem: as I researched further, I found that (a) the two services were running under different service accounts in production, and (b) one of the service accounts  was not in the same Active Directory domain as the servers (both domains being in the same Tree, however).
</p>
<div style="width: 325px; height: 176px; margin: auto; box-shadow: 1px 1px 3px 3px #ccc;">
<img alt="wcfClientServer2.png" src="http://www.safnet.com/writing/tech/images/wcfClientServer2.png" width="325" height="176" />
</div>
<p>
To prevent getting too long winded, I won't repeat most of what I found in three particularly helpful Microsoft resources &ndash; well, helpful once I was able to put the pieces together. Alone, none of them simply stated the required practice.
</p>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ff647503.aspx">Chapter 5: Authentication, Authorization, and Identities in WCF</a></li>
<li><a href="http://technet.microsoft.com/en-us/library/cc780469(v=WS.10).aspx">What Is Kerberos Authentication?</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/vstudio/bb463274(v=vs.100).aspx">Debugging Windows Authentication Errors</a></li>
</ul>
<p>
Between these  resources, I came to realize that:
</p>
<ol>
	<li>At the time of installation, a Windows service registers itself in the Domain controller, identifying itself by name, address, and either a Server Principle Name (SPN) or User Principle Name (UPN) (the former when running the service under the default Network Service account and the latter when running under a custom account, as in my situation).</li>
	<li>When in the same subnet, it is easy for the client to find the server. I suspect - but do not have the resources to test - that this was particularly true because the same service account was running both.</li>
	<li>Service1 (the client) was trying to find Service2 as identified by UPN asdf123@domain1, but in reality it was registered under asdf@domain2. That is, the wrong Kerberos token was being issued while searching for Service2.</li>
	</ol>
<p>
The solution? Simply specify the UPN identity in the config file (if using the auto-generated client proxy) or in code, using the <a href="http://technet.microsoft.com/en-us/library/cc783351%28v=ws.10%29.aspx">fully qualified domain name</a> (FQDN):
</p>
<pre class="brush: xml">
<client>
     <endpoint address="net.tcp://Service2.MyTree.MyForest.local:1234/SomeContract" ... >
          <identity>
               <userPrincipleName value="asdf@domain2.MyTree.MyForest.local">
               </userPrincipleName>
          </identity>
     </endpoint>
</client>
</pre>
<p>
(In a simpler situation, the FQDN would probably be <code>domain1.local</code>.) In C#, this can be done when creating the EndpointAddress:
</p>
<pre class="brush: csharp">
var uri = "net.tcp://Service2.MyTree.MyForest.local:1234/SomeContract";
var upn = EndpointIdentity.CreateUpnIdentity("asdf@domain2.MyTree.MyForest.local");
var endpointAddress = new EndpointAddress(uri, upn);

var binding = new NetTcpBinding(); 
// set additional options
var channelFactory = new ChannelFactory<ISomeContract>(binding, endpointAddress);

var client = channelFactory.CreateChannel();
</pre>
<p>
When running under the Network Service account &ndash; that is, using an SPN instead of UPN &ndash;:
</p>
<pre class="brush: xml">
<identity>
     <servicePrincipleName value="host/Service2.MyTree.MyForest.local:1234" />
</identity>
</pre>
<p>
And 
</p>
<pre class="brush: csharp">
var upn = EndpointIdentity.CreateSpnIdentity("host/Service2.MyTree.MyForest.local:1234");
</pre>
<p>
By the way, after finding the answer, I learned that the System log on Service2 actually had a very helpful error message in it; it tells us about using the FQDN and that the wrong account was being used:
</p>
<blockquote>
The Kerberos client received a KRB_AP_ERR_MODIFIED error from the server <username>. The target name used was host/<host>.<domain>.local. This indicates that the target server failed to decrypt the ticket provided by the client. This can occur when the target server principal name (SPN) is registered on an account other than the account the target service is using. Please ensure that the target SPN is registered on, and only registered on, the account used by the server. This error can also happen when the target service is using a different password for the target service account than what the Kerberos Key Distribution Center (KDC) has for the target service account. Please ensure that the service on the server and the KDC are both updated to use the current password. If the server name is not fully qualified, and the target domain (<user's domain>) is different from the client domain (<client's domain>.LOCAL), check if there are identically named server accounts in these two domains, or use the fully-qualified name to identify the server.
</blockquote>]]>
    </content>
</entry>

<entry>
    <title>From Ruby to Gherkin: Building Automated System Tests, pt 2</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2013/05/from-ruby-to-gherkin-building-an-automated-system-test-environment-pt-2.html" />
    <id>tag:www.safnet.com,2013:/writing/tech//3.505</id>

    <published>2013-05-29T16:55:29Z</published>
    <updated>2013-05-29T18:28:13Z</updated>

    <summary> Follow-up to Building a Test Script Environment with C# and IronRuby, pt 1, wherein we change emphasis from coding tests in Ruby to writing them in English (Gherkin) with the help of SpecFlow. After that October post, I managed...</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="testdrivendevelopment" label="test driven development" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="testing" label="testing" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<div style="float: right; margin: 0 0 10px 10px; height: 145px; width: 224px;  box-shadow: 1px 1px 3px 3px #ccc;">
<img alt="fromRubyToGherkin.jpg" src="http://www.safnet.com/writing/tech/images/fromRubyToGherkin.jpg" width="224" height="145" style="" />
</div>
<p><i>Follow-up to <a href="http://www.safnet.com/writing/tech/2012/10/building-a-test-script-environment-with-c-and-ironruby-pt-1.html">Building a Test Script Environment with C# and IronRuby, pt 1</a>, wherein we change emphasis from coding tests in Ruby to writing them in English (Gherkin) with the help of SpecFlow.</i></p>
<p>
After that October post, I managed to construct a full system/regression test suite for a key data-management application, using the combination of Ruby and C# as described. My team has been able to go through several cycles of&hellip;
</p>
]]>
        <![CDATA[<ul>
<li>Updating unit tests to reflect change requests,</li>
<li>Writing code to pass the tests, and</li>
<li>Getting <b>swift</b> regression test results back from the system test process acting on the fully-integrated code, and finally</li>
<li>Running a new test file that exercises the enhancement.</li>
</ul>
<p>
Oops, there is something amiss with that: the new test file should have been added to the system automation test suite at the outset, not at the end. That is, "test-first" should have applied at the system level, in addition to the unit level. But that's not the point of this article. The point is this: <b>at the end, I did not have a product that a business user could easily review and correct</b>.
</p>
<p>
Arguably, a non-programmer could read the code more easily, thanks to the use of Domain Specific Language concepts. Nevertheless, there was a lot of setup code that obscured intent, and the tests frankly <i>still looked daunting</i> to a non-programmer. Compounding the difficulty is the fact that the non-programmer users are still trying to understand the <i>fundamentals</i> of software testing, in plain English, and without the benefit of meaningful time to study. In other words, asking someone else to verify and maintain these tests would be throwing them into the deep end with inadequate support. The <a href="http://marcbless.blogspot.com/2011/05/agile-principle-12-inspect-and-adapt.html">inspect-and-adapt</a> mentality suggests modifying the system testing approach.
</p>
<div style="width: 170px; border-radius: 10px; background-color: #FBEF7A; float: right; margin: 0 0 10px 10px; padding: 7px; font-size: 1.2em; ">
<h3 style="margin:0;">Inspect-and-adapt:</h3>
<ol style="margin: 10px 0 0 0;">
<li>Tests are still too hard to read, and</li>
<li>The learning curve was too high,</li>
<li>Therefore find a simpler product.</li>
</ol>
</div>
<p><a href="https://github.com/cucumber/cucumber/wiki/Gherkin">Gherkin</a> to the rescue! The Gherkin language provides a very simple format for writing tests in plain English. A programmer then writes code that executes the intended actions, in the context of an automation system. Initially I continued on the Ruby path by trying to install RSpec as the interpreter, but I could not get it to install properly in IronRuby. Undismayed, I revised my goal: no longer would I seek to convert a tester into a Ruby programmer. Instead, I would encourage that tester to write and review English-language test scenarios in Gherkin, which the programming team would then support with code in C# using the <a href="http://www.specflow.org/specflownew/">SpecFlow</a> framework.
</p>
<p>At that point, we were working on a line-of-business application. Whereas learning the rudiments of Ruby, and setting up the code environment, had taken a good deal of effort, I was up-and-running with meaningful tests in SpecFlow within a day. More importantly, the other members of my team were immediately able to utilize and even correct small mistakes in these test scenarios. The learning curve was negligible when presented with a working example. And at long last, we were able to present a file containing test descriptions to a business analyst and get direct feedback.
</p>
<p>The IronRuby experiment was not a failure: it delivered a meaningful result. Empirically, however, it was a less-than-satisfying result. We evaluated, re-prioritized, and moved-on to the next iteration of our experimentation: SpecFlow. Now we feel that we have the foundation for real organizational growth around software testing.
</p>]]>
    </content>
</entry>

<entry>
    <title>Agile Introverts</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2013/05/agile-introverts.html" />
    <id>tag:www.safnet.com,2013:/writing/tech//3.504</id>

    <published>2013-05-20T02:48:15Z</published>
    <updated>2013-05-20T03:08:01Z</updated>

    <summary>A co-worker overheard the comment that &quot;agile [software development] is not always a good fit for introverts,&quot; or something along those lines, while listening to a webinar on agile testing. On the surface, it is hard to deny that claim....</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="agile" label="agile" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p>A co-worker overheard the comment that "agile [software development] is not always a good fit for introverts," or something along those lines, while listening to a webinar on agile testing. On the surface, it is hard to deny that claim. Right there in the <a href="http://agilemanifesto.org/">Agile Manifesto</a> we have two obvious yellow or even red flags:</p>
<ul>
<li>Individuals and interactions, and</li>
<li>Customer collaboration</li>
</ul>
<p>Now jumping over to the Principles, we find two more orange flags:
</p>
<ul>
<li>Business people and developers must work together daily throughout the project.</li>
<li>The most efficient and effective method of conveying information to and within a development team is face-to-face conversation.
</li>
</ul>
]]>
        <![CDATA[<p>
We find this drive for a close interaction in all of the agile methodologies, and that can scare some people. In <a href="http://www.extremeprogramming.org/rules.html">XP</a>, we even have pair programming: sitting not just near, but right alongside, another programmer.</p>
<p>But for the majority of introverts, I suspect that working in an agile environment will be no worse, and possibly better than, working in a waterfall setting or cowboy culture. Let's go back to the Manifesto and Principles, starting at the top: individuals and interactions <i>over processes and tools</i>. If you are a strong introvert, and your organization is dedicated to this Agile idea &mdash; and more importantly, dedicated to creating an environment where each employee will thrive &mdash; then the  management should adapt <i>process</i> in favor of <i>individual</i>, for example when evaluating adoption of pair programming. (On the other hand, an introvert might think carefully before accepting a job where pair programming is the rule).</p>
<p>And that leads me back to the Agile Principles, namely, "Build projects around motivated individuals. Give them the environment and support they need, and trust them to get the job done." That speaks for itself, doesn't it?</p>
<p>But what about those face-to-face conversations? In my own experience, most introverts are actually quite happy to have a face-to-face conversation with one or two other people. Perhaps this won't work "all the time" in the literal sense &ndash; but I'm guessing that the majority of extroverts don't want face-time, all-the-time, either.</p>
<p>Now, I straddle the divide. Many people never realize that I'm more intro- than extraverted, because I socialize easily when I need to. So perhaps I am not the best judge, and yet I will still step out and say: when faced with agile, introverts should set aside the fear and judge Agile from personal experience instead. After all, the world could use some more agile introverts.</p>
]]>
    </content>
</entry>

<entry>
    <title>Start Stop Continue Stickies</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2013/02/start-stop-continue-stickies.html" />
    <id>tag:www.safnet.com,2013:/writing/tech//3.496</id>

    <published>2013-02-27T02:42:23Z</published>
    <updated>2013-02-27T02:58:18Z</updated>

    <summary> Sometimes you need to go back to the basics - including basic technology. In this case, I mean sticky notes. Yes, they are a remarkable form of technology. I like doing everything the digital way. I abhor using paper...</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="agile" label="agile" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p>
Sometimes you need to go back to the basics - including basic technology. In this case, I mean sticky notes. Yes, they are a remarkable form of <i>technology</i>. I like doing everything the digital way. I abhor using paper when not necessary, because of the waste factor. Although I love the idea of note cards for user story development, I've been thankful that they are impractical for my development team. But, I think it is time to heed good advice.
</p>
<p style="text-align: center;">
<img alt="startStopContinueStickies.png" src="http://www.safnet.com/writing/tech/images/startStopContinueStickies.png" height="150" width="489" />
</p>]]>
        <![CDATA[<p>
For several months now I've been running bi-weekly retrospectives. Following good advice found many places (initially in <i>Integrating Agile Development in the Real World</i>), the retrospectives focus on:
</p>
<ul>
<li>listing&hellip;
<ul>
<li>things that are going well,</li>
<li>things that are not going well,</li>
<li>and opportunities for improvement;</li>
</ul>
</li>
<li>having a brief discussion on solutions for the 2nd and 3rd bullets;</li>
<li>prioritizing the list; and</li>
<li>assigning takeaways.</li>
</ul>
<p>Chapter 19 of <i>Agile Testing: A Practical Guide for Testers and Agile Team</i> refers to the listing practice in more simple terms: start, stop, and continue. And they provide this advice&hellip; 
</p>
<blockquote>
All team members write "start," "stop," and "continue" items on sticky notes, and then during the retrospective
meeting they put the stickies on the board and group them by topic. &hellip; It can be  hard to remember the past two weeks, much less an entire release, if that's what your retrospective covers. Research different creative approaches to reflecting on your team's experiences.
</blockquote>
<p>
How obvious and true! So let's hand out some color coded&#8824;, blank sticky notes in advance, just a small stack to everyone on the team. Ask them to fill out as things occur to them. When it comes time for the retrospective, bring all that still seem relevant. Better yet, put them on a piece of paper, slap that paper down on the copier/scanner, and create a digital version. We can quickly chop up the digital versions, arrange them in any one of various Office/type products, and  have a nice (and easy) picture instead of boring meeting notes.
</p>
<p>
It is my hope that this process will:
<ul>
<li>make it easier to remember start/stop/continue items in space in between meetings, </li>
<li>and re-emphasize  the importance of this collective feedback process.</li>
</ul>
<p>
This is nothing breathtaking or revolutionary on my part. If it works, it just means I needed to relax and rely on technology to help fix a problem &mdash; the simplest technology possible. Sticky notes. If it doesn't work out, hopefully someone will be kind of enough to write that down on a pink note and bring it to a future retrospective.
</p>
<p>
&#8824; pink = stop, yellow/or other = continue, green = start
</p>
]]>
    </content>
</entry>

<entry>
    <title>C# + IronRuby: Building Automated System Tests, pt 1</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/10/building-a-test-script-environment-with-c-and-ironruby-pt-1.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.488</id>

    <published>2012-10-11T03:16:06Z</published>
    <updated>2013-05-29T18:31:01Z</updated>

    <summary>We build a lot of console applications, and Windows services, that process inbound and outbound files in one way or another. Most depend on configuration data and some load (or unload) business data from a database, in addition to accessing...</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="testdrivendevelopment" label="test driven development" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="testing" label="testing" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p>We build a lot of console applications, and Windows services, that process inbound and outbound files in one way or another. Most depend on configuration data and some load (or unload) business data from a database, in addition to accessing the files. Testing these has always been a chore, to say the least: configurations change, data are deleted, and there's never enough time. After building a few rudimentary tools that have helped, necessity, and <a href="http://www.goodreads.com/book/show/5341009-agile-testing">Agile Testing: A Practical Guide for Testers and Agile Teams</a>, has convinced me that it is time to get serious about system/integration test automation, just as I did about unit test automation a few years ago. This is the first of a n-part series of posts on this process</p>]]>
        <![CDATA[<p>First, what is the rationale? What is this &quot;necessity&quot;, or rather <i>necessities</i>? Respecting proprietary business matters, let&rsquo;s say&hellip;</p>
<ol>
<li>There&rsquo;s never enough time partly because testing takes too much time.</li>
<li>The repetitive nature of manual testing makes it (a) boring, and (b) easy to mess up.</li>
<li>Because of both of these factors, I am loathe to delegate much testing to others. On the one hand I feel bad about pushing things on others just because I don&rsquo;t want to do them; on the other hand, I have trouble trusting results that I did not generate myself.</li>
<li>There is an active interest from others to be more involved in testing; bringing them in will free me up for more interesting projects, and, objectively speaking, provide a good check-and-balance.</li>
</ol>
<p>Automation can help with all of these factors, and more. Having come to that conclusion, what are the goals for this project?
<ul>
<li>Time is still hard-to-come by, so as with any agile project, build only what is needed right now and then start using it. This argues against a fancy UI for now, and in favor of simple test scripts.</li>
<li>Build components for auto-loading configuration and business data, as needed, into the database. These components should themselves be well-tested, and do not need to be created in the language used for the test scripts.</li>
<li>Provide a simple and familiar mechanism for saving that configuration data, e.g. csv via Excel.</li>
<li>These are &quot;business-facing&quot; tests, and they should be readable, with minimal training, by business users and non-programming testers. This argues for creation of a <a href="http://en.wikipedia.org/wiki/Domain-specific_language">domain-specific language</a>, use of a scripting language that that does not stand on ceremony, and possibly introduction of <a href="http://behaviour-driven.org/">Behavior Driven Development</a> (BDD) tools.</li>
<li>Maintain all scripts in source control.</li>
</ul>
<p>These goals rule out the normal .Net languages. A dynamic scripting language is more appropriate. From the many out there, Ruby seems to be the most obvious choice. With the help of <a href="www.ironruby.net/">IronRuby</a>, the data-access components can be written (and fully unit-tested) in C#, while scripts are written in Ruby. <a href="http://rspec.info/">RSpec</a> might eventually be used for BDD. Follow-up posts will dig into some of the implementation details, as well as the lessons learned along the way.</p>]]>
    </content>
</entry>

<entry>
    <title>Using Custom Types in Project Settings</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/09/using-custom-types-in-project-settings.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.484</id>

    <published>2012-09-07T01:57:04Z</published>
    <updated>2012-09-07T02:06:00Z</updated>

    <summary>Problem: using Application Settings in a .Net project, you find that there are so many entries that some organization is needed. Solution: create custom, serializable data types for logical groups of settings....</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="net" label=".Net" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="c" label="c#" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="xml" label="XML" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p><b>Problem:</b> using <a href="http://msdn.microsoft.com/en-us/library/k4s6c3a0.aspx">Application Settings</a> in a .Net project, you find that there are so many entries that some organization is needed.</p>
<p><b>Solution:</b> create custom, serializable data types for logical groups of settings.</p>
]]>
        <![CDATA[<h2>1. Custom Types</h2>
<p>Create one or more <acronym title="Plain Old C(sharp) Object">POCO</acronym> for logical groupings of your settings. Add the <code>[Serializable]</code> attribute from the <code>System.Xml</code> namespace because the object data need to be stored as XML in the settings file. It may be convenient to put a few other properties or methods into the class, returning calculated values based on the settings &ndash; for example, to parse a <code>TimeSpan</code> from a string in the settings. For those, you can add the <code>[XmlIgnore]</code> attribute from the <code>System.Xml.Serialization</code> namespace.</p>
<h2>2. Create XML for Your Type</h2>
<p>In step 4 you'll need the serialized XML string, with default values, for your custom type(s). Two ways of getting this: write a few lines of code to take care of it for you, or you could always construct it manually using the XML below as a template. Let's use this type to work the example:</p>
<pre class="brush: csharp">
public class MySettingsType
{
    public string SettingString { get; set; }
    public int SettingInt { get; set; }
    public string[] SettingStringArray { get; set; }
}
</pre>
<p>Now, to write a few lines of code&hellip; I put this into a unit test class so that I could easily execute it from within Visual Studio. </p>
<pre class="brush: csharp">
using System.Xml.Serialization;
using System.IO;

...

[TestMethod]
public void WriteSettingsXml()
{
	var settings = new MySettingsType
	{
		SettingInt = 4345,
		SettingBool = true,
		SettingStringArray = new string[] { "a", "b"}
	};

	var serializer = new XmlSerializer(typeof(MySettingsType));
	using (var writer = new StreamWriter(@"c:\temp\settings.xml"))
	{
		serializer.Serialize(writer, settings);
	}
}
</pre>
<p>And with this example in hand, it should be easy enough to write build your XML by hand:</p>
<pre class="brush: xml">
&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;MySettingsType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt;
  &lt;SettingBool&gt;true&lt;/SettingBool&gt;
  &lt;SettingInt&gt;4345&lt;/SettingInt&gt;
  &lt;SettingStringArray&gt;
    &lt;string&gt;a&lt;/string&gt;
    &lt;string&gt;b&lt;/string&gt;
  &lt;/SettingStringArray&gt;
&lt;/MySettingsType&gt;
</pre>
<h2>3. Open the Settings File</h2>
<p>In Visual Studio, open the Settings File. Add a new Setting entry with an appropriate name for the collection of fields in your type. For Type, select Browse. This will open a dialog box <i>and you might not find your custom type in the list</i> (I&#39;ve seen the behavior go both ways, and not exactly sure why). If you don&#39;t see it, just type the namespace and class name into the textbox and click OK. Choose the scope you want. Finally, copy your XML and paste it into the Value field &ndash; the whole thing, starting with the XML version. Compile. Now your new property will be available in <code>Properties.Settings.Default</code>.</p>
<h2>End result</h2>
<p>Imagine this with several custom types, providing organization to the project. Now imagine this in a class library that is used by several applications &mdash; if you want the defaults, just leave out a whole class worth of values.</p>
<pre class="brush: csharp">
&lt;applicationSettings&gt;
	&lt;MyApp.Properties.Settings&gt;
		&lt;setting name=&quot;Setting&quot; serializeAs=&quot;String&quot;&gt;
			&lt;value&gt;mySampleValue&lt;/value&gt;
		&lt;/setting&gt;
		&lt;setting name=&quot;Setting1&quot; serializeAs=&quot;String&quot;&gt;
			&lt;value&gt;AnotherValue&lt;/value&gt;
		&lt;/setting&gt;
		&lt;setting name=&quot;Setting2&quot; serializeAs=&quot;Xml&quot;&gt;
			&lt;value&gt;
				&lt;MySettingsType xmlns:xsi=&quot;http://www.w3.org/2001/XMLSchema-instance&quot;
					xmlns:xsd=&quot;http://www.w3.org/2001/XMLSchema&quot;&gt;
					&lt;SettingBool&gt;true&lt;/SettingBool&gt;
					&lt;SettingInt&gt;4345&lt;/SettingInt&gt;
					&lt;SettingStringArray&gt;
						&lt;string&gt;a&lt;/string&gt;
						&lt;string&gt;b&lt;/string&gt;
					&lt;/SettingStringArray&gt;
				&lt;/MySettingsType&gt;
			&lt;/value&gt;
		&lt;/setting&gt;
	&lt;/MyApp.Properties.Settings&gt;
&lt;/applicationSettings&gt;
</pre>]]>
    </content>
</entry>

<entry>
    <title>Manipulating Table Rows with jQuery</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/07/manipulating-table-rows-with-jquery.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.481</id>

    <published>2012-07-12T02:48:13Z</published>
    <updated>2012-07-23T01:54:19Z</updated>

    <summary>Problem: need to move rows up and down, and from one table to another, in an HTML page. Solution: careful use of jQuery. There are probably many different solutions already out there, but I wanted to learn how to write...</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="html" label="HTML" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="jquery" label="jQuery" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p><b>Problem:</b> need to move rows up and down, and from one table to another, in an HTML page.</p>
<p><b>Solution:</b> careful use of jQuery. There are probably many different solutions already out there, but I wanted to learn how to write one for myself. Key functions: <a href="http://api.jquery.com/closest/">closest</a>, <a href="http://api.jquery.com/detach/">detach</a>, <a href="http://api.jquery.com/append/">append</a>, <a href="http://api.jquery.com/prev/">prev</a>, <a href="http://api.jquery.com/next/">next</a>, <a href="http://api.jquery.com/before/">before</a>, and <a href="http://api.jquery.com/after/">after</a>.
</p>]]>
        <![CDATA[<h2>Demonstration</h2>
	<table id="table1" style="background-color: Lime" class="displayTable">
        <caption>Table 1</caption>
        <thead>
            <tr>
                <th>One</th>
                <th>Two</th>
                <th>Three</th>
            </tr>
        </thead>
        <tbody>
            <tr id="row1">
                <td>R1 C1</td>
                <td>R1 C2</td>
                <td>
                    <a href="#" id="row1Link" class="rowLink">Move Me</a> |
                    <a href="#" id="row1Up" class="rowUp">Up</a> | 
                    <a href="#" id="row1Down" class="rowDown">Down</a>
                </td>
            </tr>
            <tr id="row2">
                <td>R2 C1</td>
                <td>R2 C2</td>
                <td>
                    <a href="#" id="row2Link" class="rowLink">Move Me</a> |
                    <a href="#" id="row2Up" class="rowUp">Up</a> | 
                    <a href="#" id="row2Down" class="rowDown">Down</a>
                </td>
            </tr>
            <tr id="row3">
                <td>R3 C1</td>
                <td>R3 C2</td>
                <td>
                    <a href="#" id="row3Link" class="rowLink">Move Me</a> |
                    <a href="#" id="row3Up" class="rowUp">Up</a> | 
                    <a href="#" id="row3Down" class="rowDown">Down</a>
                </td>
            </tr>
        </tbody>
    </table>
    <table id="table2" style="background-color: Yellow; margin-top: 30px;" class="displayTable">
        <caption>Table 2</caption>
        <thead>
            <tr>
                <th>One</th>
                <th>Two</th>
                <th>Three</th>
            </tr>
        </thead>
        <tbody>
        </tbody>
    </table>
<h2>Table Source Code</h2>
<p>A couple of very basic tables, with "action" links in the third column. Judicious use of id and class attributes will turn out to be very helpful&hellip;</p>
<pre class="brush: html">
&lt;table id="table1" style="background-color: Lime" class="displayTable"&gt;
      &lt;caption&gt;Table 1&lt;/caption&gt;
      &lt;thead&gt;
          &lt;tr&gt;
              &lt;th&gt;One&lt;/th&gt;
              &lt;th&gt;Two&lt;/th&gt;
              &lt;th&gt;Three&lt;/th&gt;
          &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody&gt;
          &lt;tr id="row1"&gt;
              &lt;td&gt;R1 C1&lt;/td&gt;
              &lt;td&gt;R1 C2&lt;/td&gt;
              &lt;td&gt;
                  &lt;a href="#" id="row1Link" class="rowLink"&gt;Move Me&lt;/a&gt; |
                  &lt;a href="#" id="row1Up" class="rowUp"&gt;Up&lt;/a&gt; | 
                  &lt;a href="#" id="row1Down" class="rowDown"&gt;Down&lt;/a&gt;
              &lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr id="row2"&gt;
              &lt;td&gt;R2 C1&lt;/td&gt;
              &lt;td&gt;R2 C2&lt;/td&gt;
              &lt;td&gt;
                  &lt;a href="#" id="row2Link" class="rowLink"&gt;Move Me&lt;/a&gt; |
                  &lt;a href="#" id="row2Up" class="rowUp"&gt;Up&lt;/a&gt; | 
                  &lt;a href="#" id="row2Down" class="rowDown"&gt;Down&lt;/a&gt;
              &lt;/td&gt;
          &lt;/tr&gt;
          &lt;tr id="row3"&gt;
              &lt;td&gt;R3 C1&lt;/td&gt;
              &lt;td&gt;R3 C2&lt;/td&gt;
              &lt;td&gt;
                  &lt;a href="#" id="row3Link" class="rowLink"&gt;Move Me&lt;/a&gt; |
                  &lt;a href="#" id="row3Up" class="rowUp"&gt;Up&lt;/a&gt; | 
                  &lt;a href="#" id="row3Down" class="rowDown"&gt;Down&lt;/a&gt;
              &lt;/td&gt;
          &lt;/tr&gt;
      &lt;/tbody&gt;
  &lt;/table&gt;
  &lt;table id="table2" style="background-color: Yellow; margin-top: 30px;" class="displayTable"&gt;
      &lt;caption&gt;Table 2&lt;/caption&gt;
      &lt;thead&gt;
          &lt;tr&gt;
              &lt;th&gt;One&lt;/th&gt;
              &lt;th&gt;Two&lt;/th&gt;
              &lt;th&gt;Three&lt;/th&gt;
          &lt;/tr&gt;
      &lt;/thead&gt;
      &lt;tbody&gt;
      &lt;/tbody&gt;
  &lt;/table&gt;
</pre>
<h2>Between Tables</h2>
<p>One principle is that I don't want to hard-code all of the ID values. But that didn't work out entirely. Write a function and apply it to the click event of all of the elements with class "rowLink". In that function, find the parent row. Then find that row's parent table. Remove the row from the display &ndash; but use <code>detach</code> instead of <code>remove</code> so that the HTML still exists. See if that table is table1. There's the hard coding. If so, append the row into table2. Then it seems nice to help the reader notice that the row has moved.</p>
<pre class="brush: javascript">
// Setup the "Move Me" links
$(".rowLink").click(function () {
    // get the row containing this link 
    var row = $(this).closest("tr");

    // find out in which table it resides
    var table = $(this).closest("table");

    // move it
    row.detach();

    if (table.is("#table1")) {
        $("#table2").append(row);
    }
    else {
        $("#table1").append(row);
    }

    // draw the user's attention to it
    row.fadeOut();
    row.fadeIn();
});
</pre>
<h2>Up and Down</h2>
<p>Now apply a function to the click event of all the elements with class "rowUp." Again get the current row. Then get the previous element. If the previous element is itself a row, then there is room to move up &ndash; so <code>detach</code> the row and move it before the previous row. Otherwise do nothing. For moving down, simply switch from <code>prev</code> to <code>next</code> and <code>before</code> to <code>after</code>.</p>
	<pre class="brush: javascript">
// Setup the "Up" links
$(".rowUp").click(function () {
    var row = $(this).closest("tr");

    // Get the previous element in the DOM
    var previous = row.prev();

    // Check to see if it is a row
    if (previous.is("tr")) {
        // Move row above previous
        row.detach();
        previous.before(row);

        // draw the user's attention to it
        row.fadeOut();
        row.fadeIn();
    }
    // else - already at the top
});
	</pre>
		    <script type="text/javascript">
        $(document).ready(function () {
            // Setup the "Move Me" links
            $(".rowLink").click(function () {
                // get the row containing this link 
                var row = $(this).closest("tr");

                // find out in which table it resides
                var table = $(this).closest("table");

                // move it
                row.detach();

                if (table.is("#table1")) {
                    $("#table2").append(row);
                }
                else {
                    $("#table1").append(row);
                }

                // draw the user's attention to it
                row.fadeOut();
                row.fadeIn();
            });

            // Setup the "Up" links
            $(".rowUp").click(function () {
                var row = $(this).closest("tr");

                // Get the previous element in the DOM
                var previous = row.prev();

                // Check to see if it is a row
                if (previous.is("tr")) {
                    // Move row above previous
                    row.detach();
                    previous.before(row);

                    // draw the user's attention to it
                    row.fadeOut();
                    row.fadeIn();
                }
                // else - already at the top
            });

            // Setup the "Up" links
            $(".rowDown").click(function () {
                var row = $(this).closest("tr");

                // Get the previous element in the DOM
                var next = row.next();

                // Check to see if it is a row
                if (next.is("tr")) {
                    // Move row above previous
                    row.detach();
                    next.after(row);

                    // draw the user's attention to it
                    row.fadeOut();
                    row.fadeIn();
                }
                // else - already at the bottom
            });
        });

    </script>]]>
    </content>
</entry>

<entry>
    <title>Some Tips for Use of DataAnnotations in .Net</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/06/some-tips-for-use-of-dataannotations-in-net.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.479</id>

    <published>2012-06-28T01:14:22Z</published>
    <updated>2012-06-28T01:18:37Z</updated>

    <summary><![CDATA[Wherein I record a few tips on the use of System.ComponentModel.DataAnnotations, which I am likely to forget if I do not need to think about them again for some months&hellip;...]]></summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="c" label="C#" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="mvc" label="MVC" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p>Wherein I record a few tips on the use of <a href="http://rachelappel.com/asp-net-mvc/how-data-annotations-for-asp-net-mvc-validation-work/">System.ComponentModel.DataAnnotations</a>, which I am likely to forget if I do not need to think about them again for some months&hellip;</p>
<p>
<img src="http://i.msdn.microsoft.com/dynimg/IC310561.png" style="height: 258px; width: 476px;" alt="[validator screenshot from MSDN]" /></p>]]>
        <![CDATA[
<h2>Unit Testing for Validation Attributes</h2>
<p>
In your unit tests, do not test the validation &ndash; but rather test to see if the validation attributes have been applied. See Brad Wilson's blog post, <a href="http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html">DataAnnotations and ASP.NET MVC</a>, for details.
</p>
<h2>Manual Validation</h2>
<p>If you do manually validate, in a unit test or production code, using <code>Validator.TryValidateObject</code> (or other methods in the Validator class), then be sure to set the <code>validateAllProperties = true</code>. By default it is false and that means that only <code>Required</code> properties will be validated. &lt;editorial&gt;Why in the world is this false by default? The obvious and expected behavior is that all properties would be validated&lt;/editorial&gt;. <code>Validator.TryValidateObject(someObject, new ValidationContext(someObject, null, null), resultList, <span style="background: yellow">true</span>)</code>.</p>

<h2>Validating Related Objects</h2>
<p>
Validating inherited fields works nicely. But what about composition / delegation? If you are validating object A, and it is composed of objects B and C that are also validated, then you need some "deep" validation. There is a simple recipe for accomplishing this:
</p>
<ol>
<li>Implement <code>IValidatableObject</code> on class A, which will require you to add a method with signature <code>public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)</code>.
</li>
<li>
Set this method to run <code>TryValidateObject</code> on the instance of B and of C. Each call to <code>TryValidateObject</code> will need its own <code>ValidationContext</code>. Constructing a <code>ValidationContext</code> is simple &ndash; just pass in the object itself, and generally it is appropriate to pass null for the second and third parameter. Don't forget to throw in a <code>true</code> for validating all properties! Something like this will work (with opportunity for multiple refactorings):
<br />
<pre class="brush: csharp">
public IEnumerable&lt;ValidationResult&gt; Validate(ValidationContext validationContext)
{
    var resultList = new List&lt;ValidationResult&gt;();

    Validator.TryValidateObject(this.InstanceOfB, new ValidationContext(this.InstanceOfB, null, null), resultList, true);
    Validator.TryValidateObject(this.InstanceOfC, new ValidationContext(this.InstanceOfC, null, null), resultList, true);

    return resultList;
}
</pre>
<br />
Now, you wrote a failing unit test for this Validate method before coding it, right?
</li>
</ol>
<p>
Caution: if any of the properties directly in A are invalid, then those will be detected and <code>Validate(ValidationContext validationContext)</code> will never be called.
</p>
<h2>Validation Summary in an MVC Partial View</h2>
<p>When using partial views for AJAX support in an MVC application, a <code> @Html.ValidationSummary()</code> should be put inside the partial view. If you put it inside the hosting view, then it will not be populated when you submit a form inside the partial view.</p>]]>
    </content>
</entry>

<entry>
    <title>Review: Growing Object-Oriented Software, Guided By Tests</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/05/review-growing-object-oriented-software-guided-by-tests.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.473</id>

    <published>2012-05-13T02:50:18Z</published>
    <updated>2012-05-13T03:05:02Z</updated>

    <summary> Growing Object-Oriented Software, Guided by Tests by Steve Freeman and Nat Pryce I did not realize how much I still have to learn about writing good object-oriented (OO) code, and about hewing to a tight test driven development (TDD)...</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="oo" label="OO" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="review" label="review" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="testdrivendevelopment" label="test driven development" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p style="float: left; padding-right: 20px; width: 120px; font-size: .85em">
<a href="http://www.goodreads.com/book/show/4268826-growing-object-oriented-software-guided-by-tests"><img alt="Growing Object-Oriented Software, Guided by Tests" border="0" src="http://photo.goodreads.com/books/1266624968m/4268826.jpg" /></a><a href="http://www.goodreads.com/book/show/4268826-growing-object-oriented-software-guided-by-tests">Growing Object-Oriented Software, Guided by Tests</a> by <a href="http://www.goodreads.com/author/show/27264.Steve_Freeman">Steve Freeman and Nat Pryce</a></p>
<p>I did not realize how much I still have to learn about writing good object-oriented  (OO) code, and about hewing to a tight test driven development (TDD) methodology, before I read <i>Growing Object-Oriented Software, Guided By Tests</i>. My education in OO and unit testing has been largely theoretical, with no time spent directly learning from experienced OO programmers; my best mentor was a COBOL coder. Books like  <a href="http://www.goodreads.com/book/show/85009.Design_Patterns__Elements_of_Reusable_Object_Oriented_Software" title="Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma">Design Patterns: Elements of Reusable Object-Oriented Software</a>, <a href="http://www.goodreads.com/book/show/70156.Patterns_of_Enterprise_Application_Architecture" title="Patterns of Enterprise Application Architecture by Martin Fowler">Patterns of Enterprise Application Architecture</a>, <a href="http://www.goodreads.com/book/show/85019.Applying_UML_and_Patterns__An_Introduction_to_Object_Oriented_Analysis_and_Design_and_Iterative_Development" title="Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development by Craig Larman">Applying UML and Patterns: An Introduction to Object-Oriented Analysis and Design and Iterative Development</a>, <a href="http://www.goodreads.com/book/show/337302.Xunit_Test_Patterns__Refactoring_Test_Code" title="Xunit Test Patterns: Refactoring Test Code by Gerard Meszaros">Xunit Test Patterns: Refactoring Test Code</a>, and others are wonderful but have few detailed real-world business-case examples.</p>]]>
        <![CDATA[<p>That said, I admit that I skimmed through some of the middle chapters where the application was being built &ndash; it was simple to skip the details of Java implementation and focus on the points where a decision was being made, based on tests, about where to put/move a piece code. The authors did well in steering away from anything too Java-centric, that the book would remain accessible to those of us who are not deep in that language.</p>
<p>There is no need for me to recount the contents &ndash; perusal of the <a href="http://my.safaribooksonline.com/book/software-engineering-and-development/software-testing/9780321574442?bookview=toc">table of contents</a> should be sufficient. Some of the advice about testing overlaps that found in <i>XUnit Test Patterns</i>, but the overlaps is small enough to warrant reading both. Naturally, some of the advice will reinforce what any good and self-reflective programmer will have already figured out about writing tests. In that case you receive validation and further justification. And much of the advice on OO programming can be found in more detail in other works, though here it is uniquely combined with TDD to shed new light on the advantages of OO.</p>
<p>A few particular highlights for me:</p>
<ul>
<li>Let necessity drive design, rather week-long UML sessions.</li>
<li>Write to interfaces, initially ignoring implementation. Interfaces should name and describe relationships between classes.</li>
<li>Deploy as early as possible. Do so even before the application does anything, just to prove that the framework <i>can be</i> deployed.</li>
<li>Readability applies to test code as well. I already believed that, but this presentation will help me explain that better to doubters.</li>
<li>Test names can be <a href="http://www.safnet.com/writing/tech/2012/03/test-naming-convention.html">extremely descriptive</a> (prior post)</li>
<li><a href="http://www.safnet.com/writing/tech/2012/04/moles-no-longer-fit-for-unit-tests.html">I have been over-reliant</a> on Microsoft's Moles (prior post)</li>
</ul>
]]>
    </content>
</entry>

<entry>
    <title>Breaking Down a Unit Test from &quot;Reggie&quot; That Uses MoQ</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/04/breaking-down-a-unit-test-from-reggie-that-uses-moq.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.472</id>

    <published>2012-04-21T22:14:03Z</published>
    <updated>2012-04-21T22:24:57Z</updated>

    <summary> Test driven development is hard. Perhaps it would not be if we were taught to think about OO development from a TDD perspective in the first place; but those muscles are poorly developed, and the exercise leaves you sore...</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="moq" label="MoQ" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="reggie" label="Reggie" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="testdrivendevelopment" label="test driven development" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="unittest" label="unit test" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p>
Test driven development is hard. Perhaps it would not be if we were taught to think about OO development from a TDD perspective in the first place; but those muscles are poorly developed, and the exercise leaves you sore and panting a bit. As with physical exercise, there is a reward in the pain. Perhaps others do not see it, but I can already see the benefits accruing in <a href="http://reggie.codeplex.com">Reggie</a> as I rebuild it with <a href="en.wikipedia.org/wiki/SOLID_(object-oriented_design)">SOLID</a> principles in mind, driven by tests. To help me consolidate where I&rsquo;m going, and help others whose TDD muscles are likewise under-developed, let us walk through a test, shall we?
</p>]]>
        <![CDATA[
<p>First, some context. I&rsquo;m working on adding persistence to the application: ability to save and re-open session data. I have a <a href="http://en.wikipedia.org/wiki/Model_View_ViewModel">ViewModel</a>, called <code>ReggieBasicViewModel</code>, which initially contains the data to persist and which binds the View to my business logic. The ViewModel is being instantiated with a factory object, which allows the ViewModel to build concrete instances of various dependencies. This illustrates the <a href="http://www.oodesign.com/abstract-factory-pattern.html">Abstract Factory</a> pattern, and the <a href="http://msdn.microsoft.com/en-us/magazine/cc546578.aspx">Open-Closed Principle</a>, but arguably violates Single Responsibility Principle [same link as OCP] by grouping un-related functionality into the factory. The proper factory object is configured in the application&rsquo;s bootstrapper class, or <i>or it is setup in a unit test using an alternate factory implementation</i>.
</p>
<p style="text-align: center">
<img src="http://www.safnet.com/writing/tech/images/diggingIntoTests1.png" style="border: 1px solid gray; width: 470px; height: 375px; text-align: center" alt="[Class Diagrams 1]" />
</p>
<p>
<img src="http://www.safnet.com/writing/tech/images/diggingIntoTests2.png" style="border: 1px solid gray; width: 160px;height: 139px;float: right; margin: 20px 0 0 20px" alt="[Class Diagrams 2]" />
I&rsquo;d like to save to / retrieve from an XML file. But what if my requirements change in a few days? I&rsquo;m told to save to a database, or a web service. It would not be wise to design for that &ndash; but I can easily make the system flexible enough to handle addition of other types of <i>persistence</i> in the future. So I create an interface in my business layer, called <code>ISessionPersistence</code>. As you can see, I&rsquo;ve added a factory method to the IHelperFactory, for building an instance of <code>ISessionPersistence</code>.</p>
<p>The method <code>SaveSession</code> in <code>ReggieBasicViewModel</code>  does not yet have a body. It will need to execute the Save method in the persistence layer. First things first: a unit test.</p>
<pre class="brush: csharp">
[TestMethod]
public void SaveSessionLoadsSessionIntoPersistenceService()
{
    // Prepare Input</body>
    string sampleText = "Reggie";</html>
    string regularExpressionPattern = "^(Reggie)$";

    // Setup mocks
    Mock<IReggieSession> mockSession = m_mockFactory.Create&lt;IReggieSession&gt;();
    mockSession.SetupSet(ms => ms.RegularExpressionPattern = It.Is&lt;string&gt;(x => x == regularExpressionPattern));
    mockSession.SetupGet(ms => ms.RegularExpressionPattern).Returns(regularExpressionPattern);
    mockSession.SetupSet(ms => ms.SampleText = It.Is&lt;string&gt;(x => x == sampleText));
    mockSession.SetupGet(ms => ms.SampleText).Returns(sampleText);

    m_helperFactory.Setup(hf => hf.BuildReggieSession())
                   .Returns(mockSession.Object);

    m_persistence.Setup(p => p.Save(It.Is&lt;IReggieSession&gt;(x => x.SampleText == sampleText 
                                                            && x.RegularExpressionPattern == regularExpressionPattern)));

    // Call the system under test
    m_systemUnderTest.SampleText = sampleText;
    m_systemUnderTest.RegularExpressionPattern = regularExpressionPattern;
    m_systemUnderTest.SaveSession();

    // Evaluate results
    m_persistence.Verify(p => p.Save(It.IsAny&lt;IReggieSession&gt;()), Times.Once());
}
</pre>
<p>Let&rsquo;s step through that&hellip;</p>
<pre class="brush: csharp">
    // Setup mocks
    Mock&lt;IReggieSession&gt; mockSession = m_mockFactory.Create&lt;IReggieSession&gt;();
</pre>
<p>Use MoQ to create a mockup of an <code>IReggieSession</code>. I forgot to mention this: it is a small interface for holding the Sample Text and Regular Expression Pattern that will be saved.
</p>
<p style="text-align: center">
<img src="http://www.safnet.com/writing/tech/images/diggingIntoTests3.png" style="border: 1px solid gray; width: 207px; height: 137px;" alt="[Class Diagrams 3"] style="" />
</p>
<pre class="brush: csharp" style="clear: both;">
    mockSession.SetupSet(ms => ms.RegularExpressionPattern = It.Is&lt;string&gt;(x => x == regularExpressionPattern));
    mockSession.SetupGet(ms => ms.RegularExpressionPattern).Returns(regularExpressionPattern);
    mockSession.SetupSet(ms => ms.SampleText = It.Is&lt;string&gt;(x => x == sampleText));
    mockSession.SetupGet(ms => ms.SampleText).Returns(sampleText);
</pre>
<p>
Now add some meat to that mock object by setting up the Get and Set for the two properties, <code>RegularExpressionPattern</code> and <code>SampleText</code>:
</p>
<ul>
<li>The <code>SetupSet</code> line can be read this way: <code>RegularExpressionPattern_Set</code> is allowed to be called with a value matching the <code>regularExpressionPattern</code> variable.</li>
<li>The <code>SetupGet</code> can can be read as saying: <code>RegularExpressionPattern_Get</code> will return the value of <code>regularExpressionPattern</code>.</li>
<li>Etc.</li>
</ul>
</p>
<pre class="brush: csharp">
    m_helperFactory.Setup(hf => hf.BuildReggieSession())
                   .Returns(mockSession.Object);
</pre>
<p>When the factory&rsquo;s <code>BuildReggieSession</code> method is called, return the mock Session object.</p>
<pre class="brush: csharp">
    m_persistence.Setup(p => p.Save(It.Is&lt;IReggieSession&gt;(x => x.SampleText == sampleText 
											&& x.RegularExpressionPattern == regularExpressionPattern)));
</pre>
<p>Create a mock persistence engine &ndash; <em>this helps us remember that the method we&rsquo;re implementing does not care how the session is persisted!</em> It will simply use whatever method is configured in the factory, which in turn was configured by the main application&rsquo;s bootstrapper class and passed into the ViewModel&rsquo;s constructor. FYI, the factory and persistence mocks were instantiated with Strict behavior in the test fixture&rsquo;s TestInitialize method, so these are member variables for the class and the test will fail if any method is called that has not be explicitly setup. Read this line thusly: setup the persistence mock so that the Save command is allowed to be called with a <code>IReggieSession</code> whose <code>SampleText</code> has the value of <code>sampleText</code> and <code>RegularExpressionPattern</code> has the value of <code>regularExpressionPattern</code>.</p>
<pre class="brush: csharp">
    // Call the system under test
    m_systemUnderTest.SampleText = sampleText;
    m_systemUnderTest.RegularExpressionPattern = regularExpressionPattern;
    m_systemUnderTest.SaveSession();
</pre>
<p>This is clear enough. The system under test is an instance of <code>ReggieViewModel</code>, that was constructed in the <code>TestInitialize</code> method. Normally I would put the construction directly in the test, but in this test fixture, all of the tests need to be initialized in the same way. Moving that to <code>TestInitialize</code> reduces redundant code.</p>
<pre class="brush: csharp">
    // Evaluate results
    m_persistence.Verify(p => p.Save(It.IsAny&lt;IReggieSession&gt;()), Times.Once());
}
</pre>
<p>This line verifies that the Save method was called exactly one time, with any <code>IReggieSession</code> object. The exact object values do not matter, because I already configured the test to accept the particular values in the local variables.</p>
<p>Run the test. It fails. Great! Fill in the method body. It does not matter that I do not have a concrete version of <code>ISessionPersistence</code> yet, since I am programming against the interface. Now the test passes! The next step is clear: write a test for a concrete persistence class that saves sessions to XML. This will, by definition, be an integration test, writing an actual file. That is, unless I add another layer of abstraction: wrap the XML serialize/deserialize in a reusable custom class, and call that custom class from the persistence class.</p>
<pre class="brush: csharp">
 /// <summary>
 /// Save the current input values for future use.
 /// </summary>
 public void SaveSession()
 {
     var session = m_helperFactory.BuildReggieSession();
     session.SampleText = this.SampleText;
     session.RegularExpressionPattern = this.RegularExpressionPattern;

     m_persistence.Save(session);
 }
 </pre>]]>
    </content>
</entry>

<entry>
    <title>Moles: No Longer Fit for Unit Tests</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/04/moles-no-longer-fit-for-unit-tests.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.470</id>

    <published>2012-04-19T15:21:11Z</published>
    <updated>2012-04-19T15:57:25Z</updated>

    <summary>Moles is a powerful and useful framework for unit testing. Or was. But even then, it was overused (at least by me). But no more!...</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="moles" label="Moles" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="unittest" label="unit test" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<img alt="noMoles.png" src="http://www.safnet.com/writing/tech/images/noMoles.png" width="195" height="100" class="mt-image-right" style="float: right; margin: 0 0 20px 20px;" /><p>Moles is a powerful and useful framework for unit testing. Or
was. But even then, it was overused (at least by me). But no
more!</p>]]>
        <![CDATA[<p>The first clue that I might need to walk away from Moles was the
recent difficulty another developer was having in trying to get a
unit test project up-and-running on his computer. I had installed
what was current in early 2011, and he had installed the current
version from last 2011. Turns out there was a significant change
&ndash; the config file no longer worked. We had to update the
assemblies correctly on my machine, rebuild many times, and fool
around with manually removing some assemblies. It got confusing and
messy. I suppose that's why MS still labeled this version as
&lt; 1.0.</p>
<p>Next: <i>Growing Object-Oriented Software, Guided by Tests</i>
showed me how I was letting <i>design</i> guide <i>tests</i> far
too much &ndash; and here I thought I was practicing test driven
development (TDD) just by writing unit tests. No. Moles was a
symptom of this &ndash; the framework is used to replace a concrete
method in a dependent class. Well, in good TDD, the dependent class
shouldn't exist yet. There should not be a concrete method to
replace.</p>
<blockquote>
&quot;There&lsquo;s a more subtle but powerful reason for not mocking concrete classes. When we extract an interface as part of our test-driven development process, we have to think up a name to describe the relationship we've just discovered--in this example, the ScheduledDevice. We find that this makes us think harder about the domain and teases out concepts that we might otherwise miss. Once something has a name, we can talk about it.&quot; (from Ch 20, unknown page)
</blockquote>
<p>Next: Microsoft's own documentation tells me that I'm doing it
wrong, and that I would experience "significant performance
degradation" from use of Moles. I should have been doing more with
Stubs. From the <i>Microsoft Moles Reference Manual" (v0.91,
p4):</i></p>
<blockquote><i>"In general, we recommend that you use stub types to
isolate from dependencies. This can be achieved by hiding the
components behind interfaces. Mole types can be used to isolate
from third-party components that do not provide a testable
API."</i></blockquote>
<p>Finally: Microsoft <a href="http://research.microsoft.com/en-us/projects/moles/">has announced</a> the end-of-the-line
for Moles. In Visual Studio, the framework <a href="http://www.peterprovost.org/blog/2012/04/15/visual-studio-11-fakes-part-1/">will be replaced</a> with
one called Fakes.</p>]]>
    </content>
</entry>

<entry>
    <title>Reggie Converted to Use Caliburn Micro, Ninject</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/04/reggie-converted-to-use-caliburn-micro-ninject.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.469</id>

    <published>2012-04-18T02:18:02Z</published>
    <updated>2012-04-18T02:25:37Z</updated>

    <summary>Reggie, my regular expression testing application, has been rebuilt in the Caliburn Micro framework, using Ninject for Inversion of Control and MoQ to round out the unit tests. Now that I&apos;ve learned something about WPF, and that &quot;out of the...</summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="reggie" label="Reggie" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p><a href="http://reggie.codeplex.com/">Reggie</a>, my regular expression testing application, has been rebuilt in the <a href="http://caliburnmicro.codeplex.com/">Caliburn Micro</a> framework, using <a href="http://www.ninject.org/">Ninject</a> for Inversion of Control and <a href="http://code.google.com/p/moq/">MoQ </a>to round out the unit tests. </p>
<p>Now that I've learned something about WPF, and that "out of the box" it is not entirely trivial to work with, it seemed worthwhile to rebuild the app using a standard framework, viz Caliburn Micro. The Mindscape Blog offers a <a href="http://www.mindscapehq.com/blog/index.php/category/wpf/">friendlier CM tutorial</a> than the one on the project's website. </p>
<p>In addition, I simplified the architecture by removing the separate business layer. The business logic is so light that it is not worth the effort (20 
lines!). I will refactor if doing so provides a real benefit.</p>
<img src="http://i3.codeplex.com/Download?ProjectName=reggie&DownloadId=369250" style="width: 387px; height: 357px;" alt="[Reggie v0.2]" />]]>
        
    </content>
</entry>

<entry>
    <title>Breaking My Moles Habit, With MoQ</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/04/breaking-my-moles-habit-with-moq.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.468</id>

    <published>2012-04-16T13:43:37Z</published>
    <updated>2012-04-16T13:49:38Z</updated>

    <summary><![CDATA[For several years now, I have been relying on Microsoft&rsquo;s Moles for isolating one method from another in my unit tests. Recently I&rsquo;ve begun to understand that this was not the best approach. I&rsquo;ll dig into that more in a...]]></summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="moles" label="Moles" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="moq" label="MoQ" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="unittest" label="unit test" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<img alt="Mockery" src="http://www.safnet.com/writing/tech/images/johnny_automatic_jester.png" width="102" height="150" class="mt-image-right" style="float: right; margin: 0 0 20px 20px;" /><p>For several years now, I have been relying on Microsoft&rsquo;s <a href="http://research.microsoft.com/en-us/projects/moles/">Moles</a> for isolating one method from another in my unit tests. Recently I&rsquo;ve begun to understand that this was not the best approach. I&rsquo;ll dig into that more in a future post. Having come to this conclusion, I need to start ripping out Moles. Based on the user feedback across the web, and the powerful Lambda expression syntax I&rsquo;ve grown used to, I&rsquo;ve chosen MoQ as my replacement. Now for an exercise&hellip;
</p>]]>
        <![CDATA[<p>&nbsp;</p>
<pre class="brush: csharp">
XYZ.Business.AppFacades.Moles.MSomeFacade.AllInstances.GetAllInt32Int32IOrderBy
    = (SomeFacade iFacade, int iStartRow, int iRowcount, IOrderBy iOrderBy) =>
        {
            Assert.AreEqual(startRow, iStartRow, "getall - wrong start row");
            Assert.AreEqual(rowCount, iRowcount, "getall - wrong row count");
            Assert.IsInstanceOfType(iOrderBy, typeof(OrderBySomeProperty), "getall - sort order");
            Assert.IsFalse(iOrderBy.Descending, "getall - descending");

            return new List<ISomething>() { someInstantiatedObject };
        };
		
		// Run the system under test
        SomeController target = m_kernel.Get<SomeController>();
</pre>
<p>Replace with&hellip;</p>

<pre class="brush: csharp">
var mockFacade = new Mock<ISomeFacade>(MockBehavior.Strict);
mockFacade.Setup(ibf => ibf.GetAll(It.Is<int>(i => i == startRow), It.Is<int>(j => j == rowCount), It.Is<IOrderBy>(k => k is OrderBySomeProperty))).Returns(
    (int iStartRow, int iRowcount, IOrderBy iOrderBy) =>
    {
        return new List<ISomething>() { someInstantiatedObject };
    });

m_kernel.Bind<IBrandFacade>().ToConstant(mockFacade.Object);
</pre>

<p>Thanks to the Strict behavior, I end up getting an error on another method in the facade class. An explicit mocking is needed for that one too:
</p>
<pre class="brush: csharp">
mockFacade.Setup(ibf => ibf.GetRowCount()).Returns(1);
</pre>
<p>
In the Moles example, I would have ended up hitting the real GetRowCount method without realizing it. If I hadn&rsquo;t implicitly setup a fake database with that Ninject call <code>m_kernel.Get&lt;SomeController&gt;</code>, the GetRowCount method would have actually queried the database. As a unit test, this is precisely what I was trying to avoid with Moles.
</p>
<p>
I have lost one thing in translation &ndash; if one of the arguments is wrong, it can be a little more difficult to tell why. In the Moles example, I have the explicit Assert statements in the body of the Mole. In the MoQ example, with Strict behavior turned on, I am telling Mock to throw an error if any criteria other than those three Lambdas attached to <code>It.Is&lt;T&gt;(Func&lt;T,bool&gt;)</code> is passed to the GetAll method. When I manually mess up one of the input values to the test method, I get this result:</p>
<blockquote>
Test method MyTest.SortIndexPageTwoByAddressAscending threw exception: 
Moq.MockException: ISomeFacade.GetAll(3, 3, XYZ.Business.DTO.Sortable.OrderBySomeProperty) invocation failed with mock behavior Strict.
All invocations on the mock must have a corresponding setup.
</blockquote>
<p>With the Moles example, I would have seen <code>Assert.AreEqual failed. Expected:&lt;1&gt;. Actual:&lt;3&gt;. getall - wrong start row</code>, which is a little more explicit. In the MoQ example I know that there is a problem with the arguments; the third one was just a test of type, and it is clear that it is not the cause. So I must look to the two <code>int</code>s. Still, that is not all that difficult: I know that I have the values 3 and 3, and all I must do is look at the value of startRow and of rowCount to see which one is not three. Then I&rsquo;ll understand which failed. That only takes me a few seconds longer.</p>
<p>Of course, I could switch back from Strict to Loose behavior on the Mock, which would allow me to put those Assert statements into the body of the Mock. But then I lose the benefit of getting a failure if there are unexpected method calls. I think I&rsquo;ll accept the small inconvenience above in return for the huge convenience of verifying that the system under test isn&rsquo;t explicitly or implicitly calling some other method in <code>ISomeFacade</code>.</p>]]>
    </content>
</entry>

<entry>
    <title>Unit vs. Integration Tests When Querying Nullable Columns</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/04/unit-vs-integration-tests-when-querying-nullable-columns.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.462</id>

    <published>2012-04-13T01:47:11Z</published>
    <updated>2012-04-13T01:53:46Z</updated>

    <summary><![CDATA[Here&rsquo;s an interesting scenario: I have a Linq-to-Entities query that is giving me no results when performing a system test, but when I look in the database, logically there should be results. Better yet, the unit test passes. How can...]]></summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="linq" label="Linq" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="testdrivendevelopment" label="test driven development" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="testing" label="testing" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="unittest" label="unit test" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p>Here&rsquo;s an interesting scenario: I have a Linq-to-Entities
query that is giving me no results when performing a system test,
but when I look in the database, logically there should be results.
Better yet, the unit test passes. How can that be?</p>]]>
        <![CDATA[<p>The query includes a step where it is excluding any MyObject
that is linked a particular SomeOtherObject. MyObject has a
<i>conceptual</i>, but not <i>foreign</i>, key that links to
SomeOtherObject (call it "SomeGUID"). In this scenario, a
<code>null</code> is meaningful &ndash; it is a 1 to 0
relationship. That turns out to be the root cause of the problem
above.</p>
<p>I was just telling someone a few days ago that a query on a
nullable column must take the null into account, which surprised
that person. And now I find that I've overlooked that myself! Two
problems then:</p>
<ol>
<li>A <i>T-SQL WHERE</i> clause like <code>SomeGUID !=
&lsquo;SomeValue&rsquo;</code> will not return a row where SomeGUID
is <code>NULL</code>. You need <code>SomeGUID !=
&lsquo;SomeValue&rsquo; OR SomeGUID IS NULL</code>. But a similar
<i>Linq WHERE</i> clause that doesn&rsquo;t hit a database will
return the null row.</li>
<li>Unit tests of Linq-to-Entities, that use a fake database, may
not expose some problems with searches that encounter NULL values.
Integration tests are needed for that. Hence, don't forget to also
throw together at least a few integration tests for your
queries.</li>
</ol>
<p>To prove this, I wrote a new unit test that uses the fake
database (there are other tests for this method, but I wanted to
focus on this particular problem by creating a new one). There is
one MyObject and it is not connected to any SomeOtherObject. The
query in question should return this one MyObject. The unit test
does indeed pass.</p>
<p>I then slightly rewrite the test so that the query is hitting
the real database, but with the same data: an integration test. The
test fails &ndash; no results are returned. At this point I was
expecting this.</p>
<p>Modify the Linq query so that it include the <code>OR &hellip;
IS NULL</code> clause. From</p>
<pre class="brush: csharp">
query = query.Where(x =&gt; x.SomeGUID != theGuidIDontWant);
</pre>
<p>To</p>
<pre class="brush: csharp">
query = query.Where(x =&gt; x.SomeGUID != theGuidIDontWant || x.SomeGUID == null);
</pre>
<p>Now both tests are passing.</p>]]>
    </content>
</entry>

<entry>
    <title>Using Windows CNAMEs to Reduce Server Confusion</title>
    <link rel="alternate" type="text/html" href="http://www.safnet.com/writing/tech/2012/04/using-windows-cnames-to-reduce-server-confusion.html" />
    <id>tag:www.safnet.com,2012:/writing/tech//3.461</id>

    <published>2012-04-04T00:20:19Z</published>
    <updated>2012-04-04T00:22:11Z</updated>

    <summary><![CDATA[A common challenge for development teams is remembering the names for all of the different servers in an enterprise environment when the server naming convention is either not descriptive (&quot;Deathstar&quot;, &quot;Falcon&quot;, &quot;XWing&quot;) or obscure (&quot;abcDBS001&quot;, &quot;abcDBS002&quot;, &quot;abcWEB01&quot;). The Star Wars...]]></summary>
    <author>
        <name>Stephen Fuqua</name>
        
    </author>
    
    <category term="agile" label="agile" scheme="http://www.sixapart.com/ns/types#tag" />
    <category term="windows" label="Windows" scheme="http://www.sixapart.com/ns/types#tag" />
    
    <content type="html" xml:lang="en-us" xml:base="http://www.safnet.com/writing/tech/">
        <![CDATA[<p>A common challenge for development teams is remembering the names for all of the different servers in an enterprise environment  when the server naming convention is either not descriptive (&quot;Deathstar&quot;, &quot;Falcon&quot;, &quot;XWing&quot;) or obscure (&quot;abcDBS001&quot;, &quot;abcDBS002&quot;, &quot;abcWEB01&quot;). The Star Wars names suffer from an obvious problem of mapping description to purpose. Those obscure names are commonly used to help distinguish between dozens to hundreds of different servers in an enterprise. Arguably they are helpful to the infrastructure team as they manage this motley collection. But for a developer, remembering if &quot;abcWEB01&quot; is the test web server or prod can be challenging; even when remembered, it would be simple enough to overlook or accidentally type &quot;abcWEB04&quot;.</p>]]>
        <![CDATA[<p>A Windows Server can be configured with <a href="http://technet.microsoft.com/en-us/library/cc776292%28v=ws.10%29.aspx">a name alias</a> (CNAME) that preserves the naming convention used by infrastructure, but helps the development team avoid confusion and accidents. Assuming that there is a good separation between servers &ndash; say, development, test, and production &ndash; and their purposes &ndash; say, web apps, services, reports, and database &ndash; wouldn&#39;t it just be easier to refer to:</p>
<ul>
<li>devweb</li>
<li>testweb</li>
<li>prodweb</li>
<li>devservices</li>
<li>testsql</li>
<li><i>et cetera</i></li>
</ul>
<p>Of course, that scheme presumes that there is only one server in each category. If there are multiple servers in order to fit different needs, then find a name that explains that need: for example, testexternalweb and testinernalweb, for DMZ and internal web servers. I can&#39;t begin to reckon the number of times such an (aliased) naming convention would have helped avoid mistakes and improved communication over the years.</p>
<p>Bonus: if abcWEB01 needs to be retired and replaced by with abcWeb10, just change the CNAME so that prodweb points to the new server. Application configuration nightmare averted.</p>]]>
    </content>
</entry>

</feed>
