<?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>Simply Does Not Work</title>
	<atom:link href="http://nicholas.piasecki.name/blog/feed/" rel="self" type="application/rss+xml" />
	<link>http://nicholas.piasecki.name/blog</link>
	<description>Confessions of a small business software developer</description>
	<lastBuildDate>Sat, 31 Mar 2012 01:57:49 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
		<item>
		<title>A brief rant on credit card security</title>
		<link>http://nicholas.piasecki.name/blog/2011/02/a-brief-rant-on-credit-card-security/</link>
		<comments>http://nicholas.piasecki.name/blog/2011/02/a-brief-rant-on-credit-card-security/#comments</comments>
		<pubDate>Sat, 26 Feb 2011 16:06:59 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[Rants]]></category>
		<category><![CDATA[e-commerce]]></category>
		<category><![CDATA[fraud]]></category>
		<category><![CDATA[payments]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=833</guid>
		<description><![CDATA[I wish that the Address Verification System (AVS) worked well, that it worked against shipping instead of billing addresses (i.e., cardholders could maintain a list of valid shipping addresses online with their bank), and that it was required to process &#8230; <a href="http://nicholas.piasecki.name/blog/2011/02/a-brief-rant-on-credit-card-security/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>I wish that the Address Verification System (AVS) worked well, that it worked against <em>shipping</em> instead of billing addresses (i.e., cardholders could maintain a list of valid shipping addresses online with their bank), and that it was required to process all card-not-present transactions (because this might give banks an incentive to make AVS actually work well all of the time, when their cardholders start complaining that e-commerce stores are flagging all of their transactions, and for consumers to maintain updated address information at their banks).</p>

<p>To stop fraud, we need to stop allowing purchases to be made solely with the information that appears on the card because this is not secret information; it is basic information about an account. This is not something that merchants can fix alone. Merchants already have to foot the bill for chargebacks, and PCI standards are really just an attempt to make merchants responsible for maintaining the security of what is, at its core, a payment system that broke in the 1990s. CVN didn&#8217;t work&#8211;10 years later, we still have to explain to consumers where the number is because the card associations have not spent enough effort educating the public and, quite frankly, they don&#8217;t care. To use a credit card, anywhere, you should have to swipe it (PCI is still relevant in this scenario). Period.</p>

<p>Two-factor authentication, in the traditional sense, is not a solution. 3-D Secure is confusing for both merchants and consumers, expensive, and little used: for the program to work, it needs to be required. A better solution would be programs like Discover&#8217;s Secure Online Account Number (where you can generate a temporary account number), but they fucked that up by making the temporary account numbers expire on the same day as the real account number (to be effective, they should expire after a certain number of transactions or be able to be locked down to a specific merchant). And for such a program to work, this also needs to be required, too.</p>

<p>It&#8217;s time for consumers and banks to grow up and deal with credit card fraud because the problems with it today are largely ones that merchants cannot and no amount of obfuscating cardholder data can fix. Unfortunately, at the end of the day, it&#8217;s the merchant who usually ends up paying for the fraudulent charges when the dime finally drops, so we&#8217;ll continue to see little help from the card associations and the issuing banks: no one has the balls to make sweeping consumer- and bank-initiated security changes to the industry and <em>require</em> those changes for future transactions, unless they&#8217;re pointing their fingers at the merchants.</p>

<p>I guess we&#8217;ll just have to keep bending over and taking it&#8211;the responsibility, the consequences of fraud, and all of the blame when the system doesn&#8217;t work.</p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2011/02/a-brief-rant-on-credit-card-security/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>DKIM Signing Outbound Messages in Exchange Server 2007</title>
		<link>http://nicholas.piasecki.name/blog/2010/12/dkim-signing-outbound-messages-in-exchange-server-2007/</link>
		<comments>http://nicholas.piasecki.name/blog/2010/12/dkim-signing-outbound-messages-in-exchange-server-2007/#comments</comments>
		<pubDate>Fri, 24 Dec 2010 00:55:26 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[Rants]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[dkim]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[exchange]]></category>
		<category><![CDATA[it-stuff]]></category>
		<category><![CDATA[sbs-2008]]></category>
		<category><![CDATA[skiviez]]></category>
		<category><![CDATA[yahoo]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=768</guid>
		<description><![CDATA[DomainKeys Identified Mail is a proposed standard that, in its own words, allows a domain (such as skiviez.com) to assert responsibility for the contents of an e-mail message. The outgoing mail transport agent (&#8220;mail server&#8221;) computes a hash of the &#8230; <a href="http://nicholas.piasecki.name/blog/2010/12/dkim-signing-outbound-messages-in-exchange-server-2007/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.dkim.org/">DomainKeys Identified Mail</a> is a <a href="http://www.dkim.org/specs/rfc4871-dkimbase.html">proposed standard</a> that, in its own words, allows a domain (such as <code>skiviez.com</code>) to assert responsibility for the contents of an e-mail message.</p>

<p>The outgoing mail transport agent (&#8220;mail server&#8221;) computes a hash of the body of the mail message and adds a special, cryptographically signed <code>DKIM-Signature</code> header to the mail message that contains this hash as well as some other information about the message. The public part of the key, used by receiving mail transport agents to verify the signature on incoming messages, is stored as a <code>TXT</code> record in the DNS for the signing domain.</p>

<p>The result of all of this is that the recipient can now know that the body and certain headers of the e-mail message were not tampered with or changed by a third party while the message was in transit. If the signature contained within the <code>DKIM-Signature</code> header doesn&#8217;t verify, then it&#8217;s possible that the message is a phishing message, spam, or some other false representation of members of the signing domain. (IMHO, however, it is more likely to just indicate a broken DKIM implementation, as there are several obnoxious corner cases that we will see.)</p>

<h2>Where is the Exchange support?</h2>

<p>No currently released version of Microsoft Exchange supports DKIM natively, not even 2010. This is purportedly because Microsoft threw its weight behind another standard called <a href="http://www.openspf.org/">SPF</a>, or Sender Protection Framework. SPF is much simpler to implement because it does not make a statement about the integrity of the message contents; that is, there is no signing step that requires processing of each outbound message and stamping it with a special header. Instead, a <code>TXT</code> record in the DNS for the sending domain lists the IP addresses from which e-mail messages from that domain are allowed to originate.</p>

<p>For example, let&#8217;s say that a store has a mail transport agent at <code>mail.example.com</code> and a Web site at <code>www.example.com</code>. An SPF record for <code>example.com</code> might make a statement like the following:</p>

<p>&#8220;E-mail messages purporting to be from @example.com should only originate from either <code>mail.example.com</code> or <code>www.example.com</code>. All other originating IP addresses should be treated with suspicion.&#8221;</p>

<p>You can see why this is easier to implement; you just add an entry to DNS, and you don&#8217;t have to configure the outbound mail transport agent to do anything. The only reason a mail transport agent would need to change is for it to gain the ability to inspect <em>incoming</em> messages and validate the <code>MAIL FROM</code> part of the message headers against the corresponding SPF <code>TXT</code> records in DNS. And that is what Exchange does today.</p>

<p>While SPF does not validate the integrity of the message&#8211;a hacked, legitimate company mail server that spews out spam unwittingly will still pass an SPF&#8211;it is a simple, convenient way to mark phishing and spoofing attempts originating from other locations, like a random house in Wisconsin that is unwittingly part of a botnet, with suspicion.</p>

<p>But, then again, a hacked mail transport agent using DKIM that spews out spam unwittingly will still pass a DKIM verification. Spam can be signed just like regular mail. So the advantage of DKIM over SPF is that DKIM provides the ability to prove that the contents of the message were not modified in transit, and if an organization so chose, they could sign different messages with different keys or decide to not sign certain kinds of messages at all, allowing the recipient to interpret these different kinds of mail in different ways.</p>

<p>In reality, most e-mail doesn&#8217;t need to be <em>that</em> secure, so the utility-to-difficulty ratio may be a little out-of-whack here, especially when other standards for signing messages already exist.</p>

<h2>So DKIM is more complicated and not supported by Microsoft. Why implement DKIM on Exchange?</h2>

<p>Because fuck <a href="http://www.yahoo.com/">Yahoo!</a>, that&#8217;s why.</p>

<p>Actually, let&#8217;s step back a minute.</p>

<p>Yahoo! invented something called <a href="http://domainkeys.sourceforge.net/">Domain Keys</a>, which predates DKIM and which DKIM is largely based on, in an attempt to combat spam in the ways described previously. The aim was for Yahoo! mail servers to be able to easily identify entire classes of suspect e-mail and send them to people&#8217;s spam folders (which, in Yahoo! weasel words, is referred to as the &#8220;bulk mail folder&#8221;). Then they integrated it into the Yahoo! mail system.</p>

<p>If your business sends mail of any kind of volume to Yahoo! mail servers, such as an e-mail newsletter that users subscribe to, you&#8217;ll quickly see a message along the lines of the following:</p>

<p>421 4.16.55 [TS01] Messages from x.x.x.x temporarily deferred due to excessive user complaints</p>

<p>And you might also notice your e-mail messages going straight to the spam folder on Yahoo! mail accounts by default, with a <code>X-Yahoo-Filtered-Bulk: x.x.x.x</code> header appearing in the message headers. If this has happened, it is because Yahoo! has decided that you are naughty and placed the IP address of your mail transport agent on an internal blacklist. If a Yahoo! user has previously marked e-mail from your domain as &#8220;Not Spam,&#8221; then that user will continue to receive your e-mail, but any other Yahoo! users will find your e-mail going to the spam folder by default until they either click the &#8220;Not Spam&#8221; button on one of them or add your from address to their contact list.</p>

<p>&#8220;But we&#8217;re a legitimate small business,&#8221; you say. &#8220;Only about 5,000 of the e-mails on our mailing list are actual Yahoo! addresses, the newsletter list is opt-in, and there are &#8216;Unsubscribe&#8217; links in every e-mail. It&#8217;s not like we&#8217;re spamming users out of the blue,&#8221; you continue. &#8220;These are users who have asked for this service and can cancel at anytime. So why has Yahoo! blacklisted us and treat us like spam?&#8221;</p>

<p>The answer, unfortunately, is that Yahoo! is incompetent and can&#8217;t build a mail service that can handle spam like Gmail can handle spam. Instead, their e-mail system depends on the following metrics:</p>

<ul>
<li>If a large burst of e-mail comes from the same IP address within a certain time period, temporarily consider it as a spam and temporarily deny the requests. The mail will still arrive, but the &#8220;fat pipe&#8221; will be squashed down so that overall delivery takes longer to complete. The idea is that if the mail is originating from a spammer, they are unlikely to try again.</li>
<li>If a &#8220;significant&#8221; number of Yahoo! users mark mail messages originating from the same IP address as spam by clicking on the &#8220;Spam&#8221; button in their account, add that IP address to the <code>X-Yahoo-Filtered-Bulk</code> blacklist.</li>
</ul>

<p>In other words, if enough people mark your e-mail as spam, your IP address is fucked, and you&#8217;ll soon be fielding complaints from customers who insist that they aren&#8217;t receiving your Web sites transactional e-mails, such as a &#8220;forgot my password&#8221; or &#8220;shipping confirmation&#8221; e-mail, because Yahoo! has now decided to deliver all e-mails that originate from your IP address to the spam folder, which many users do not think to check or cannot find. So they blame you.</p>

<p>If you think that Yahoo! has blacklisted you in error, or if you have improved your e-mail sending practices and wish to have them consider you for removal, you can fill out <a href="http://help.yahoo.com/l/us/yahoo//mail/postmaster/defer.html">this form with incorrect JavaScript required field validation</a> to request that the Yahoo! postmaster take you off the naughty list. About 27 hours later, a Yahoo! representative with a sub-room temperature IQ will e-mail you back a long, canned reply that generally amounts to &#8220;No.&#8221;</p>

<p>But in that &#8220;no&#8221; message, they offer the possibility of signing up to the <a href="http://feedbackloop.yahoo.net/">Complaint Feedback Loop</a>. When you participate in this program, if a Yahoo! user presses the &#8220;Spam&#8221; button on one of your e-mails, then Yahoo! will e-mail you the e-mail address of that user along with a copy of the e-mail that you sent. You can then unsubscribe that user from your mailing list yourself (since they neglected to use the unsubscribe link in your e-mail and will continue to damage the reputation of your IP address if you continue to send mail to them), or you can see which kinds of e-mails you are sending are creating the most problems.</p>

<p>But participation in their feedback loop requires that you use DKIM to sign all of your outbound mail messages. The reasons for this are not clear, but I assume it has to do with ensuring that you are only notified about the problematic e-mails that legitimately came from your organization, and not ones generated by a spammer. Or, it could simply be a way to drive adoption of Yahoo!&#8217;s DKIM standard.</p>

<p>At any rate, Yahoo! mail is the most widely used e-mail service on the planet, so when the idiots in the higher echelons of Yahoo! say &#8220;Jump!&#8221; then we must ask &#8220;How high?&#8221; When they say &#8220;implement DKIM&#8221;, we implement DKIM.</p>

<h2>So what are options for implementing DKIM on Exchange?</h2>

<p>One option is to simply not do it in Exchange and set up a relaying mail server that has DKIM support, like <a href="http://www.hmailserver.com/">hMailServer</a> or <a href="http://www.postfix.org/">Postfix</a> with dkim-milter. But if you&#8217;re at a small business, the idea of maintaining yet another server for what is conceptually a simple task is not a pleasant thought.</p>

<p>Another option is to use a dedicated device like a <a href="http://www.barracudanetworks.com/ns/products/spam_overview.php">Barracuda</a> or an <a href="http://www.ironport.com/">IronPort</a>. This device would sit in front of Exchange and rewrite the mail headers in transit, adding the <code>DKIM-Signature</code> header as it flies out of your office. But these devices are not cheap and are out of reach of many small businesses. And the thought of acquiring a specialized device for doing something any mail transport agent should be able to do natively is not a pleasant thought.</p>

<p>You can buy an off-the-shelf plug-in for Exchange like <a href="http://www.emailarchitect.net/domainkeys/">this one from a company in Hong Kong</a>. The reviews on the Internet do generally seem to indicate that it does work. But do we really want to spend $300 &#8211; $800 on a component from a company without a reputation and give that component read access to all of our organization&#8217;s outbound mail messages? Trust is certainly a driving factor here.</p>

<p>A fourth option, and the option I pursued since I considered giving up on DKIM if Yahoo! didn&#8217;t change its ways after our implementation, is to take advantage of Exchange 2007&#8242;s new <a href="http://technet.microsoft.com/en-us/library/bb125012%28EXCHG.80%29.aspx">Transport Agents</a> functionality. This allows you to write custom, managed code that runs on that .NET Framework that integrates with the Exchange message processing pipeline. In our case, we could write a custom transport agent that appends a <code>DKIM-Signature</code> header to outgoing MIME messages.</p>

<h2>Setting up the project</h2>

<p>In Visual Studio, we just need to use a plain old &#8220;C# Class Library&#8221; project. The project <em>must</em> target version 2.0 of the CLR (that&#8217;s .NET Framework 2.0, .NET Framework 3.0, or .NET Framework 3.5, thanks to the dipshits in Microsoft&#8217;s marketing department) and <em>not</em> the .NET Framework 1.x or, maddeningly, the .NET Framework 4.x. This is because the transport agent process provided by Exchange Server 2007 that will load our transport agent is running on CLR 2.0, and a process that&#8217;s been loaded with an earlier version of the CLR can&#8217;t load a later version.</p>

<p>We also need to reference two assemblies provided by the Exchange Server, <code>Microsoft.Exchange.Data.Common.dll</code> and <code>Microsoft.Exchange.Data.Transport.dll</code>. You would think that you would be able to find these in, say, the Exchange Server SDK that&#8217;s available from Microsoft Downloads. But you&#8217;d be wrong. Microsoft keeps diddling with the version of these assemblies with various update rollups for Exchange, and the only way to get a copy is to pull them off an actual Exchange Server 2007 installation. Mine were located in <code>C:\Program Files\Microsoft\Exchange Server\Public</code>; I just copied them to my local computer and referenced them in my new class library assembly for local development.</p>

<p>To start, we just need to create two classes. The first is our actual agent, which derives from the <code>RoutingAgent</code> class defined in the DLLs we just copied:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">sealed</span> <span style="color: #6666cc; font-weight: bold;">class</span> DkimSigningRoutingAgent <span style="color: #008000;">:</span> RoutingAgent
<span style="color: #008000;">&#123;</span>
	<span style="color: #0600FF; font-weight: bold;">public</span> DkimSigningRoutingAgent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">// What &quot;Categorized&quot; means in this sense,</span>
		<span style="color: #008080; font-style: italic;">// only the Exchange team knows</span>
		<span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OnCategorizedMessage</span> <span style="color: #008000;">+=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">WhenMessageCategorized</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> WhenMessageCategorized<span style="color: #008000;">&#40;</span>
		CategorizedMessageEventSource source,
		QueuedMessageEventArgs e<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">// This is where the magic will happen</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>The second is a factory class that the Exchange server&#8217;s little plug-in agent looks for; it&#8217;ll instance new copies of our agent:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">sealed</span> <span style="color: #6666cc; font-weight: bold;">class</span> DkimSigningRoutingAgentFactory <span style="color: #008000;">:</span> RoutingAgentFactory
<span style="color: #008000;">&#123;</span>
	<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">override</span> RoutingAgent CreateAgent<span style="color: #008000;">&#40;</span>SmtpServer server<span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> DkimSigningRoutingAgent<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>You&#8217;re probably thinking, &#8220;Wow! <a href="http://msdn.microsoft.com/en-us/library/microsoft.exchange.data.transport.routing.routingagent%28v=EXCHG.80%29.aspx">The documentation provided by the Exchange team sure blows donkey chunks</a>, how did you ever figure out that that was what you needed to do?&#8221; The answer is by spelunking through the <a href="http://msdn.microsoft.com/en-us/exchange/default">Exchange Server SDK</a> examples and by religiously following <a href="http://msexchangeteam.com/archive/2006/12/04/431755.aspx">this guy&#8217;s blog</a>.</p>

<p>Now we&#8217;re ready to start reading mail messages and &#8220;canonicalizing&#8221; them into the format that the DKIM spec expects.</p>

<h2>Exchange and &#8220;Internet Mail&#8221;</h2>

<p>If there is one thing that is annoying about Exchange, it is that 20-some years after the fact it seems skeptical that this whole &#8220;Internet Mail&#8221; thing is going to catch on. Getting Exchange to give you the raw message in MIME format is not as simple as one might think.</p>

<p>You see, to be able to hash the body of the message and sign certain headers in the message, we need to know exactly how Exchange is going to format it when it is sent. Even a single space or newline that is added after we compute the hash can throw the whole thing off.</p>

<p>In our routing agent&#8217;s <code>OnCategorizedMessage</code> event listener, the event arguments give us access to an instance of the <code>MailItem</code> class. It has a boatload of properties for accessing the body and headers of the message programmatically. Unfortunately, we can&#8217;t use these properties because they represent the <em>semantic</em> values, not the <em>raw</em> ones. Instead, we&#8217;ll need to use the <code>GetMimeReadStream()</code> and <code>GetMimeWriteStream()</code> methods to read the raw mail message and write out the modified version, respectively.</p>

<h2>Implementing the routing agent</h2>

<p>Let&#8217;s start by completing the Routing Agent implementation. We&#8217;ll keep it simple by moving all of the hard signing stuff into an <code>IDkimSigner</code> interface, which we&#8217;ll worry about implementing later:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">sealed</span> <span style="color: #6666cc; font-weight: bold;">class</span> DkimSigningRoutingAgent <span style="color: #008000;">:</span> RoutingAgent
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> ILog log <span style="color: #008000;">=</span> LogManager<span style="color: #008000;">.</span><span style="color: #0000FF;">GetLogger</span><span style="color: #008000;">&#40;</span>
        MethodBase<span style="color: #008000;">.</span><span style="color: #0000FF;">GetCurrentMethod</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DeclaringType</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> IDkimSigner dkimSigner<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">public</span> DkimSigningRoutingAgent<span style="color: #008000;">&#40;</span>IDkimSigner dkimSigner<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>dkimSigner <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentNullException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;dkimSigner&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">dkimSigner</span> <span style="color: #008000;">=</span> dkimSigner<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OnCategorizedMessage</span> <span style="color: #008000;">+=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">WhenMessageCategorized</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> WhenMessageCategorized<span style="color: #008000;">&#40;</span>
        CategorizedMessageEventSource source,
        QueuedMessageEventArgs e<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">try</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">SignMailItem</span><span style="color: #008000;">&#40;</span>e<span style="color: #008000;">.</span><span style="color: #0000FF;">MailItem</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">catch</span> <span style="color: #008000;">&#40;</span>Exception ex<span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            log<span style="color: #008000;">.</span><span style="color: #0000FF;">Error</span><span style="color: #008000;">&#40;</span>
                Resources<span style="color: #008000;">.</span><span style="color: #0000FF;">DkimSigningRoutingAgent_SignFailed</span>,
                ex<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> SignMailItem<span style="color: #008000;">&#40;</span>MailItem mailItem<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span>mailItem<span style="color: #008000;">.</span><span style="color: #0000FF;">Message</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsSystemMessage</span> <span style="color: #008000;">&amp;&amp;</span>
            mailItem<span style="color: #008000;">.</span><span style="color: #0000FF;">Message</span><span style="color: #008000;">.</span><span style="color: #0000FF;">TnefPart</span> <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var inputStream <span style="color: #008000;">=</span> mailItem<span style="color: #008000;">.</span><span style="color: #0000FF;">GetMimeReadStream</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">dkimSigner</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CanSign</span><span style="color: #008000;">&#40;</span>inputStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var outputStream <span style="color: #008000;">=</span> mailItem<span style="color: #008000;">.</span><span style="color: #0000FF;">GetMimeWriteStream</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                    <span style="color: #008000;">&#123;</span>
                        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">dkimSigner</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Sign</span><span style="color: #008000;">&#40;</span>inputStream, outputStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                    <span style="color: #008000;">&#125;</span>
                <span style="color: #008000;">&#125;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>The only real quirk is the <code>if</code> statement in the <code>SignMailItem()</code> function, which I mostly discovered through trial and error. If the mail item is a &#8220;system message&#8221; (whatever that means) then all of the <code>mailItem</code>&#8216;s methods will be read only (throwing exceptions if we try to mutate), so we shouldn&#8217;t even bother. And if the mail item has a TNEF part, then in it&#8217;s in a <a href="http://en.wikipedia.org/wiki/Transport_Neutral_Encapsulation_Format">bizarro proprietary Microsoft format</a>, and the DKIM spec just isn&#8217;t going to work with that. Finally, if something blows up, we catch the exception and log it&#8211;better to send a message without a signature than not send it all.</p>

<h2>Defining an interface for DKIM signing</h2>

<p>So the next step is to make up that <code>IDkimSigner</code> implementation and make it do the dirty work. You can see that I&#8217;ve made it simple in that we only need to write two methods:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">interface</span> IDkimSigner <span style="color: #008000;">:</span> IDisposable
<span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">bool</span> CanSign<span style="color: #008000;">&#40;</span>Stream inputStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #6666cc; font-weight: bold;">void</span> Sign<span style="color: #008000;">&#40;</span>Stream inputStream, Stream outputStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<h3>A method for sanity checking</h3>

<p>The first method will scan our mail item&#8217;s content stream and do a sanity check and ensure that we can actually sign the message. For example, if our <code>IDkimSigner</code> implementation is configured to sign messages originating from <code>warehouse1.example.com</code> and we pass <code>CanSign()</code> a message from <code>warehouse2.example.com</code>, then we can return <code>false</code> to indicate that we just don&#8217;t know what to do with the message. Let&#8217;s implement that method.</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> domain<span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">bool</span> CanSign<span style="color: #008000;">&#40;</span>Stream inputStream<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">bool</span> canSign<span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> line<span style="color: #008000;">;</span>
    StreamReader reader<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">disposed</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ObjectDisposedException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;DomainKeysSigner&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>inputStream <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentNullException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;inputStream&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    canSign <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">false</span><span style="color: #008000;">;</span>
    reader <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamReader<span style="color: #008000;">&#40;</span>inputStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    inputStream<span style="color: #008000;">.</span><span style="color: #0000FF;">Seek</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span>, SeekOrigin<span style="color: #008000;">.</span><span style="color: #0000FF;">Begin</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    line <span style="color: #008000;">=</span> reader<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span>line <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">string</span> header<span style="color: #008000;">;</span>
        <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> headerParts<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// We've reached the end of the headers (headers are</span>
        <span style="color: #008080; font-style: italic;">// separated from the body by a blank line).</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>line<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">break</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// Read a line. Because a header can be continued onto</span>
        <span style="color: #008080; font-style: italic;">// subsequent lines, we have to keep reading lines until we</span>
        <span style="color: #008080; font-style: italic;">// run into the end-of-headers marker (an empty line) or another</span>
        <span style="color: #008080; font-style: italic;">// line that doesn't begin with a whitespace character.</span>
        header <span style="color: #008000;">=</span> line <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\r</span><span style="color: #008080; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">;</span>
        line <span style="color: #008000;">=</span> reader<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">while</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #008000;">&#40;</span>line<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span>
            <span style="color: #008000;">&#40;</span>line<span style="color: #008000;">.</span><span style="color: #0000FF;">StartsWith</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\t</span>&quot;</span>, StringComparison<span style="color: #008000;">.</span><span style="color: #0000FF;">Ordinal</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">||</span>
            line<span style="color: #008000;">.</span><span style="color: #0000FF;">StartsWith</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot; &quot;</span>, StringComparison<span style="color: #008000;">.</span><span style="color: #0000FF;">Ordinal</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            header <span style="color: #008000;">+=</span> line <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;<span style="color: #008080; font-weight: bold;">\r</span><span style="color: #008080; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">;</span>
            line <span style="color: #008000;">=</span> reader<span style="color: #008000;">.</span><span style="color: #0000FF;">ReadLine</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #008080; font-style: italic;">// Extract the name of the header. Then store the full header</span>
        <span style="color: #008080; font-style: italic;">// in the dictionary. We do this because DKIM mandates that we</span>
        <span style="color: #008080; font-style: italic;">// only sign the LAST instance of any header that occurs.</span>
        headerParts <span style="color: #008000;">=</span> header<span style="color: #008000;">.</span><span style="color: #0000FF;">Split</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">char</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">&#123;</span> <span style="color: #666666;">':'</span> <span style="color: #008000;">&#125;</span>, <span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>headerParts<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">2</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #6666cc; font-weight: bold;">string</span> headerName<span style="color: #008000;">;</span>
&nbsp;
            headerName <span style="color: #008000;">=</span> headerParts<span style="color: #008000;">&#91;</span><span style="color: #FF0000;">0</span><span style="color: #008000;">&#93;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>headerName<span style="color: #008000;">.</span><span style="color: #0000FF;">Equals</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;From&quot;</span>, StringComparison<span style="color: #008000;">.</span><span style="color: #0000FF;">OrdinalIgnoreCase</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// We don't break here because we want to read the bottom-most</span>
                <span style="color: #008080; font-style: italic;">// instance of the From: header (there should be only one, but</span>
                <span style="color: #008080; font-style: italic;">// if there are multiple, it's the last one that matters).</span>
                canSign <span style="color: #008000;">=</span> header
                    <span style="color: #008000;">.</span><span style="color: #0000FF;">ToUpperInvariant</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                    <span style="color: #008000;">.</span><span style="color: #0000FF;">Contains</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;@&quot;</span> <span style="color: #008000;">+</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">domain</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToUpperInvariant</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    inputStream<span style="color: #008000;">.</span><span style="color: #0000FF;">Seek</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span>, SeekOrigin<span style="color: #008000;">.</span><span style="color: #0000FF;">Begin</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> canSign<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>Barf. But we have to do this style of ghetto parsing because, after all, we&#8217;re dealing with the raw e-mail message format. All we&#8217;re doing is scanning through the headers until we reach the last <code>From:</code> header, and then we make sure that the <code>From:</code> e-mail address belongs to the domain that our instance knows how to sign. Then we seek back to the beginning of the stream to be polite.</p>

<h3>A method for signing</h3>

<p>The second method that we have to implement is the one that actually does all of the dirty work. And in DKIM signing, we can break it down into five steps:</p>

<ol>
<li>Compute a hash of the body of the message.</li>
<li>Create an unsigned version of the <code>DKIM-Signature</code> header that contains that body hash value and some other information, but has the signature component set to an empty string.</li>
<li>&#8220;Canonicalize&#8221; the headers that we are going to sign. By &#8220;canonicalize&#8221;, we mean &#8220;standardize capitalization, whitespace, and newlines into a format required by the spec, since other mail transport agents who get their grubby paws on this message might reformat the headers&#8221;.</li>
<li>Slap our unsigned version of the <code>DKIM-Signature</code> header to the end of our &#8220;canonicalized&#8221; headers, sign that data, and slap the resulting signature to the end of the <code>DKIM-Signature</code> header.</li>
<li>Write this signed <code>DKIM-Signature</code> into the headers of the mail message, and send it on its merry way.</li>
</ol>

<p>Divide and conquer!</p>

<h2>Implementing the <code>Sign()</code> method</h2>

<p>Our implementation for the <code>Sign()</code> method will tackle each step in turn:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> Sign<span style="color: #008000;">&#40;</span>Stream inputStream, Stream outputStream<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">disposed</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ObjectDisposedException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;DomainKeysSigner&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>inputStream <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentNullException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;inputStream&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>outputStream <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentNullException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;outputStream&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    var bodyHash <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetBodyHash</span><span style="color: #008000;">&#40;</span>inputStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    var unsignedDkimHeader <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetUnsignedDkimHeader</span><span style="color: #008000;">&#40;</span>bodyHash<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    var canonicalizedHeaders <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetCanonicalizedHeaders</span><span style="color: #008000;">&#40;</span>inputStream<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    var signedDkimHeader <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetSignedDkimHeader</span><span style="color: #008000;">&#40;</span>unsignedDkimHeader, canonicalizedHeaders<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    WriteSignedMimeMessage<span style="color: #008000;">&#40;</span>inputStream, outputStream, signedDkimHeader<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<h3>Computing the body hash</h3>

<p>The first step, computing the hash of the body, is actually pretty easy. There is only one quirk in that DKIM spec says that if the body ends with multiple empty lines, then the body should be normalized to just one terminating newline for the purposes of computing the hash. The code is not exciting, and you can download it at the end of this article.</p>

<h3>Creating the &#8220;unsigned&#8221; header</h3>

<p>The next step is to create the &#8220;unsigned&#8221; <code>DKIM-Signature</code> header. This is where the DKIM spec is just weird. The <code>DKIM-Signature</code> header contains a lot of information in it, such as the selector, domain, and the hashing algorithm (SHA1 or SHA256) being used. Since that information is vital to ensuring the integrity of the signature, it&#8217;s important that that information be a part of the DKIM signature.</p>

<p>If I were designing this, I would append two headers to e-mail messages: a <code>DKIM-Information</code> header that contained all of the above information and is part of the data that is signed and a <code>DKIM-Signature</code> header that contains just the signature data. But the DKIM spec makes use only the one <code>DKIM-Signature</code> header, and for the purposes of signing, we treat the &#8220;signature part&#8221; of the header (<code>b=</code>) as an empty string:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> GetUnsignedDkimHeader<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> bodyHash<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span>
        CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">InvariantCulture</span>,
        <span style="color: #666666;">&quot;DKIM-Signature: v=1; a={0}; s={1}; d={2}; c=simple/simple; q=dns/txt; h={3}; bh={4}; b=;&quot;</span>,
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">hashAlgorithmDkimCode</span>,
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">selector</span>,
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">domain</span>,
        <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Join</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot; : &quot;</span>, <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">eligibleHeaders</span><span style="color: #008000;">.</span><span style="color: #0000FF;">OrderBy</span><span style="color: #008000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> x, StringComparer<span style="color: #008000;">.</span><span style="color: #0000FF;">Ordinal</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ToArray</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>,
        bodyHash<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>You can see here that I&#8217;ve got some instance variables that were set in our <code>IDkimSigner</code> implementation&#8217;s constructor, such as the hash algorithm to use, the selector, domain, headers to include in the signature, and so on. We also insert our recently-computed hash of the body here.</p>

<p>You can also see that I&#8217;m using &#8220;simple&#8221; body canonicalization and &#8220;simple&#8221; header canonicalization. The DKIM spec gives us a few options in determining how the message is represented for signing and verification purposes. For the &#8220;simple&#8221; body canonicalization, it means &#8220;exactly as written, except for the weird rule about multiple newlines at the end of the body&#8221;. For the &#8220;simple&#8221; header canonicalization, it means &#8220;exactly as written, whitespace, newlines, and everything&#8221;.</p>

<p>There is a &#8220;relaxed&#8221; canonicalization method, but it&#8217;s more work, since you have to munge the headers and body into a very particular format, and I didn&#8217;t feel like writing a MIME parser.</p>

<h3>Extracting &#8220;canonicalized&#8221; headers</h3>

<p>The third step is to get a list of the canonicalized headers. In the constructor, I accept a list of headers to sign: <code>From</code>, <code>To</code>, <code>Message-ID</code>, and so on. (<code>From</code> is always required to be signed.) Then I use parsing code similar to that used in the <code>CanSign()</code> method and build a list of of the raw headers. The only real gotcha to watch out for is that headers can be wrapped onto more than one line, and since we&#8217;re using the &#8220;simple&#8221; canonicalization algorithm, we&#8217;ll need to preserve those whitespaces and newlines exactly as we extract them from the stream. Then I sort the headers alphabetically, since that&#8217;s how I specified them in the <code>GetUnsignedDkimHeader()</code> method specified above.</p>

<h3>Signing the message</h3>

<p>The logic behind signing the message is not that difficult. We smash all of the canonicalized headers together, add our unsigned <code>DKIM-Signature</code> header to the end, and compute our signature on this. Then we append the signature to the <code>b=</code> element, previously empty, of our <code>DKIM-Signature</code> header:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> GetSignedDkimHeader<span style="color: #008000;">&#40;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> unsignedDkimHeader,
    IEnumerable<span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span> canonicalizedHeaders<span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #6666cc; font-weight: bold;">byte</span><span style="color: #008000;">&#91;</span><span style="color: #008000;">&#93;</span> signatureBytes<span style="color: #008000;">;</span>
    <span style="color: #6666cc; font-weight: bold;">string</span> signatureText<span style="color: #008000;">;</span>
    StringBuilder signedDkimHeader<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var stream <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> MemoryStream<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var writer <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StreamWriter<span style="color: #008000;">&#40;</span>stream<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var canonicalizedHeader <span style="color: #0600FF; font-weight: bold;">in</span> canonicalizedHeaders<span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                writer<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span>canonicalizedHeader<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            <span style="color: #008000;">&#125;</span>
&nbsp;
            writer<span style="color: #008000;">.</span><span style="color: #0000FF;">Write</span><span style="color: #008000;">&#40;</span>unsignedDkimHeader<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            writer<span style="color: #008000;">.</span><span style="color: #0000FF;">Flush</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            stream<span style="color: #008000;">.</span><span style="color: #0000FF;">Seek</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span>, SeekOrigin<span style="color: #008000;">.</span><span style="color: #0000FF;">Begin</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            signatureBytes <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">cryptoProvider</span><span style="color: #008000;">.</span><span style="color: #0000FF;">SignData</span><span style="color: #008000;">&#40;</span>stream, <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">hashAlgorithmCryptoCode</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    signatureText <span style="color: #008000;">=</span> Convert<span style="color: #008000;">.</span><span style="color: #0000FF;">ToBase64String</span><span style="color: #008000;">&#40;</span>signatureBytes<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    signedDkimHeader <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> StringBuilder<span style="color: #008000;">&#40;</span>unsignedDkimHeader<span style="color: #008000;">.</span><span style="color: #0000FF;">Substring</span><span style="color: #008000;">&#40;</span><span style="color: #FF0000;">0</span>, unsignedDkimHeader<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">-</span> <span style="color: #FF0000;">1</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    signedDkimHeader<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span>signatureText<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    signedDkimHeader<span style="color: #008000;">.</span><span style="color: #0000FF;">Append</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;;<span style="color: #008080; font-weight: bold;">\r</span><span style="color: #008080; font-weight: bold;">\n</span>&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> signedDkimHeader<span style="color: #008000;">.</span><span style="color: #0000FF;">ToString</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>The only gotcha here, which I lost a few hours to, is a weird quirk of the .NET Framework 3.5 implementation of the <code>SignData()</code> function of the <code>RSACryptoServiceProvider</code> class. One of the overloads of the <code>SignData()</code> function accepts an instance of a <code>HashAlgorithm</code> to specify the kind of hash to use. The SHA-256 implementation was added in .NET 3.5 SP1, but it was done in such a way that an internal switch statement used internally by the .NET crypto classes wasn&#8217;t updated until .NET 4.0 to recognize the new <code>SHA256CryptoServiceProvider</code> type. <a href="http://blogs.msdn.com/b/shawnfa/archive/2008/08/25/using-rsacryptoserviceprovider-for-rsa-sha256-signatures.aspx">Some guy</a> blogs about why this is, but what it essentially means is that if you pass a <code>SHA256CryptoServiceProvider</code> instance to the <code>SignData()</code> method on .NET 2.0/3.0/3.5/3.5SP1, you get an exception, and on .NET 4.0 you don&#8217;t. Since Exchange 2007 uses .NET 3.5 SP1, we have to use the recommended workaround of using the overload that accepts a <code>string</code> representation of the hash algorithm.</p>

<h3>Writing out the message</h3>

<p>The last step is to write out the message with our newly created <code>DKIM-Signature</code> header. This really is a simple as taking the output stream, writing the <code>DKIM-Signature</code> header, and then dumping in the entire contents of the input stream.</p>

<h2>Getting a key to sign messages with</h2>

<p>Let us take a brief interlude from our DKIM circles of hell and obtain a key with which we will actually sign the <code>DKIM-Signature</code> header we&#8217;ve worked so hard to create.</p>

<p>We need to generate an RSA public/private key pair: a public key to store in DNS in the format required by the DKIM spec, and a private key to actually sign the messages with. <a href="http://www.port25.com/support/support_dkwz.php">The nice folks over at Port25 have a DKIM wizard that does exactly that.</a></p>

<p>It&#8217;s smashingly simple&#8211;just enter your domain name (say, &#8220;<code>example.com</code>&#8220;), a &#8220;selector&#8221; (say, &#8220;<code>key1</code>&#8220;), and select a key size (bigger is better, right?). The &#8220;selector&#8221; is a part of the DKIM spec that allows a single signing domain to use multiple keys. For example, you could use a key with selector name &#8220;newsletters&#8221; to sign all of the crap newsletter e-mails that you send out, and another key with selector name &#8220;tx&#8221; to sign all of the transactional e-mails that you send out.</p>

<p>It then spits out the syntax of the <code>TXT</code> records that you need to add to DNS for that selector:</p>

<p><pre>
key1._domainkey.example.com IN  TXT     "k=rsa\; p={BIG HONKING PUBLIC KEY HERE}"
_domainkey.example.com      IN  TXT     "t=y; o=~;"
</pre></p>

<p>The first record is where the public part of the key is stored. Whenever a mail transport agent sees one of our <code>DKIM-Signature</code> headers with a selector of <code>key1</code>, it&#8217;ll know to go hunting in DNS for a <code>TXT</code> record named <code>key1._domainkey.example.com</code> and pull the public key for verification from there.</p>

<p>The second record is part of the older DomainKeys specification and it is not strictly necessary. As written here, it means that we&#8217;re in testing mode (&#8220;t=y&#8221;)&#8211;that is, don&#8217;t freak out if you see a bad signature because we&#8217;re still dicking around with the setup of our implementation&#8211;and that not all messages originating from this domain will be signed (&#8220;o=~&#8221;)&#8211;maybe we won&#8217;t bother signing our newsletter e-mails, for example.</p>

<p>We&#8217;ll also have the private key specified in a format similar to the one below:</p>

<p><pre>
-----BEGIN RSA PRIVATE KEY-----
MIIBOwIBAAJBANXBbZybdmjKDTONFVqAWXmGzR6GSZX5LV3OF//1jRz7dzGWTCKK
jembqBxqhr0Y2ua2l4D4EZi6FwDmdqgLS6MCAwEAAQJAD4qhypovEM1oClB+tfbR
Cpn3ffmrjgDxAHoEmrKi0PGBn8fumW22bad2tmrAjWWTVmeXJvQyEy1awq0M2PMR
0QIhAPEnqivb5dKZbTeKhiF4c6IUHfwEq8wNf2LWZvdH3ROrAiEA4un604mDss4Q
qAVEx686pUttfWyJrYkcZ/tx7kOoL+kCICEysqyDAypw0KY6vahR6qk/V7lf8z6O
BSFYHqigDgEtAiEAsK9r5UcQSyv1AD+J/MpOqeJ/kMfwtDUs7zJ01gfMb/ECIQDg
8d/XVJDi4Cqbt4wfcHZxADAgqyK8Z5M69fBecnExVg==
-----END RSA PRIVATE KEY-----
</pre></p>

<p>One thing I have glossed over in the code discussion until now was how that <code>this.cryptoProvider</code> instance that actually computes the signature got created.</p>

<p>We&#8217;ll need to read this key and load it into the cryptography classes used by the .NET Framework and by Windows to actually sign mail messages and get that <code>this.cryptoProvider</code> instance. Surely there is a simple API for this, yes?</p>

<h3>Instancing a <code>CryptoProvider</code></h3>

<p>One problem is that the <a href="http://msdn.microsoft.com/en-us/library/aa380255%28v=vs.85%29.aspx">documentation in MSDN for the CryptoAPI is bad</a>. I say &#8220;bad&#8221; because it certainly seems like .NET and Windows don&#8217;t expose native support for processing a PEM-encoded key, and if it does, well, I couldn&#8217;t find the documentation for it. Instead, the <code>RSACryptoServiceProvider</code> prefers to store its keys in <a href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.rsa.fromxmlstring.aspx">an XML format that nothing else in the world seems to use</a>.</p>

<p>This means that our implementation is so close to being finished that we can almost taste it, but now we have to complete a side quest to actually read our damn key and get an instance of the <code>RSACryptoServiceProvider</code>. Or, we could generate a certificate ourselves and store it in the Certificates MMC snap-in, but why should we have to do that? I&#8217;d rather just plop the damn key in the application configuration file like the rest of the goddamned world does it, &#8220;secure container&#8221; my ass.</p>

<p><a href="http://www.jensign.com/opensslkey/opensslkey.cs">We can thank the moon and the stars that some guy has written a PEM reader for us</a>. How does it work? I have no idea, but I tested it on several keys and it seemed to work fine, which is good enough for me. I tossed this code into a static <code>CryptHelper</code> class, and now getting an instance of the <code>RSACryptoServiceProvider</code> is as simple as</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">cryptoProvider</span> <span style="color: #008000;">=</span> CryptHelper
     <span style="color: #008000;">.</span><span style="color: #0000FF;">GetProviderFromPemEncodedRsaPrivateKey</span><span style="color: #008000;">&#40;</span>encodedKey<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>


<h2>Loading the routing agent into Exchange Server 2007</h2>

<p>I took all of this code and then added boring administrative stuff like logging and moving some hardcoded values (such as the PEM-encoded key, the selector, and the domain) into the usual .NET <code>App.config</code> file mechanism.</p>

<p>Installing the agent on the Exchange Server is surprisingly simple. After compiling the project and futzing with the configuration file, we just copy the DLLs and configuration file to a folder on the Exchange Server, say, <code>C:\Program Files\Skiviez\Wolverine\DKIM Signer for Exchange\</code>.</p>

<p>Then we launch the Exchange Management Shell (remember to right-click it and &#8220;Run as Administrator&#8221;) and execute a command to tell Exchange to actually register our agent:</p>

<p><pre>
Install-TransportAgent
     -Name "DKIM Signer for Exchange"
     -TransportAgentFactory "Skiviez.Wolverine.Exchange.DkimSigner.DkimSigningRoutingAgentFactory"
     -AssemblyPath "C:\Program Files\Skiviez\Wolverine\DKIM Signer for Exchange\Skiviez.Wolverine.Exchange.DkimSigner.dll"
</pre></p>

<p>followed by</p>

<p><pre>
Enable-TransportAgent -Name "DKIM Signer for Exchange"
</pre></p>

<p>Interestingly, there will be a note telling you to close the Powershell window. It is not kidding. For some reason, the <code>Install-TransportAgent</code> cmdlet will keep a file handle open on our DLL, preventing Exchange from actually loading it until we close the Powershell window.</p>

<p>To make it actually work, we need to restart the Microsoft Exchange Transport service. I&#8217;ve found that restarting the Microsoft Exchange Mail Submission right after that is a good idea; otherwise, there can be a short delay of about 15 minutes before people&#8217;s Outlooks attempt to send outbound mail again.</p>

<h2>Testing the implementation</h2>

<p>To make sure things are actually working, Port25 comes to the rescue with their <a href="http://www.port25.com/domainkeys/">verification tool</a>. You just send an e-mail to <a href="mailto:check-auth@verifier.port25.com">check-auth@verifier.port25.com</a> and within a few minutes, they&#8217;ll send you an e-mail back with a boatload of debugging information. If it&#8217;s all good, you&#8217;ll see a result like the following:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">Summary of Results
SPF check:          pass
DomainKeys check:   neutral
DKIM check:         pass
Sender-ID check:    pass
SpamAssassin check: ham</pre></div></div>


<p>(What you&#8217;re looking for is the &#8220;pass&#8221; next to the DKIM check. The DomainKeys part being neutral is OK, since DomainKeys is the older standard and we&#8217;re choosing not to implement it.)</p>

<h2>Conclusions and Delusions</h2>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/12/works-on-my-machine.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/12/works-on-my-machine.png" alt="" title="Works On My Machine" width="200" height="193" class="alignright size-full wp-image-814" /></a></p>

<p>I&#8217;ve been using this code for a few weeks now and it seems to work fine&#8211;the messages that I&#8217;ve sent through the server to Port25 and my Yahoo! test account all end up showing the DKIM passing. The usual &#8220;it works on my machine!&#8221; disclaimers apply, however, as I&#8217;m sure there are myriad configuration differences in Exchange that could this not to work. Bug fixes are welcome, but don&#8217;t come crying if it sends all of your e-mail to that big junk folder in the sky.</p>

<p>And thanks to some blowhards at Yahoo!, the world now has a public domain implementation of DKIM signing for Exchange to play with.</p>

<p>And in case you&#8217;re curious&#8211;after doing all this work to set up DKIM and participate in the Complaint Feedback Loop at their suggestion&#8211;their answer is still &#8220;no,&#8221; without elaboration. When Yahoo! finally goes under, I won&#8217;t be one shedding a nostalgic tear.</p>

<p>There are some unit tests, but they do have our private key in them, and I couldn&#8217;t be bothered to siphon those out. The code below is just the bits that do the actual signing.</p>

<p><a href='http://nicholas.piasecki.name/blog/wp-content/uploads/2010/12/DkimSigner.zip'>Download the code used in this article.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2010/12/dkim-signing-outbound-messages-in-exchange-server-2007/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>Inside Skiviez: Mailing Addresses</title>
		<link>http://nicholas.piasecki.name/blog/2010/11/inside-skiviez-mailing-addresses/</link>
		<comments>http://nicholas.piasecki.name/blog/2010/11/inside-skiviez-mailing-addresses/#comments</comments>
		<pubDate>Wed, 24 Nov 2010 16:27:44 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[design]]></category>
		<category><![CDATA[skiviez]]></category>
		<category><![CDATA[web stuff]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=714</guid>
		<description><![CDATA[Skiviez ships to about two dozen countries around the world. This means that our e-commerce system has to be able to accept and deal with international addresses. For a long time, Skiviez dealt with this problem in a way that &#8230; <a href="http://nicholas.piasecki.name/blog/2010/11/inside-skiviez-mailing-addresses/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.skiviez.com/">Skiviez</a> ships to about <a href="http://www.skiviez.com/underwear.aspx/pages/shipping-rates/us">two dozen countries</a> around the world. This means that our e-commerce system has to be able to accept and deal with international addresses.</p>

<p>For a long time, Skiviez dealt with this problem in a way that I would say the vast majority of US-based e-commerce based retailers dealt with it: they added a country dropdown, turned the State field into a textbox, and made the State field no longer required. And if you are not obsessive compulsive like I am, then this works reasonably well enough: international customers have to shoehorn their address into the format presented, but the data can still get in there.</p>

<p>However, after 10 years in operation, this approach was beginning to show some deficiencies:</p>

<p><strong>Magnetic attraction.</strong> There is, for lack of a better term, a magnetic attraction between users and text boxes. Even if the field is not required, users have a tendency to enter &#8220;N/A&#8221;, &#8220;.&#8221;, &#8220;?&#8221;, &#8220;none&#8221;, or some other placeholder value in fields that do not apply to them.</p>

<p><strong>Address quality problems.</strong> With the above method, the bumpers are off&#8211;a user could type &#8220;cheese&#8221; into the postal code field, and we&#8217;d just have to accept it on their word that &#8220;cheese&#8221; is a valid postal code for the United Kingdom because the site wasn&#8217;t doing any sort of validation except for United States-based addresses. Shipping a parcel to another country only to have it returned or destroyed as a result of an invalid or insufficient address is an expensive issue.</p>

<p><strong>Integration issues.</strong> To actually ship out international packages, we have to do deal with third-party carrier APIs (such as Endicia, FedEx, and UPS) to purchase postage and print shipping labels. Some of these APIs do perform more advanced validation on international addresses. This could cause problems because a poorly formatted address would make it nearly all of the way through our fulfillment process&#8211;order acceptance, picking, processing, and packaging&#8211;only to blow up with an error at the shipping desk. It&#8217;d be nice if we could catch problems earlier to avoid disrupting the shipping flow and eliminate the potential for misrouting the package.</p>

<h2>A smarter system</h2>

<p>With the October 2010 release of the Skiviez Web site (which was a pretty huge update), the Web site is now much, much smarter in how it asks for address information. For example, here&#8217;s the default address form for the United States, which is about what you&#8217;d expect:</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-22-2010-6-39-23-PM.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-22-2010-6-39-23-PM.png" alt="" title="United States Address Input" width="426" height="534" class="aligncenter size-full wp-image-728" /></a></p>

<p>But if you choose, say, Ireland in the countries drop down, the page refreshes and displays a new form:</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-22-2010-6-40-52-PM.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-22-2010-6-40-52-PM.png" alt="" title="Ireland Address Input" width="430" height="473" class="aligncenter size-full wp-image-729" /></a></p>

<p>The state drop down is gone (since Ireland doesn&#8217;t have states), the ZIP/postal code text box is gone (since Ireland does not use postal codes), and a new County text box is available.</p>

<p>Once an address is entered, it is formatted in the way a person native to that country would expect. For example, in a German address, the postal code comes before the city:</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-22-2010-6-49-33-PM.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-22-2010-6-49-33-PM.png" alt="" title="German Address Formatting" width="262" height="135" class="aligncenter size-full wp-image-731" /></a></p>

<p>Taking it even further, if you select, say, Finland from the drop down, you get a form back that looks like this:</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-22-2010-6-46-10-PM.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-22-2010-6-46-10-PM.png" alt="" title="Finland Address Input" width="425" height="482" class="aligncenter size-full wp-image-730" /></a></p>

<p>The postal code validates against the postal code format used in Finland, and that field appears before the Municipality field, since the convention throughout most of the EU is to write &#8220;{Postal Code} {City}&#8221; instead of the American &#8220;{City} {State} {Postal Code}&#8221; way.</p>

<p>Clearly, we&#8217;ve made a lot of improvements to address handling at Skiviez, and this simple input format actually has <em>a lot</em> of complexity behind it. So how does it all work?</p>

<h2>Tweaking the existing database schema</h2>

<p>At Skiviez, we were clearly working from a legacy database schema. The customer addresses table has been sitting there for 10 years, and we&#8217;re not about to change it any time soon. And while there is some internal cruft, the fields in the database more or less looked like the following:</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/Fields.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/Fields.png" alt="" title="Original Fields" width="169" height="396" class="aligncenter size-full wp-image-717" /></a></p>

<p>This is a normal, relational schema. So how do we enhance this table so that it can store addresses from the dozens of countries that we ship to? That sounds like a tall order: surely the addresses of the world are all wildly different from one another, and we&#8217;ll have to go <a href="http://en.wikipedia.org/wiki/Entity-attribute-value_model">entity-attribute-value</a>, throwing away the relational bit of our relational data store, to be able to accurately store this diverse information, right?</p>

<p>Well, it turns out that you can take these existing fields, relax away any <code>NOT NULL</code> constraints, and rename them to field names that are operating at a higher level of abstraction. (We didn&#8217;t actually rename the fields in the database, as this would have broken old code, but the new field names do exist in the object model, described later.)</p>

<p>In other words, you can shoehorn most of the addresses in the world (most importantly, the ones that Skiviez ships to), by just thinking of the existing fields in these terms:</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/fields2.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/fields2.png" alt="" title="Renamed Fields" width="434" height="424" class="aligncenter size-full wp-image-718" /></a></p>

<p>Nothing has really changed. We&#8217;re just making the concession that it&#8217;s OK that the meaning of the data within these fields will change slightly depending on the country we&#8217;re talking about. In the United States, the &#8220;AdministrativeArea&#8221; is the state, territory, or military post office. In Ireland, the &#8220;AdministrativeArea&#8221; is the county. And in Finland, the &#8220;AdministrativeArea&#8221; is <code>NULL</code> because it simply isn&#8217;t used at all.</p>

<h2>Creating a sane object model</h2>

<p>There is something wrong with the database schema, though, and for the sake of preserving legacy code and data, I worked around it in the new object model that is persisted to this schema. The problem is as follows:</p>

<p><strong>A mailing address is not the same as a contact.</strong></p>

<p>Frequently while coding over the years, I found myself wanting to deal with a physical address when I didn&#8217;t have any related contact information. That is, I had a group of data for <code>123 Main St; Richmond, VA 23221; United States</code>, but I didn&#8217;t know who lived there or what the phone number was. The only object I had in my model was an <code>Address</code> object that was a 1-1 mapping with the old database schema, so this meant having <code>Address</code> instances with a <code>null</code> name and a <code>null</code> phone number.</p>

<p>A more natural model is to split the fields into three objects and create a fourth object that is composed of all of them:</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/diagram.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/diagram.png" alt="" title="Basic Object Model" width="648" height="470" class="aligncenter size-full wp-image-721" /></a></p>

<p>So instead of one big honking <code>Address</code> object, we have</p>

<ul>
<li>an <code>Address</code> object that just contains physical address information;</li>
<li>a <code>Country</code> object (not shown in the above diagram) that contains information necessary to format and validate an address (more on this later);</li>
<li>a <code>PersonalName</code> object that binds all of the name fields together;</li>
<li>a <code>Contact</code> object that groups together a <code>PersonalName</code>, an optional company name string, and a <code>PhoneNumberBase</code> object; and</li>
<li>a <code>MailingAddress</code> object that pairs a <code>Contact</code> with an <code>Address</code>.</li>
</ul>

<p>By splitting the old <code>Address</code> object into these individual components, I can now freely re-use these components elsewhere in the application. For example, the <code>PersonalName</code> object also gets used in the <code>Customer</code> object. The return form generator expects a <code>MailingAddress</code> object, but a shipping rate calculator can deal with an <code>Address</code> object directly, since the latter has no need for the <code>Contact</code> information. In other words, the object model went from coarse-grained to fine-grained.</p>

<p>But perhaps the most important aspect of this model is that each of the four above classes is <strong>immutable</strong>.</p>

<h2>Why are immutable addressing objects better?</h2>

<p>When an object is immutable, it can&#8217;t be altered after it is first instanced. In other words, everything about the object is permanently set at construction time; its instance methods won&#8217;t mutate the object, and its properties don&#8217;t have public setters. In domain driven design, this is often referred to as a value type, but I don&#8217;t like that terminology as it can cause some confusion with value-vs-reference types in the .NET Framework.</p>

<p>This means that if I have an instance of an <code>Address</code> and want to edit the <code>PostalCode</code> property, then I will need to create a brand new instance of an <code>Address</code>, copy most of the properties over, and set my new postal code at construction time.</p>

<p>There are a few advantages to this approach:</p>

<ul>
<li>The instance can validate itself once at construction time. This can be a big win if validation is particularly complex and dependent on the values of other properties (which is exactly what happens in an address, since the country determines whether or not a field is required and what format it needs to be in). If anything else is referencing that <code>Address</code> instance, then it can assume that that instance won&#8217;t get put into an invalid state. For example, a <code>SalesOrder</code> has a <code>ShippingAddress</code> property that takes a <code>MailingAddress</code> instance. The <code>SalesOrder</code> doesn&#8217;t have to worry about someone coming along and saying <code>ShippingAddress.PostalCode = null</code> at some point, bypassing any validation checks. The whole <code>ShippingAddress</code> instance would have to be replaced, which means building a new <code>Address</code> instance, which means running the validation logic built into the address builder.</li>
<li>The hash code of the instance is consistent throughout the object&#8217;s lifetime. This is useful for modeling an address property as a component in NHibernate, which I won&#8217;t get into here.</li>
</ul>

<p>But a big disadvantage to this approach is that it can be tedious to deal with in code. At face level, this means that our <code>Address</code> object would need a gigantic constructor or support an <code>IFreezable</code>-type of implementation. A cleaner way is to use <a href="http://en.wikipedia.org/wiki/Builder_pattern">the builder pattern</a> to allow us to set the fields in any order and validate the <code>Address</code> in one shot:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var country <span style="color: #008000;">=</span> CountryMother<span style="color: #008000;">.</span><span style="color: #0000FF;">UnitedStates</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> Address<span style="color: #008000;">.</span><span style="color: #0000FF;">Builder</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithPrimaryStreetLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;3005 SOME ST&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithMunicipality</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;RICHMOND&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithAdministrativeArea</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;VIRGINIA&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithPostalCode</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;23221&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithCountry</span><span style="color: #008000;">&#40;</span>country<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">Build</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span> <span style="color: #008080; font-style: italic;">// exception thrown here if validation errors</span></pre></div></div>


<p>If we want to get a list of detailed validation problems instead of throwing an exception, the builder provides a mechanism for that:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var country <span style="color: #008000;">=</span> CountryMother<span style="color: #008000;">.</span><span style="color: #0000FF;">UnitedStates</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var builder <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Address<span style="color: #008000;">.</span><span style="color: #0000FF;">Builder</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithPrimaryStreetLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;3005 SOME ST&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithMunicipality</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;RICHMOND&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithAdministrativeArea</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;VIRGINIA&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithPostalCode</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;23221&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithCountry</span><span style="color: #008000;">&#40;</span>country<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
var results <span style="color: #008000;">=</span> builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Validate</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>results<span style="color: #008000;">.</span><span style="color: #0000FF;">Any</span><span style="color: #008000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">!</span>x<span style="color: #008000;">.</span><span style="color: #0000FF;">Success</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>var error <span style="color: #0600FF; font-weight: bold;">in</span> results<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Where</span><span style="color: #008000;">&#40;</span>x <span style="color: #008000;">=&gt;</span> <span style="color: #008000;">!</span>x<span style="color: #008000;">.</span><span style="color: #0000FF;">Success</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        Console<span style="color: #008000;">.</span><span style="color: #0000FF;">WriteLine</span><span style="color: #008000;">&#40;</span>
            <span style="color: #666666;">&quot;Field {0}, Error {1}&quot;</span>,
            error<span style="color: #008000;">.</span><span style="color: #0000FF;">Field</span>,
            error<span style="color: #008000;">.</span><span style="color: #0000FF;">Message</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
<span style="color: #0600FF; font-weight: bold;">else</span>
<span style="color: #008000;">&#123;</span>
    var instance <span style="color: #008000;">=</span> builder<span style="color: #008000;">.</span><span style="color: #0000FF;">Build</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>This allows the user interface to be able to get to detailed error messages pretty easily. But how does that call to <code>Validate()</code> work? How does the builder really know what format an address should be in?</p>

<h2>Validation</h2>

<p>We need to define a way for a <code>Country</code> to know how its mailing addresses need to be formatted. Since we have all countries of the world in our database, but we don&#8217;t ship to all countries in the world, I created a nullable property on the <code>Country</code> object called <code>Scheme</code>. The <code>Scheme</code> is an instance of the <code>AddressScheme</code> class and it&#8217;s persisted to the database along with the country.</p>

<p>If we try to build an address without a country specified or with a country that doesn&#8217;t have an <code>AddressScheme</code>, then we throw an exception saying that we just can&#8217;t do that. Otherwise, our <code>Validate()</code> method will run through a list of the <code>AddressFieldRule</code>s that are contained within the <code>AddressScheme</code> instance, calling the <code>Validate(string)</code> method on the rule for a particular field.</p>

<p>To be able to easily persist these rules in the database, I created an <code>enum</code> that parallels the generic properties of the <code>Address</code> class that we defined earlier:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">enum</span> AddressField <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">int</span>
<span style="color: #008000;">&#123;</span>
    Unknown <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
    AdministrativeArea <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
    Country <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
    Municipality <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
    PostalCode <span style="color: #008000;">=</span> <span style="color: #FF0000;">4</span>,
    PrimaryStreetLine <span style="color: #008000;">=</span> <span style="color: #FF0000;">5</span>,
    SecondaryStreetLine <span style="color: #008000;">=</span> <span style="color: #FF0000;">6</span>,
    SubAdministrativeArea <span style="color: #008000;">=</span> <span style="color: #FF0000;">7</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>Internally, the <code>Address</code> object maintains its state via a <code>Hashtable</code> of fields, where the key is the <code>AddressField</code> enumerated value and the value is an object, usually <code>string</code> but sometimes a <code>Country</code>. The properties of the <code>Address</code> object are really just strongly-typed convenience mappings onto that <code>Hashtable</code> as in the following example:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">string</span> AdministrativeArea
<span style="color: #008000;">&#123;</span>
	get
	<span style="color: #008000;">&#123;</span>
		<span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#91;</span>AddressField<span style="color: #008000;">.</span><span style="color: #0000FF;">AdministrativeArea</span><span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">private</span> set
	<span style="color: #008000;">&#123;</span>
		<span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">&#91;</span>AddressField<span style="color: #008000;">.</span><span style="color: #0000FF;">AdministrativeArea</span><span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>The implementation of the <code>AddressFieldRule</code> is fairly straightforward. I provide the capability to validate against a regular expression (such as might happen with a postal code field), to simply consider the field required (such as might happen with a city field), and to ensure that the value is a member of a list of a predefined list of values (such as might happen with a province field). The <code>Validate(string)</code> method figures out which rules to apply based on the properties that are set and returns an <code>AddressFieldRuleValidationResult</code> that describes what went right and what went wrong.</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
<span style="color: #008080; font-style: italic;">/// Describes a requirement for an address field for a particular address.</span>
<span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> AddressFieldRule
<span style="color: #008000;">&#123;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// The list of allowed values; this may be null if no particular set of</span>
    <span style="color: #008080; font-style: italic;">/// values is required.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> IEnumerable<span style="color: #008000;">&lt;</span>addressFieldAllowedValue<span style="color: #008000;">&gt;</span> allowedValues<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// The description of the field and its format.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> description<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// The address field.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> AddressField field<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Whether or not the field is required.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">bool</span> isRequired<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// The localized name.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> name<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// An optional validation regular expression template.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> validationRegex<span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Initializes a new instance of the &lt;see cref=&quot;AddressFieldRule&quot;/&gt; class.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;field&quot;&gt;The field.&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;isRequired&quot;&gt;if set to &lt;c&gt;true&lt;/c&gt; [is required].&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;name&quot;&gt;English, localized name for the field. Required.&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;description&quot;&gt;The english description.&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;validationRegex&quot;&gt;The validation regex. Optional.&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;allowedValues&quot;&gt;The allowed values. Optional; if null, then</span>
    <span style="color: #008080; font-style: italic;">/// no particular set of values is required.&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;T:System.ArgumentNullException&quot;&gt;if the englishName is null</span>
    <span style="color: #008080; font-style: italic;">/// or empty&lt;/exception&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;exception cref=&quot;T:System.ArgumentOutOfRangeException&quot;&gt;if the address field</span>
    <span style="color: #008080; font-style: italic;">/// is not in a valid range&lt;/exception&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> AddressFieldRule<span style="color: #008000;">&#40;</span>
        AddressField field,
        <span style="color: #6666cc; font-weight: bold;">bool</span> isRequired,
        <span style="color: #6666cc; font-weight: bold;">string</span> name,
        <span style="color: #6666cc; font-weight: bold;">string</span> description,
        <span style="color: #6666cc; font-weight: bold;">string</span> validationRegex,
        IEnumerable<span style="color: #008000;">&lt;</span>addressFieldAllowedValue<span style="color: #008000;">&gt;</span> allowedValues<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #008000;">&#40;</span>name<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentNullException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;name&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #6666cc; font-weight: bold;">Enum</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsDefined</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>AddressField<span style="color: #008000;">&#41;</span>, field<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentOutOfRangeException<span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;field&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #008000;">&#40;</span>validationRegex<span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span>
            allowedValues <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">&amp;&amp;</span>
            allowedValues<span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">throw</span> <span style="color: #008000;">new</span> ArgumentException<span style="color: #008000;">&#40;</span>
                <span style="color: #666666;">&quot;The ValidationRegex and the AllowedValues options are mutually exclusive.&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">field</span> <span style="color: #008000;">=</span> field<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">description</span> <span style="color: #008000;">=</span> description<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">isRequired</span> <span style="color: #008000;">=</span> isRequired<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">name</span> <span style="color: #008000;">=</span> name<span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">allowedValues</span> <span style="color: #008000;">=</span> allowedValues <span style="color: #008000;">??</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>addressFieldAllowedValue<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">validationRegex</span> <span style="color: #008000;">=</span> validationRegex<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Initializes a new instance of the &lt;see cref=&quot;AddressFieldRule&quot;/&gt; class.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">protected</span> AddressFieldRule<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Gets values that, if not empty, then the address field value</span>
    <span style="color: #008080; font-style: italic;">/// should be one of the membersin the First property of each of these</span>
    <span style="color: #008080; font-style: italic;">/// Pairs. The Second property, if</span>
    <span style="color: #008080; font-style: italic;">/// set, is an alternative name that could be displayed in a dropdown to</span>
    <span style="color: #008080; font-style: italic;">/// the user.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> IEnumerable<span style="color: #008000;">&lt;</span>addressFieldAllowedValue<span style="color: #008000;">&gt;</span> AllowedValues
    <span style="color: #008000;">&#123;</span>
        get
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">allowedValues</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> set
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">allowedValues</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Gets a human-readable string that describes the required format for the</span>
    <span style="color: #008080; font-style: italic;">/// field. It may give an example, such as &quot;JYX 938&quot;.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">string</span> Description
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">description</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> set <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">description</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Gets the field that this metadata describes.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> AddressField Field
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">field</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> set <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">field</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Gets a value indicating whether or not the field must be</span>
    <span style="color: #008080; font-style: italic;">/// included in the address.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">bool</span> IsRequired
    <span style="color: #008000;">&#123;</span>
        get
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">isRequired</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> set
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">isRequired</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Gets an English, localized name for the field. For example, the</span>
    <span style="color: #008080; font-style: italic;">/// StateOrProvince field has a name of &quot;Province or Territory&quot; for</span>
    <span style="color: #008080; font-style: italic;">/// Canadian addresses.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">string</span> Name
    <span style="color: #008000;">&#123;</span>
        get <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">name</span><span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
        <span style="color: #0600FF; font-weight: bold;">private</span> set <span style="color: #008000;">&#123;</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">name</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span> <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Gets an optional validation regular expression template, which may</span>
    <span style="color: #008080; font-style: italic;">/// be null.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> <span style="color: #6666cc; font-weight: bold;">string</span> ValidationRegex
    <span style="color: #008000;">&#123;</span>
        get
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">validationRegex</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">private</span> set
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">validationRegex</span> <span style="color: #008000;">=</span> value<span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Gets or sets the data store identifier for the rule.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">int</span><span style="color: #008000;">?</span> Identity
    <span style="color: #008000;">&#123;</span>
        get<span style="color: #008000;">;</span>
        set<span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #008080; font-style: italic;">/// &lt;summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// Validates the value.</span>
    <span style="color: #008080; font-style: italic;">/// &lt;/summary&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;param name=&quot;value&quot;&gt;The value to validate.&lt;/param&gt;</span>
    <span style="color: #008080; font-style: italic;">/// &lt;returns&gt;The validation result.&lt;/returns&gt;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #0600FF; font-weight: bold;">virtual</span> AddressFieldRuleValidationResult Validate<span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> value<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">&#40;</span>value <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span> <span style="color: #008000;">||</span> value<span style="color: #008000;">.</span><span style="color: #0000FF;">Trim</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">==</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsRequired</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            var message <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span>
                CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentCulture</span>,
                <span style="color: #666666;">&quot;The field '{0}' is required, but the value was empty or blank.&quot;</span>,
                <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> AddressFieldRuleValidationResult<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                Field <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Field</span>,
                Original <span style="color: #008000;">=</span> value,
                Message <span style="color: #008000;">=</span> message
            <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>value <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            var input <span style="color: #008000;">=</span> value<span style="color: #008000;">.</span><span style="color: #0000FF;">Trim</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>input<span style="color: #008000;">.</span><span style="color: #0000FF;">Length</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #008000;">!</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ValidationRegex</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span>
                    <span style="color: #008000;">!</span>Regex<span style="color: #008000;">.</span><span style="color: #0000FF;">IsMatch</span><span style="color: #008000;">&#40;</span>input, <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ValidationRegex</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    var message <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span>
                        CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentCulture</span>,
                        <span style="color: #666666;">&quot;The field '{0}' has an unexpected or incorrectly formatted value.&quot;</span>,
                        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                    <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> AddressFieldRuleValidationResult<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                    <span style="color: #008000;">&#123;</span>
                        Field <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Field</span>,
                        Original <span style="color: #008000;">=</span> value,
                        Message <span style="color: #008000;">=</span> message
                    <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
                <span style="color: #008000;">&#125;</span>
&nbsp;
                <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AllowedValues</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Count</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&gt;</span> <span style="color: #FF0000;">0</span><span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    <span style="color: #6666cc; font-weight: bold;">string</span> preferred<span style="color: #008000;">;</span>
&nbsp;
                    <span style="color: #008080; font-style: italic;">// If an alternative value is detected, select the preferred.</span>
                    var alternativeAllowedValue <span style="color: #008000;">=</span>
                        <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">from</span> av <span style="color: #0600FF; font-weight: bold;">in</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AllowedValues</span>
                            <span style="color: #0600FF; font-weight: bold;">where</span> <span style="color: #008000;">!</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">IsNullOrEmpty</span><span style="color: #008000;">&#40;</span>av<span style="color: #008000;">.</span><span style="color: #0000FF;">Alternative</span><span style="color: #008000;">&#41;</span> <span style="color: #008000;">&amp;&amp;</span>
                            av<span style="color: #008000;">.</span><span style="color: #0000FF;">Alternative</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Equals</span><span style="color: #008000;">&#40;</span>input, StringComparison<span style="color: #008000;">.</span><span style="color: #0000FF;">OrdinalIgnoreCase</span><span style="color: #008000;">&#41;</span>
                            <span style="color: #0600FF; font-weight: bold;">select</span> av<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">SingleOrDefault</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>alternativeAllowedValue <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
                    <span style="color: #008000;">&#123;</span>
                        <span style="color: #008080; font-style: italic;">// We matched an alternative value, so let's use the</span>
                        <span style="color: #008080; font-style: italic;">// corresponding primary value</span>
                        preferred <span style="color: #008000;">=</span> alternativeAllowedValue<span style="color: #008000;">.</span><span style="color: #0000FF;">Preferred</span><span style="color: #008000;">;</span>
&nbsp;
                        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> AddressFieldRuleValidationResult<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                        <span style="color: #008000;">&#123;</span>
                            Field <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Field</span>,
                            Original <span style="color: #008000;">=</span> value,
                            Preferred <span style="color: #008000;">=</span> preferred,
                            Success <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span>
                        <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
                    <span style="color: #008000;">&#125;</span>
                    <span style="color: #0600FF; font-weight: bold;">else</span>
                    <span style="color: #008000;">&#123;</span>
                        <span style="color: #008080; font-style: italic;">// Search on the primary value, then.</span>
                        var primaryAllowedValue <span style="color: #008000;">=</span>
                            <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">from</span> av <span style="color: #0600FF; font-weight: bold;">in</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AllowedValues</span>
                                <span style="color: #0600FF; font-weight: bold;">where</span> av<span style="color: #008000;">.</span><span style="color: #0000FF;">Preferred</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Equals</span><span style="color: #008000;">&#40;</span>input, StringComparison<span style="color: #008000;">.</span><span style="color: #0000FF;">OrdinalIgnoreCase</span><span style="color: #008000;">&#41;</span>
                                <span style="color: #0600FF; font-weight: bold;">select</span> av<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">SingleOrDefault</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                        <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>primaryAllowedValue <span style="color: #008000;">!=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
                        <span style="color: #008000;">&#123;</span>
                            <span style="color: #008080; font-style: italic;">// We matched the primary value, let's re-assign</span>
                            <span style="color: #008080; font-style: italic;">// it to get the correct casing</span>
                            preferred <span style="color: #008000;">=</span> primaryAllowedValue<span style="color: #008000;">.</span><span style="color: #0000FF;">Preferred</span><span style="color: #008000;">;</span>
&nbsp;
                            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> AddressFieldRuleValidationResult<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                            <span style="color: #008000;">&#123;</span>
                                Field <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Field</span>,
                                Original <span style="color: #008000;">=</span> value,
                                Preferred <span style="color: #008000;">=</span> preferred,
                                Success <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span>
                            <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
                        <span style="color: #008000;">&#125;</span>
                        <span style="color: #0600FF; font-weight: bold;">else</span>
                        <span style="color: #008000;">&#123;</span>
                            var message <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span>
                                CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">CurrentCulture</span>,
                                <span style="color: #666666;">&quot;The field '{0}' was not in the list of expected values.&quot;</span>,
                                <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Name</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
                            <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> AddressFieldRuleValidationResult<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
                            <span style="color: #008000;">&#123;</span>
                                Field <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Field</span>,
                                Original <span style="color: #008000;">=</span> value,
                                Message <span style="color: #008000;">=</span> message
                            <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
                        <span style="color: #008000;">&#125;</span>
                    <span style="color: #008000;">&#125;</span>
                <span style="color: #008000;">&#125;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> AddressFieldRuleValidationResult<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            Field <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Field</span>,
            Original <span style="color: #008000;">=</span> value,
            Preferred <span style="color: #008000;">=</span> value,
            Success <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">true</span>
        <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>(In the case of a state or province field, where we ensure that the value belongs to a predefined list of <code>AddressFieldAllowedValue</code>s, we also let the rule tell the consumer which value is &#8220;preferred.&#8221; For example, a user might enter &#8220;Virginia&#8221;, but the system will spit back &#8220;VA&#8221; as the preferred formatting for that value.)</p>

<p>As a result, that <code>Validate()</code> method on the builder doesn&#8217;t have to do much heavy lifting:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> IEnumerable<span style="color: #008000;">&lt;</span>addressFieldRuleValidationResult<span style="color: #008000;">&gt;</span> Validate<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
    var failures <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> List<span style="color: #008000;">&lt;</span>addressFieldRuleValidationResult<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">address</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Country</span> <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        var result <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> AddressFieldRuleValidationResult<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            Field <span style="color: #008000;">=</span> AddressField<span style="color: #008000;">.</span><span style="color: #0000FF;">Country</span>,
            Message <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;The country is required.&quot;</span>
        <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
        failures<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>result<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">else</span> <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">address</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Country</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AddressScheme</span> <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        var result <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> AddressFieldRuleValidationResult<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            Field <span style="color: #008000;">=</span> AddressField<span style="color: #008000;">.</span><span style="color: #0000FF;">Country</span>,
            Message <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;The country must have an address scheme.&quot;</span>
        <span style="color: #008000;">&#125;</span><span style="color: #008000;">;</span>
&nbsp;
        failures<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>result<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
    <span style="color: #008000;">&#125;</span>
    <span style="color: #0600FF; font-weight: bold;">else</span>
    <span style="color: #008000;">&#123;</span>
        var scheme <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">address</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Country</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AddressScheme</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span>AddressField field <span style="color: #0600FF; font-weight: bold;">in</span> <span style="color: #008000;">new</span> ArrayList<span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">address</span><span style="color: #008000;">.</span><span style="color: #0000FF;">fields</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Keys</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>field <span style="color: #008000;">!=</span> AddressField<span style="color: #008000;">.</span><span style="color: #0000FF;">Country</span> <span style="color: #008000;">&amp;&amp;</span>
                field <span style="color: #008000;">!=</span> AddressField<span style="color: #008000;">.</span><span style="color: #0000FF;">Unknown</span><span style="color: #008000;">&#41;</span>
            <span style="color: #008000;">&#123;</span>
                <span style="color: #008080; font-style: italic;">// If the field is not Country or Unknown, let's</span>
                <span style="color: #008080; font-style: italic;">// see if the scheme has a rule defined for it.</span>
                <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>scheme<span style="color: #008000;">.</span><span style="color: #0000FF;">HasRuleFor</span><span style="color: #008000;">&#40;</span>field<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
                <span style="color: #008000;">&#123;</span>
                    <span style="color: #008080; font-style: italic;">// Since a rule is defined, let's validate the field.</span>
                    var result <span style="color: #008000;">=</span> scheme<span style="color: #008000;">.</span><span style="color: #0000FF;">ValidateField</span><span style="color: #008000;">&#40;</span>field, <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">address</span><span style="color: #008000;">&#91;</span>field<span style="color: #008000;">&#93;</span> <span style="color: #0600FF; font-weight: bold;">as</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                    <span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>result<span style="color: #008000;">.</span><span style="color: #0000FF;">Success</span><span style="color: #008000;">&#41;</span>
                    <span style="color: #008000;">&#123;</span>
                        <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">address</span><span style="color: #008000;">&#91;</span>field<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> result<span style="color: #008000;">.</span><span style="color: #0000FF;">Preferred</span><span style="color: #008000;">;</span>
                    <span style="color: #008000;">&#125;</span>
                    <span style="color: #0600FF; font-weight: bold;">else</span>
                    <span style="color: #008000;">&#123;</span>
                        failures<span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>result<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
                    <span style="color: #008000;">&#125;</span>
                <span style="color: #008000;">&#125;</span>
                <span style="color: #0600FF; font-weight: bold;">else</span>
                <span style="color: #008000;">&#123;</span>
                    <span style="color: #008080; font-style: italic;">// No rule is defined, so strip the data out of the</span>
                    <span style="color: #008080; font-style: italic;">// address.</span>
                    <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">address</span><span style="color: #008000;">&#91;</span>field<span style="color: #008000;">&#93;</span> <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">;</span>
                <span style="color: #008000;">&#125;</span>
            <span style="color: #008000;">&#125;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
&nbsp;
    <span style="color: #0600FF; font-weight: bold;">return</span> failures<span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>Where do all of these address rules come from? There is nothing more valuable than <a href="http://www.columbia.edu/kermit/postal.html">Frank&#8217;s Compulsive Guide to Postal Addresses</a>.</p>

<h2>Formatting</h2>

<p>Another important property on the <code>AddressScheme</code> is the <code>Formatter</code>. This is an object that knows how to format an address for a particular country. The <code>ToString()</code> implementation on the <code>Address</code> can then just call <code>this.Country.Formatter.Format("M", this)</code> to get a string back that contains the correctly formatted address, where &#8220;M&#8221; is our <code>IFormattable</code> code for an address format that includes newlines.</p>

<p>My <code>AddressFormatter</code> object works by taking a template string that is loaded from the database. The template format is pretty simple: it&#8217;s a combination of the <code>AddressField</code> enumerated values (delimited by braces) and the semicolon (which indicates separate lines of the address). For example, the template for a German address is specified as:</p>

<p><pre>{PrimaryStreetLine};{SecondaryStreetLine};DE-{PostalCode}  {Municipality};{Country}</pre></p>

<p>Given an &#8220;S&#8221; format code (for &#8220;single-line output&#8221;), we&#8217;ll substitute the values and leave the semicolons. Given an &#8220;M&#8221; format code (for &#8220;mailing output&#8221;), we&#8217;ll substitute the values and swap the semicolons with newlines. We also remove any contiguous separators that might happen, such as when the <code>SecondaryStreetLine</code> is blank, to avoid having a blank line in the address.</p>

<p>So given an address that was built as</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;">var country <span style="color: #008000;">=</span> CountryMother<span style="color: #008000;">.</span><span style="color: #0000FF;">Germany</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">return</span> <span style="color: #008000;">new</span> Address<span style="color: #008000;">.</span><span style="color: #0000FF;">Builder</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithPrimaryStreetLine</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;42 Kaiserstrasse&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithMunicipality</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Berlin&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithPostalCode</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;12345&quot;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">WithCountry</span><span style="color: #008000;">&#40;</span>country<span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">.</span><span style="color: #0000FF;">Build</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span></pre></div></div>


<p>our formatter, given a format code of &#8220;M&#8221;, will spit out</p>

<p><pre>
42 Kaiserstrasse
DE-12345 Berlin
Germany
</pre></p>

<p>Since the address object is immutable, we know it&#8217;s valid, so the formatter doesn&#8217;t have to worry about handling a potentially invalid address object.</p>

<p>The user interface of the Web site also uses the template to figure what input fields to display and what order to display them in.</p>

<h2>Determining address kind</h2>

<p>When shipping, it&#8217;s often important to know the &#8220;kind&#8221; of an address, as in the following enumeration demonstrates:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">enum</span> AddressKind <span style="color: #008000;">:</span> <span style="color: #6666cc; font-weight: bold;">int</span>
<span style="color: #008000;">&#123;</span>
    Unknown <span style="color: #008000;">=</span> <span style="color: #FF0000;">0</span>,
    Commercial <span style="color: #008000;">=</span> <span style="color: #FF0000;">1</span>,
    PostOfficeBox <span style="color: #008000;">=</span> <span style="color: #FF0000;">2</span>,
    Residential <span style="color: #008000;">=</span> <span style="color: #FF0000;">3</span>,
    Military <span style="color: #008000;">=</span> <span style="color: #FF0000;">4</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>Why is this important? For example, you can only use USPS to ship to a PO box or a military (APO/FPO/DPO) address, and you can&#8217;t use FedEx Home Service on a commercial address.</p>

<p>One mistake that I made over the years was trying to store the <code>AddressKind</code> right in the <code>Address</code> object. This was a mistake for a few reasons:</p>

<ul>
<li>I don&#8217;t always care about the address kind, such as for an international address, so having it appear on every <code>Address</code> instance is wasteful.</li>
<li>Computing the address kind can be expensive. While figuring out a PO box or a military address just involves scanning the address fields, determining commercial or residential status means calling a Web service supplied by FedEx, which can take seconds to complete. By having the <code>Kind</code> property on the address, I&#8217;m left with a bad situation: I can either keep the immutability of my address object by determining the address kind for <em>every</em> address when I instantiate them, or I can break immutability, which negates the advantage of not having to worry about change tracking on these objects.</li>
</ul>

<p>As a result, our new Web site simply doesn&#8217;t store the address kind at all. The kind, if needed, is determined on the fly by calling the <code>DetermineAddressKind()</code> method of an <code>IAddressKindDeterminer</code> instance.</p>

<h2>Being flexible: Legacy data and third-party integration points</h2>

<p>Finally, there&#8217;s one last point to be made. This new address validation and formatting is great and all, but there are two potential problems:</p>

<ul>
<li>There is 10 years of less-than-satisfactory address data already in the database, and it could be in an &#8220;invalid&#8221; format according to these new guidelines. Obviously, we want to maintain backward compatibility here, as we don&#8217;t want to force our customers to re-type their address data, and we don&#8217;t want to blow up when simply trying to load the address from the database.</li>
<li>Addresses sometimes get force-fed to the system via third-party integrations such as PayPal Express Checkout or Google Checkout. I can&#8217;t really reject addresses coming from these sources, so I have to be able to &#8220;take it like it is,&#8221; even if it means it doesn&#8217;t quite adhere to my preferred format.</li>
</ul>

<p>As a result, the new address system has to be able to grandfather in old addresses and graciously accept other addresses from integration. For accepting addresses from integration, I simply added an overload to the address builder&#8217;s <code>Build()</code> method that does not perform any validation&#8211;and trust myself only to use that overload in the proper scenarios.</p>

<p>For handling legacy address data, I simply let NHibernate set the address fields directly when loading objects from the database. That is, since the address isn&#8217;t constructed via the address builder but is instead built up via reflection, no validation is run on the legacy address and so the legacy address will still load.</p>

<p>One advantage of this model comes from the <code>Address</code> object&#8217;s immutability. Since the address can&#8217;t be changed, if the user wishes to edit an old address, they&#8217;ll be forced to bring the whole address up to snuff since a new <code>Address</code> instance will need to be created.</p>

<h2>Conclusions and delusions</h2>

<p>At the end of the day, we&#8217;re left with a robust implementation of address storage and address validation:</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-24-2010-10-41-55-AM.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/11/11-24-2010-10-41-55-AM.png" alt="" title="Source Fields" width="356" height="573" class="aligncenter size-full wp-image-751" /></a></p>

<p>International address validation, input, and handling has never been better at Skiviez, and for the first time in years, I feel like it&#8217;s finally under control&#8211;thanks to a clean object design, immutability, and a few days of thinking really hard about the problem. I hope this post gives someone some insight on their own project out there. Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2010/11/inside-skiviez-mailing-addresses/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Windows Mobile Device Center hangs on splash screen</title>
		<link>http://nicholas.piasecki.name/blog/2010/10/windows-mobile-device-center-hangs-on-splash-screen/</link>
		<comments>http://nicholas.piasecki.name/blog/2010/10/windows-mobile-device-center-hangs-on-splash-screen/#comments</comments>
		<pubDate>Wed, 27 Oct 2010 02:05:20 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Programming]]></category>
		<category><![CDATA[activesync]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[configuration]]></category>
		<category><![CDATA[windows mobile]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=701</guid>
		<description><![CDATA[At Skiviez, we use two HandHeld Honeywell Dolphin D7600 Mobile Computers to pick orders. They&#8217;re devices with a barcode scanner, a touch screen, and WiFi capability. They run a Platform Builder variant of Windows CE 5.0. And in Windows XP, &#8230; <a href="http://nicholas.piasecki.name/blog/2010/10/windows-mobile-device-center-hangs-on-splash-screen/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/d7600.gif"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/d7600.gif" alt="" title="Dolphin D7600" width="110" height="288" class="alignright size-full wp-image-705" /></a></p>

<p>At <a href="http://www.skiviez.com">Skiviez</a>, we use two <s>HandHeld</s> <a href="http://www.honeywellaidc.com/Site.aspx/eu/en/product_center/product_support/?category=42&amp;product=246">Honeywell Dolphin D7600 Mobile Computers</a> to pick orders. They&#8217;re devices with a barcode scanner, a touch screen, and WiFi capability. They run a Platform Builder variant of Windows CE 5.0. And in Windows XP, they used ActiveSync to connect to Windows and provide the basic service of being able to access the file system of the device (the other services provided by ActiveSync, like syncing mail, contacts, and calendars, don&#8217;t really make sense for an industrial device like this).</p>

<p>ActiveSync is a pretty wonky and ugly looking program, but it worked.</p>

<p>In Windows Vista and Windows 7, ActiveSync has been replaced&#8211;though the tradition of fragility and wonkiness continued&#8211;by an abomination called the Windows Mobile Device Center. (Indeed, it is telling that the new Windows Phone 7 drops ActiveSync/Windows Mobile Device Center completely and instead uses its own synchronization mechanism through the Zune software.) Which, like its predecessor, still worked for providing the basic service of accessing the file system and allowing Visual Studio to connect a debugger.</p>

<p>Except, one day, it stopped working. And I had no idea why.</p>

<p>Suddenly, plunking the device into its cradle would have the following behavior:</p>

<ul>
<li>The device would authenticate and think it is connected.</li>
<li>The PC&#8217;s USB subsystem would recognize the device and think it is connected.</li>
<li>Windows Mobile Device Center would permanently hang at the splash screen:</li>
</ul>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/windows-sync-dead-3.jpg"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/windows-sync-dead-3.jpg" alt="" title="Splash Screen" width="419" height="222" class="aligncenter size-full wp-image-703" /></a></p>

<p>Which is just awesome.</p>

<p>If I re-launched Windows Mobile Device Center via the Start menu, the program would open, but it would insist that the device is &#8220;Not Connected.&#8221;</p>

<p>So, I began to troubleshoot.</p>

<ul>
<li>I looked in the Event Log. (My first mistake. I&#8217;m renaming the Event Log the &#8220;Red Herrings Viewer&#8221;.)</li>
<li>I tried enabling verbose logging for Windows Mobile Device Center (which reports nothing useful).</li>
<li>I tried uninstalling the the device and letting Windows reinstall its drivers.</li>
<li>I tried uninstalling Windows Mobile Device Center and reinstalling it.</li>
<li>I tried soft resetting the device.</li>
<li>I tried hard resetting the device.</li>
<li>I made sure that the &#8220;Windows Mobile *&#8221; firewall rules existed in Windows Firewall.</li>
<li>I tried a different USB port.</li>
<li>I tried a different USB cable.</li>
<li>I tried a different D7600 device.</li>
<li>I tried a different D7600 cradle.</li>
<li>I tried merged the registry settings from another Windows 7 machine that the device would successfully connect to.</li>
<li>I tried switching to the RNDIS connectivity model.</li>
<li>I tried granting additional permissions on the &#8220;Windows CE Services&#8221; registry keys.</li>
<li>I tried diddling with the various &#8220;Windows CE Services&#8221; registry keys.</li>
</ul>

<p>You might think that anyone of these things would contain the solution. But you&#8217;d wrong.</p>

<p>The problem was that I had FileZilla FTP Server installed on my machine, configured to allow FTPS connections. (We use an FTP server to manage images and files on the Skiviez Web site, and I had a local copy on my machine from when I was testing the configuration.)</p>

<p>Now, some people might ask &#8220;Why the hell would an FTP server break Windows Mobile device connectivity?&#8221; Apparently, Windows Mobile Device Center uses port 990 to orchestrate the connection.</p>

<p><a href="http://www.iana.org/assignments/port-numbers">Port 990 just so happens to be the standard control port for FTPS connections.</a> If anything else is consuming port 990, then the Windows Mobile Device Center either hang, reports that the device is not connected, or stupidly tries to keep connecting to it. (A message like &#8220;whoops port 990 is in use or does not seem to be a mobile device&#8221; would go a long way.)</p>

<p>So <strong>make sure nothing is using port 990</strong>; then go pour yourself a g&amp;t.</p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2010/10/windows-mobile-device-center-hangs-on-splash-screen/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Inside Skiviez: Catalog Listings and Search Queries</title>
		<link>http://nicholas.piasecki.name/blog/2010/10/inside-skiviez-catalog-listings-and-search-queries/</link>
		<comments>http://nicholas.piasecki.name/blog/2010/10/inside-skiviez-catalog-listings-and-search-queries/#comments</comments>
		<pubDate>Sun, 10 Oct 2010 16:09:30 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Web Development]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[skiviez]]></category>
		<category><![CDATA[web stuff]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=648</guid>
		<description><![CDATA[Last Tuesday, I rolled out a new release of the Skiviez Web site. It is the most significant technical change at Skiviez since 2007 and brings with it a lot of improvements in how it operates against our company&#8217;s 10-year-old &#8230; <a href="http://nicholas.piasecki.name/blog/2010/10/inside-skiviez-catalog-listings-and-search-queries/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Last Tuesday, I rolled out a new release of the <a href="http://www.skiviez.com/">Skiviez Web site</a>. It is the most significant technical change at Skiviez since 2007 and brings with it a lot of improvements in how it operates against our company&#8217;s 10-year-old database.</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-9-56-40-AM.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-9-56-40-AM.png" alt="" title="Facets" width="208" height="432" class="alignleft size-full wp-image-649" /></a></p>

<p>One of these new features is a fast, <a href="http://www.lucidimagination.com/Community/Hear-from-the-Experts/Articles/Faceted-Search-Solr">faceted</a> product catalog. Faceting is the technical name for something you&#8217;ve seen in many e-commerce stores like NewEgg, Zappo&#8217;s, and Lowe&#8217;s: a list of links that quickly allow you to drill down to the content that you&#8217;d like to see.</p>

<p>Trying to do this kind of thing efficiently in a traditional relational database is not going to happen unless you want to start adding and removing indexes on the fly or go full on <a href="http://en.wikipedia.org/wiki/Entity-attribute-value_model">Entity-Attribute-Value</a>, which somewhat defeats the purpose of using a relational database. You lose efficient indexing, you lose type information, you lose, well, the relations.</p>

<p>Instead, Skiviez now uses <a href="http://lucene.apache.org/solr/">Solr</a>&#8211;an open source search platform that is based on <a href="http://lucene.apache.org/java/docs/index.html">Lucene</a>, a text search engine library&#8211;for managing catalog listing pages and search pages.</p>

<h2>Solr from 10,000 feet</h2>

<p>Solr is not relational. It doesn&#8217;t have tables. The schema is flat; all &#8220;documents&#8221; in the Solr store share the same schema. From a relational perspective, you could think of it as one table with many columns, except that not every row in the table uses all of the columns. (This isn&#8217;t how it internally works at all, but it&#8217;s a useful metaphor.)</p>

<p>Some fields are &#8220;stored,&#8221; which means you can get back the data that you put in. Some fields are &#8220;indexed,&#8221; which means that you can query on them directly and use them for faceting. And some fields are &#8220;multivalued&#8221;, which means that they can hold more than one value at a time. For example, our <code>&lt;sizeInStock&gt;</code> field can hold <code>S</code>, <code>M</code>, and <code>L</code> values all at once for a particular product, and just <code>L</code> for another.</p>

<p>Why would you ever want a value to not be &#8220;stored&#8221;? Why add data that you can&#8217;t get back? Well, in Solr, storing and indexing are distinct concepts, so you can a value that is not stored, just indexed. A good example from the Skiviez Solr schema would be the <code>salesVolume</code> field, which indicates how many units of a particular item were sold in the past week:</p>


<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">		<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;field</span></span>
<span style="color: #009900;">			<span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;salesVolume&quot;</span></span>
<span style="color: #009900;">			<span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;sint&quot;</span></span>
<span style="color: #009900;">			<span style="color: #000066;">indexed</span>=<span style="color: #ff0000;">&quot;true&quot;</span></span>
<span style="color: #009900;">			<span style="color: #000066;">stored</span>=<span style="color: #ff0000;">&quot;false&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>


<p>This is just an integer, a number of units sold. In my UI, I&#8217;m not going to ever actually display that number&#8211;that would reveal a little too much information about our business. But I still want our users to be able to sort catalog listings by &#8220;Top Selling&#8221; products. By creating an index, we enable sorting; by disallowing storage, we save some space.</p>

<p>The Skiviez Solr schema defines a &#8220;type&#8221; field, some fields that are shared among all document types, and a few type-specific fields. This works well because the only intended use of Solr is catalog listings and searching; if I had to store more disparate kinds of data, I might create several Solr schemas.</p>


<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;"><span style="color: #808080; font-style: italic;">&lt;!--</span>
<span style="color: #808080; font-style: italic;">	This field is used to indicate the type of data that is stored within</span>
<span style="color: #808080; font-style: italic;">	the document. Since the Skiviez Solr instance represents a variety of</span>
<span style="color: #808080; font-style: italic;">	different types, this field helps to indicate what kind of data you are</span>
<span style="color: #808080; font-style: italic;">	looking at.</span>
&nbsp;
<span style="color: #808080; font-style: italic;">	Types that are currently understood the Web site include:</span>
&nbsp;
<span style="color: #808080; font-style: italic;">		BLOGARTICLE</span>
<span style="color: #808080; font-style: italic;">		BRAND</span>
<span style="color: #808080; font-style: italic;">		LINE</span>
<span style="color: #808080; font-style: italic;">		PRODUCT</span>
<span style="color: #808080; font-style: italic;">		PRODUCTSUMMARY</span>
<span style="color: #808080; font-style: italic;">                PROMOTION</span>
<span style="color: #808080; font-style: italic;">		STYLE</span>
<span style="color: #808080; font-style: italic;">		WEBPAGE</span>
<span style="color: #808080; font-style: italic;">--&gt;</span>
<span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;field</span></span>
<span style="color: #009900;">	<span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;type&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">type</span>=<span style="color: #ff0000;">&quot;string&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">indexed</span>=<span style="color: #ff0000;">&quot;true&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">stored</span>=<span style="color: #ff0000;">&quot;true&quot;</span></span>
<span style="color: #009900;">	<span style="color: #000066;">required</span>=<span style="color: #ff0000;">&quot;true&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span></pre></div></div>


<p>Why is this useful? Well, the search portion of the Skiviez Web site can use the <code>&lt;type&gt;</code> field and the fields that are used by all of the different document types to quickly search a wide variety of sources:</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-11-45-05-AM.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-11-45-05-AM.png" alt="" title="A wide variety of sources" class="aligncenter size-full wp-image-684" /></a></p>

<p>In this case, we&#8217;re looking at our <code>&lt;type&gt;</code>, <code>&lt;urlKey&gt;</code>, <code>&lt;name&gt;</code>, and <code>&lt;image&gt;</code> fields. The Web site can use this to quickly sort information and build links to content.</p>

<p>The <code>PRODUCT</code> type uses a wealth of product-specific fields, however, and when we query to display catalog pages, we tell Solr to only return documents of type <code>PRODUCT</code>. I could have created a second Solr schema for this purpose, but why bother?</p>

<h2>Getting data into Solr</h2>

<p>The traditional SQL database is still the &#8220;authoritative&#8221; data store, and the Solr indexes are read-only snapshots of that data. This means that the data coming from Solr is always slightly stale, so I had to ask myself:</p>

<ul>
<li>How stale is too stale?</li>
<li>When do I value speed or querying over staleness?</li>
</ul>

<p>Part of the new Skiviez Web site is a Windows service that I call the &#8220;Worker.&#8221; It uses <a href="http://quartznet.sourceforge.net/">Quartz.NET</a> to execute C# <code>IJob</code> implementations periodically. You can think of them as traditional scheduled tasks in Windows; the only difference is that I am explicitly managing them in code, using the same object-oriented model of our domain in those jobs, and, as long as the service is installed, I don&#8217;t need to worry about configuring scheduled tasks.</p>

<p>Every three hours, one of those <code>IJob</code>s that gets executed is the <code>RefreshSolrIndexesJob</code>, and all that job does is ping an <code>HttpWebRequest</code> over to <code>http://solr.example.com/dataimport?command=full-import</code>, where <code>solr.example.com</code> is placed with the FQDN of our internal Solr server. This is because I use Solr&#8217;s built-in <a href="http://wiki.apache.org/solr/DataImportHandler"><code>DataImportHandler</code></a> to actually suck in the data from the SQL database; the job just has to &#8220;touch&#8221; that URL periodically to make the sync work. Because the <code>DataImportHandler</code> commits the changes periodically, this is all effectively running in the background, transparent to the users of the Web site. And because the Skiviez product catalog is reasonably small (a few thousand items), we can blow away the whole Solr index and re-build it in fewer than two minutes.</p>

<p>There&#8217;s also a function in our backend application that allows employees to trigger the index rebuilding immediately; this can happen when new product arrives in the warehouse and we want to get it up on the Web site right away.</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-11-18-03-AM.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-11-18-03-AM.png" alt="" title="Manual Rebuild Function" class="aligncenter size-full wp-image-676" /></a></p>

<p>The <code>DataImportHandler</code> is built into Solr, and configuring it is a little confusing because it uses some strange terminology. It just takes an XML configuration file, and whenever you ping its request handler, it performs synchronization tasks based on what has been specified in its configuration.</p>


<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;entity</span></span>
<span style="color: #009900;">        <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;brands&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">dataSource</span>=<span style="color: #ff0000;">&quot;undiesDatabase&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">transformer</span>=<span style="color: #ff0000;">&quot;TemplateTransformer&quot;</span></span>
<span style="color: #009900;">        <span style="color: #000066;">query</span>=<span style="color: #ff0000;">&quot;</span>
<span style="color: #009900;">            SELECT</span>
<span style="color: #009900;">                b.ID AS BrandId,</span>
<span style="color: #009900;">                b.[Name] AS BrandName,</span>
<span style="color: #009900;">                b.Description AS BrandDescription,</span>
<span style="color: #009900;">                b.UrlKey AS BrandUrlKey,</span>
<span style="color: #009900;">                CASE b.Active</span>
<span style="color: #009900;">                  WHEN 'Y' THEN 'True'</span>
<span style="color: #009900;">                  ELSE 'False'</span>
<span style="color: #009900;">                END AS BrandIsActive</span>
<span style="color: #009900;">            FROM na.brands AS b</span>
<span style="color: #009900;">            ORDER BY b.[Name];&quot;</span><span style="color: #000000; font-weight: bold;">&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;field</span> <span style="color: #000066;">column</span>=<span style="color: #ff0000;">&quot;id&quot;</span> <span style="color: #000066;">template</span>=<span style="color: #ff0000;">&quot;BRAND-${brands.BrandId}&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;field</span> <span style="color: #000066;">column</span>=<span style="color: #ff0000;">&quot;type&quot;</span> <span style="color: #000066;">template</span>=<span style="color: #ff0000;">&quot;BRAND&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;field</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;identity&quot;</span> <span style="color: #000066;">column</span>=<span style="color: #ff0000;">&quot;BrandId&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;field</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;name&quot;</span> <span style="color: #000066;">column</span>=<span style="color: #ff0000;">&quot;BrandName&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;field</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;description&quot;</span> <span style="color: #000066;">column</span>=<span style="color: #ff0000;">&quot;BrandDescription&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;field</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;isActive&quot;</span> <span style="color: #000066;">column</span>=<span style="color: #ff0000;">&quot;BrandIsActive&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
        <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;field</span> <span style="color: #000066;">name</span>=<span style="color: #ff0000;">&quot;urlKey&quot;</span> <span style="color: #000066;">column</span>=<span style="color: #ff0000;">&quot;BrandUrlKey&quot;</span> <span style="color: #000000; font-weight: bold;">/&gt;</span></span>
      <span style="color: #009900;"><span style="color: #000000; font-weight: bold;">&lt;/entity<span style="color: #000000; font-weight: bold;">&gt;</span></span></span></pre></div></div>


<p>I say the terminology is confusing because in <code>&lt;field&gt;</code> elements, the @column attribute is the name of the Solr field and the name of the column in the SQL result set. But if the @name attribute is specified, then the @column attribute is the name of the column in the result set and the @name attribute is the name of the Solr field. It&#8217;s confusing because some <code>&lt;field&gt;</code> elements don&#8217;t pull directly from the result set, instead relying on a &#8220;transformer.&#8221; You would expect to just specify a @name for those fields, but specifying just @column is correct. In the above example, the &#8220;Template Transformer&#8221; is used on the <code>id</code> field to format Solr identities in the format of <code>BRAND-127</code>, where <code>127</code> is the SQL database&#8217;s primary key for the brand.</p>

<p>(And yes, attributes can have newlines in them. I&#8217;m not sure how I went through years of programming without realizing this, but once I realized that I could do it, it made reading those SQL queries much easier! This example is by far the shortest query for pulling Solr data from the SQL database; the one for products is over 200 lines long.)</p>

<h2>Querying data: how stale is too stale?</h2>

<p>This does mean that information in the Skiviez product catalog can be up to three hours stale. A user might click a link for &#8220;Medium In Stock (3)&#8221; on the catalog page (since this kind of faceted data is generated by querying Solr) but then see on the product detail page that no mediums are in stock (since on this page, the quantity information is one of the few things not cached and queried directly against the database). This is annoying, but generally rare in our particular scenario (we are a reasonably small business and not that high traffic), and it will be fixed up in 3 hours anyway when we rebuild the whole index again from scratch, so I have accepted this as a reasonable trade-off.</p>

<p>(If I really wanted to solve this problem, there are a few approaches that I could take. I could use <a href="http://www.udidahan.com/2009/06/14/domain-events-salvation/">domain events</a> to fire off partial updates to the Solr index whenever a Save/Update operation occurred on an <code>Item</code> or <code>ItemGroup</code> in the Skiviez domain model, or I could insert a record into a table named, say, <code>dbo.IdentitiesOfStuffThatNeedsUpdatingInSolr</code>, and have an <code>IJob</code> that reads that list and executes partial updates every minute. And even if I did these things, I&#8217;d still probably want to do a periodic &#8220;blow it all away and refresh&#8221; in case one of those partial updates failed in the background.)</p>

<p>As for querying this data from Solr, there are a few approaches that I could have taken. One is to hide the fact that Solr exists entirely via the methods of a repository-like class: the <code>Get*()</code> methods would access Solr, and the Create/Update/Delete methods would access the database. I didn&#8217;t like this approach because my Solr schema is already shamelessly tailored to the UI that will be accessing that data, as it should be&#8211;I&#8217;ve already made the decision to use Solr to provide easy faceting, sorting, and fast display of information, so I might as well use it to its fullest extent. This means making it explicit in code as to when I mean to access Solr and when I mean to access the up-to-date, non-cached database object.</p>

<p>In my case, I ended up using <a href="http://nhforge.org/Default.aspx">NHibernate</a> to do the CRUD access (e.g., loading an <code>ItemGroup</code>, futzing with its pricing rules, and then saving it back), forgoing the repository pattern because I don&#8217;t typically see its value when NHibernate and its mappings are already abstracting the database. (Sometimes abstracting out NHibernate is useful, however, as we&#8217;ll see below.)</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-10-20-52-AM.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-10-20-52-AM.png" alt="" title="Trade-offs" width="328" height="81" class="aligncenter size-full wp-image-655" /></a></p>

<p>When querying for data, I know pretty well if I&#8217;m using it for catalog-oriented purposes (in which I care about <em>speed</em> and <em>querying features</em>) or for displaying in a table on a back-end administrative application (I care about <em>currency</em>). For querying on the Web site, I have an interface called <code>IListingQuery</code>. It has a <code>Search()</code> method that accepts a <code>ListingRequest</code> where I define some parameters&#8211;selected facets, search terms, page number, number of items per page, etc.&#8211;and gives back a <code>ListingResponse</code>&#8211;remaining facets, number of results, the results on this page, etc. This interface is pretty boring stuff.</p>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/moew.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/moew.png" alt="" title="Simpler than it looks" class="aligncenter size-full wp-image-672" /></a></p>

<p>Where it gets interesting is that the implementation of <code>IListingQuery</code> that gets dependency injected into my Web site&#8217;s <code>ProductsController</code> is using a list of <code>IListingQueryStrategy</code>s underneath. The default strategy, the <code>SolrListingQueryStrategy</code>, hits Solr directly via a plain old-fashioned <code>HttpWebRequest</code> and parses the XML in the <code>HttpWebResponse</code> (which is much easier to use, in my humble opinion, than some of the Solr client libraries).</p>

<p>If the Solr-based strategy throws an exception or vomits for some reason, then the <code>DatabaseListingQueryStrategy</code> runs next and hits the database directly&#8211;although it ignores some parameters of the <code>ListingRequest</code>, like faceting or advanced text searching, since that is inefficient to do there and is the whole reason I am using Solr in the first place. The idea is that usually Solr is answering my search requests quickly in their full-featured glory, but if something blows up and Solr goes down, then the catalog pages of the site can still function in &#8220;reduced-functionality mode&#8221; by hitting the database with a limited feature set directly. (As implemented on the Skiviez site today, you would realize that this happened if the filters list on the left-hand side becomes empty and search parameters are ignored.)</p>

<p>(The explosion of classes that you see in the screenshot above is mostly due to testability. For example, Solr works by sending long, complicated GET requests to it. So I&#8217;ve pulled out of the URI-building functionality into its own class; it serves a single purpose and can be tested as such. The actual <code>SolrListingQueryStrategy</code> class implementation is very short, with most of the work delegated to other classes within that folder.)</p>

<h2>Conclusions and delusions</h2>

<p><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-11-56-35-AM1.png"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/10/10-10-2010-11-56-35-AM1.png" alt="" title="Putting it together" class="aligncenter size-full wp-image-688" /></a></p>

<p>What is important is that I have made explicit in code that this is a search&#8211;by using <code>IListingQuery</code> instead of NHibernate&#8211;so the database-based strategy can take some liberties in ignoring some of the search parameters without worrying about affecting some of its down-level callers too severely. The decision to perform a query against a possibly-stale data store versus the authoritative data store has been made explicit&#8211;if I want fast, possibly stale data with advanced search features, I use <code>IListingQuery</code>. If I want slow, up-to-date data with insert/update/delete capability, I use NHibernate&#8217;s named queries. And if I make a change in the SQL database, I know that the out-of-process Worker service will update Solr eventually, making things eventually consistent.</p>

<p>The end result? Fast catalog pages for our customers that gracefully fall back to the old behavior when something doesn&#8217;t work.</p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2010/10/inside-skiviez-catalog-listings-and-search-queries/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>SBS 2008 restarts unexpectedly when backup starts</title>
		<link>http://nicholas.piasecki.name/blog/2010/05/sbs-2008-restarts-unexpectedly-when-backup-starts/</link>
		<comments>http://nicholas.piasecki.name/blog/2010/05/sbs-2008-restarts-unexpectedly-when-backup-starts/#comments</comments>
		<pubDate>Thu, 20 May 2010 23:32:22 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[backup]]></category>
		<category><![CDATA[failure]]></category>
		<category><![CDATA[sbs-2008]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=622</guid>
		<description><![CDATA[Today, our SBS 2008 server restarted itself at 5:00 p.m. sharp. I mean on the dot. That was disturbing enough in itself. When the system came back up, it helpfully asked me to type in &#8220;Why did the system shut &#8230; <a href="http://nicholas.piasecki.name/blog/2010/05/sbs-2008-restarts-unexpectedly-when-backup-starts/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Today, our SBS 2008 server restarted itself at 5:00 p.m. sharp. I mean <em>on the dot</em>.</p>

<p>That was disturbing enough in itself. When the system came back up, it helpfully asked me to type in &#8220;Why did the system shut down unexpectedly?&#8221; and I enthusiastically typed in &#8220;Fuck if I know you jackass.&#8221; Then, I headed straight for the event log.</p>

<p>The event log was full of terrifying messages such as</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">The system failed to flush data to the transaction log. Corruption may occur.</pre></div></div>


<p>or</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">An error was detected on device \Device\Harddisk1\DR2  during a paging operation.</pre></div></div>


<p>Hmm. There was no blue screen, no bug check, no minidump. It was as if the power had been cut.</p>

<p>I looked accusingly at the UPS since I have had problems with bad UPSs interrupting the power supply in the past. I held down its self-test button, it made that satisfying buzzing noise, and &#8230; everything stayed up.</p>

<p>But while crouched down next to the UPS, I heard an odd swishing noise, like a tiny man was running his finger across a sheet of Saran Wrap. Then I noticed that the external Western Digital hard drive that we use for SBS 2008 backup was doing its swooshing-lights mode, not its solid-lights mode, and I knew from previous experience that it only did that when it was starting up or shutting down.</p>

<p>I had a hunch&#8211;in SBS 2008, backup uses Volume Shadow Copy, and I had seen similar disk errors when another of our external hard drives cooked itself (though instead of rebooting, that server became unresponsive). I unplugged the external drive and the event log messages stopped.</p>

<p>I then promptly threw the external hard drive into the trash, drove straight to Best Buy and bought a new external hard drive with the company credit card. (Aside: Why do 90% of external hard drives come with craptastic backup software or &#8220;one-touch&#8221; buttons? I just want a drive in a box. I finally found one in the &#8220;Seagate Expansion&#8221; line.)</p>

<p>Then I plugged in the new external hard drive and re-ran the &#8220;Configure server backup&#8221; wizard from the SBS 2008 console. I unchecked the old, now non-existent drive, checked the new one, and off it went. And all seems happy now. (I ran <code>chkdsk</code> for good measure on the system and data drives and they checked out OK, so it does all seem related to the external backup drive cooking itself.)</p>

<p>Should it be capable of handling faulty backup hardware more gracefully? Sure. And I wish that SBS 2008 had the option to use the old <code>ntbackup</code> utility because then at least you could backup to network-attached storage. It&#8217;s been my experience that external hard drives really are not that reliable and have an average lifespan of only about two years, but maybe I have just been glaring at them the wrong way.</p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2010/05/sbs-2008-restarts-unexpectedly-when-backup-starts/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I Hate Software</title>
		<link>http://nicholas.piasecki.name/blog/2010/05/i-hate-software/</link>
		<comments>http://nicholas.piasecki.name/blog/2010/05/i-hate-software/#comments</comments>
		<pubDate>Wed, 05 May 2010 19:59:29 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[Rants]]></category>
		<category><![CDATA[bugs]]></category>
		<category><![CDATA[fedex]]></category>
		<category><![CDATA[smartftp]]></category>
		<category><![CDATA[ups]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=585</guid>
		<description><![CDATA[Today, I realized that I hate software. First, it was FedEx It has been 45 days since I reported to FedEx that the new SmartPost integration offered by their Web services simply does not work when an EPL2 label is &#8230; <a href="http://nicholas.piasecki.name/blog/2010/05/i-hate-software/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Today, I realized that I hate software.</p>

<h2>First, it was FedEx</h2>

<p>It has been 45 days since I reported to FedEx that the new SmartPost integration offered by their Web services simply does not work when an EPL2 label is requested:</p>

<div id="attachment_588" class="wp-caption aligncenter" style="width: 310px"><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/05/0828_0012.jpg"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/05/0828_0012.jpg" alt="" title="I Hate Software, Part 1" width="300" height="441" class="size-full wp-image-588" /></a><p class="wp-caption-text">I Hate Software, Part 1</p></div>

<p>The problem is that the USPS Delivery Confirmation barcode does not print when an EPL2 label is requested. That&#8217;s because in the EPL2 document that FedEx sends back, quotation marks in the barcode command are not properly escaped:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">A90,473,0,3,1,2,N,&quot;ZIP - USPS DELIVERY CONFIRMATION e-VS&quot;
B50,535,0,1,3,4,175,N,&quot;&quot;F1&quot;42023221&quot;F1&quot;0000000000000000000000&quot;</pre></div></div>


<p>That should read <code>"\"F1\"420..."</code> for it to print correctly. (The ZPLII version of the label works fine.)</p>

<p>I understand that larger corporations have fixed software release cycles and different bug triage mechanisms, but having to through three levels of support and waiting 45+ days to simply say &#8220;this simply doesn&#8217;t work please add a backslash&#8221; is somewhat frustrating.</p>

<h2>Then, there was UPS</h2>

<p>Similarly, I&#8217;ve discovered a recently-introduced error with the UPS Web services. If you request a 4&#8243; x 6&#8243; EPL shipping label, then the UPS Web service will happily ignore request and send back a 4&#8243; x 8&#8243; label instead. That&#8217;s because they&#8217;re sending back the wrong width and height settings in the label response:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">q795
Q1600,24</pre></div></div>


<p>That would be 795 dots / 203 dpi == 3.91&#8243; wide (OK) and 1600 dots / 203 dpi == 7.88&#8243; high (hmm, not what I asked for). (The ZPLII version of the label works fine.)</p>

<h2>Finally, SmartFTP sent me over the edge</h2>

<p>Since updating to the latest version of SmartFTP, I found myself frequently being unable to connect to the Skiviez private FTP server that is used to manage software updates, e-mails, and product catalog images. It would fail about 80% of the time with</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">[13:51:38] 234 Using authentication type TLS
[13:51:38] SSL: Error (Error=0x80090308).</pre></div></div>


<p>I&#8217;m sure that this means something. And even if I knew what it was, sometimes it would just work without me changing anything (about 10 percent of the time). Further still, I hadn&#8217;t touched the FTP server for some time.</p>

<p>That&#8217;s when I noticed in the SmartFTP change log:</p>


<div class="wp_syntax"><div class="code"><pre class="text" style="font-family:monospace;">FTP: Completely rewrote SSL layer</pre></div></div>


<p>Sigh. Downgraded to the version prior to that changelog entry, and it works fine.</p>

<h2>Conclusions and delusions</h2>

<p>I have certainly done my part to contribute buggy, crappy software to the world. I continue to spew out more buggy, crappy software with each passing day. But it is extra depressing and disheartening to know that I, some idiot working at a small company, can run across such simply-does-not-work bugs (and, in FedEx&#8217;s case, never-actually-worked-ever bugs) in software produced by large corporations and used by presumably hundreds to thousands of people around the world.</p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2010/05/i-hate-software/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quick Tip: Sharing a FedEx ZP 500 printer attached to a Windows XP computer to a Windows Vista/7 machine</title>
		<link>http://nicholas.piasecki.name/blog/2010/04/quick-tip-sharing-a-fedex-zp-500-printer-attached-to-a-windows-xp-computer-to-a-windows-vista7-machine/</link>
		<comments>http://nicholas.piasecki.name/blog/2010/04/quick-tip-sharing-a-fedex-zp-500-printer-attached-to-a-windows-xp-computer-to-a-windows-vista7-machine/#comments</comments>
		<pubDate>Thu, 15 Apr 2010 22:30:46 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[printing]]></category>
		<category><![CDATA[quick-tip]]></category>
		<category><![CDATA[zebra]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=569</guid>
		<description><![CDATA[At Skiviez/WFS, we have a FedEx ZP 500 ZPL printer on the shipping desk. This is what FedEx is migrating everyone to now that the tried-and-true Zebra/Eltron LP2844* series is getting a little long in the tooth. (Along with a &#8230; <a href="http://nicholas.piasecki.name/blog/2010/04/quick-tip-sharing-a-fedex-zp-500-printer-attached-to-a-windows-xp-computer-to-a-windows-vista7-machine/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>At <a href="http://www.skiviez.com/">Skiviez</a>/<a href="http://www.warehousefs.com/">WFS</a>, we have a FedEx ZP 500 ZPL printer on the shipping desk. This is what FedEx is migrating everyone to now that the tried-and-true Zebra/Eltron LP2844* series is getting a little long in the tooth. (Along with a gradual migration to ZPL over EPL2, but that&#8217;s a rant for another day.)</p>

<div id="attachment_571" class="wp-caption aligncenter" style="width: 185px"><a href="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/04/printer_faq.jpg"><img src="http://nicholas.piasecki.name/blog/wp-content/uploads/2010/04/printer_faq.jpg" alt="" title="FedEx ZP 500" width="175" height="91" class="size-full wp-image-571" /></a><p class="wp-caption-text">FedEx ZP 500</p></div>

<p>The FedEx ZP 500 is a bit of a white elephant in that Zebra doesn&#8217;t mention it on their Web site; it&#8217;s some sort of special contract job with FedEx to produce and jointly brand these devices. It&#8217;s probably just a re-branded version of the Zebra GK420d, but in reality we have the printer manufacturer pretending that they don&#8217;t make the printer (e.g., &#8220;call FedEx for support&#8221;) and a shipping company who has no idea how to support the printer (e.g., &#8220;call Zebra for the printer driver&#8221;). But I&#8217;m getting distracted.</p>

<p>The real issue was that the shipping desk is running Windows XP and shares the printer via the native Windows printer sharing mechanism so that it&#8217;s listed in the Active Directory. I do this so that I can run integration tests from the workstation in my office and test the label generation functions of our software without needing to have a thermal label printer hooked up to my workstation solely for this purpose. These printers aren&#8217;t cheap, you know.</p>

<h2>New operating system, new drivers required</h2>

<p>I recently upgraded my workstation to Windows 7. When I tried to add the shared FedEx thermal printer, I was greeted with error code <code>0x00000007a</code> along with an error message that generally amounted to &#8220;something didn&#8217;t work.&#8221; I suspected a driver problem since Vista is when Microsoft locked down on the mandate that printer drivers run in user mode, not kernel mode&#8211;which is a good thing in terms of system stability, since a poorly-written printer driver can no longer trigger a BSOD and a reboot, but a bad thing in terms of backwards compatibility.</p>

<p>The problem is that</p>

<ul>
<li>the Windows XP machine is offering the Windows XP drivers to my Windows 7 install;</li>
<li>the Windows 7 printer wizard doesn&#8217;t give me a chance to supply my own printer drivers, and instead happily installs the XP ones, which don&#8217;t work;</li>
<li>the FedEx-supplied Vista drivers are mutually exclusive in terms of compatibility with the XP drivers, so I can&#8217;t install them on the XP machine via the <code>Server Properties</code> thingie; and</li>
<li>even if I could do that, I am hesitant to dick around with the printer drivers on a critical machine.</li>
</ul>

<h2>Adding the printer</h2>

<p>The solution was to add a printer in a different, counter-intuitive way. Here&#8217;s what I did:</p>

<ol>
<li>From the Windows 7 Control Panel, I went to &#8220;View devices and printers&#8221; and then &#8220;Add a printer&#8221;.</li>
<li>When asked &#8220;What type of printer do you want to install?&#8221; I chose <strong>Add a local printer</strong>, even though I know full damn well that I&#8217;m not actually adding a local printer.</li>
<li>For &#8220;Choose a printer port,&#8221; I chose &#8220;Create a new port&#8221; with &#8220;Type of port&#8221; set to &#8220;Local Port&#8221;.</li>
<li>In the &#8220;Enter a port name&#8221; dialog, I entered the UNC share name for the printer, which looks like <code>\\{MACHINE-NAME}\{PRINTER-SHARE-NAME}</code>. In my case, it was <code>\\ASHWHWS003\FedEx ZP 500 Plus</code>.</li>
<li>When asked for a driver, I chose &#8220;Have Disk&#8221; and navigated to the *.inf file in the ZD directory of the <a href="http://fedex.com/us/software/printerdrivers.html">Zebra Designer drivers</a> available from the FedEx Web site.</li>
</ol>

<p>This allowed me to use locally-available printer drivers on a printer attached to another machine. Good luck!</p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2010/04/quick-tip-sharing-a-fedex-zp-500-printer-attached-to-a-windows-xp-computer-to-a-windows-vista7-machine/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>Buying Software Sucks</title>
		<link>http://nicholas.piasecki.name/blog/2010/01/buying-software-sucks/</link>
		<comments>http://nicholas.piasecki.name/blog/2010/01/buying-software-sucks/#comments</comments>
		<pubDate>Tue, 19 Jan 2010 22:50:35 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[IT]]></category>
		<category><![CDATA[Rants]]></category>
		<category><![CDATA[consulting]]></category>
		<category><![CDATA[cots]]></category>
		<category><![CDATA[marketing]]></category>
		<category><![CDATA[purchasing]]></category>
		<category><![CDATA[requirements]]></category>
		<category><![CDATA[salespeople]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=522</guid>
		<description><![CDATA[What follows is a rant about the state of marketing in the software industry. We happen to like our system So we&#8217;ve branched out and offered fulfillment services to other merchants, as I&#8217;ve mentioned before. Essentially, other e-commerce stores or &#8230; <a href="http://nicholas.piasecki.name/blog/2010/01/buying-software-sucks/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>What follows is a rant about the state of marketing in the software industry.</p>

<h2>We happen to like our system</h2>

<p>So we&#8217;ve branched out and offered <a href="http://www.warehousefulfillmentservices.com/">fulfillment services to other merchants</a>, as I&#8217;ve mentioned before. Essentially, other e-commerce stores or merchants can store their items in our warehouse and then transmit orders as &#8220;fulfillment requests&#8221; to us. We either ship the request or mark it as invalid with a little message (&#8220;item has insufficient stock, delivery point validation failed, tax identification number required, etc.&#8221;). If they want to re-attempt, then they re-submit an entirely new fulfillment request.</p>

<p>This simple model has worked surprisingly well: the system doesn&#8217;t track &#8220;orders&#8221; (since each merchant handles backordering and cancellations differently), and while it does maintain an inventory log, it doesn&#8217;t track the cost of goods in inventory or anything like that, since that is not necessary for us to do our job. (Instead, it tracks a whole boatload of other information that people don&#8217;t normally think about, like HS codes or unit weight.)</p>

<h2>Some of our merchants need some hand-holding</h2>

<p>We have an API so merchants can integrate with our system. And so I&#8217;ve written a few plug-ins for Magento and osCommerce that auto-transmit their orders as fulfillment requests, sync outbound shipments back, and deduct inventory from their systems (since we are the authoritative inventory count). This works great for their retail businesses.</p>

<p>We have a merchant that we&#8217;ve been doing retail business with for some time who now wants to do wholesale stuff with us. He wants a sales order/invoicing/inventory management solution, and it needs to be able to track multiple inventories across multiple warehouses (our integration, if any, would only be adjusting inventory for a particular warehouse). He wants to enter sales orders remotely, press a button that shows him how much is ordered so he knows how much to make, have that manufactured and sent to us, click another button to transmit the sales order as a fulfillment request to us once it&#8217;s in stock, and then have us sync back with the shipment info, creating an invoice.</p>

<p>&#8220;Shouldn&#8217;t they have had these features prior to switching to you guys?&#8221; you ask. Well, yes. In this case, all of these features were provided in an all-in-one system provided by their previous fulfillment warehouse. They have since learned their lesson about keeping all of their data in the hands of a third party because when that relationship went south, so did their access to their own data.</p>

<p>We would rather not add these features to our system. Since all merchants have different ways of handling backorders, pre-orders, cancellations, cost of goods sold (FIFO, LIFO, average, priority), we&#8217;ve been maintaining the position that&#8211;unlike our competitors&#8211;our system is essentially feature complete, since it&#8217;s <em>ours</em> and does what <em>we</em> need it to do to ship things out. The features that I&#8217;ve mentioned <em>should</em> be things that the merchants are keeping track of themselves&#8211;since that&#8217;s their business&#8211;and integrate with our system via the programming API. While an argument could be made that our system would be abso-freaking-fantastic for merchants who need an all-in-one software and data solution (yes, it certainly would), the reality is that our competitors have an outsourced team of software developers, and we are a small business working in an area that is tangential to our core business as a result of the &#8220;new economy&#8221; that has a software development team of just one person (me) and can&#8217;t even begin to dream of hiring any more until we start seeing some serious cash flow.</p>

<p>In any case, to land this deal, we need to find a system for this merchant, and fast, because there are some important trade shows coming up.</p>

<h2>Welcome to marketing Hell</h2>

<p>Now for the rant, because you would think that these requirements are not exotic:</p>

<ul>
<li>Let salespeople enter sales orders remotely.</li>
<li>Keep track of inventory in multiple locations, and track the cost of inventory.</li>
<li>Provide integration hooks so the user can send orders to the warehouse and so the warehouse can send shipment data back.</li>
<li>Keep track of sales-order-to-invoice conversions and payments.</li>
<li>Provide reporting features.</li>
</ul>

<h3>QuickBooks 2010: Same as last year! Now with more shininess!</h3>

<p>You might take a look at integrating with QuickBooks, but you&#8217;d realize that once you&#8217;ve penetrated the marketing speak that the software in 2010 is essentially no different in terms of fundamental feature set as it was in 2006, and that it doesn&#8217;t support inventory in multiple locations and doesn&#8217;t scale well. In fact, QuickBooks performance once you start approaching 10,000 SKUs is so bad that they sell an &#8220;enterprise&#8221; version that essentially&#8211;aside from some fine-grained access permissions&#8211;has no added features other than the feature of not crashing when dealing with large lists of information.</p>

<p>We could pay another couple of thousand dollars for <a href="http://www.fishbowlinventory.com/products/pricing/">Fishbowl inventory</a>, which would add multiple location support to Quickbooks, but then we&#8217;d have created a Rube Goldberg machine straight out of the gate, with me synchronizing with Fishbowl which is then synchronizing with Quickbooks. I&#8217;m sure nothing would go wrong there. That would be insane; we might as well just stick a few fax machines into the sync process and call it an insurance company.</p>

<h3>A gap in the market</h3>

<p>The reality is that there is a huge gap in the marketplace between merchants who are moving $200k or less per year&#8211;just use commercial off-the-shelf (COTS) QuickBooks, you can do most things manually and use your e-commerce system&#8217;s native order management functions&#8211;and merchants who are moving $5m or more&#8211;just use SAP or some other enterprisey software. If you&#8217;re in between, like we are and like the merchant that I&#8217;m researching for is, the options available to you are not pretty.</p>

<p>I&#8217;m not sure why this is. All I can think of is that perhaps companies historically did not spend much time in this space&#8211;they either stayed small or had venture capital to acquire the big boy systems and grow quickly. People aren&#8217;t exactly lending money anymore, so I suspect that this is a segment that is only going to grow.</p>

<p>If you try to look for COTS software in this segment, you&#8217;ll never find the feature matrix that you need:</p>

<ul>
<li><a href="http://www.inflowinventory.com/">inFlow Inventory</a> is pretty, but offers no integration features, as if an entire business could be run out of one app, and doesn&#8217;t offer Web access.</li>
<li><a href="http://www.workingpoint.com/">WorkingPoint</a> is Web-based but doesn&#8217;t offer inventory tracking in multiple locations or an integration API.</li>
<li><a href="http://quickbooks.intuit.com/">QuickBooks</a> has a <a href="http://www.vi4qb.com/">Web-based</a> extension that lets QuickBooks understand multiple inventories but costs thousands of dollars, assumes that the company owns its own warehouse (that is, needing picking/packing/shipping capabilities), and still does the same style of synchronization as Fishbowl does. You&#8217;d think Intuit would just add the @#$#@ feature to QuickBooks itself!</li>
</ul>

<h3>No COTS to sleep in</h3>

<p>The market seems to have determined that people in this segment have outgrown COTS software and need some consulting help. So any Web sites that advertise products will be full of pages and pages of <a href="http://www.netsuite.com/portal/home.shtml">impenetrable marketing bullshit</a> that use obnoxious acronyms like ERP, CRM, MRP, and WMS, promise the moon, and coyly make no reference to pricing or contract requirements so you can&#8217;t even tell if you&#8217;re dealing with the right league of product, when the reality is at the end of the day you could look at two or three screenshots and the SDK&#8217;s API and immediately tell if the product fit your needs.</p>

<p>Instead, I notice a disturbing trend of &#8220;pretty Web site, crap product,&#8221; such as <a href="http://www.simplyaccounting.com/productsServices/compare_products/?WT.mc_id=hp_comp">Sage&#8217;s Simply Accounting</a>, which certainly appears to have an impressive array of features but in reality doesn&#8217;t even know the difference between a <a href="http://en.wikipedia.org/wiki/Sales_order">sales order</a> and an <a href="http://en.wikipedia.org/wiki/Invoice">invoice</a>. You can try going to <a href="http://www.microsoft.com/dynamics/en/us/default.aspx">Microsoft&#8217;s Dynamics site</a>, but good luck figuring out what the difference between Dynamics AX, Dynamics CRM, Dynamics NAV, and Dynamics GP are: you&#8217;ll be told to contact your &#8220;Microsoft Dynamics solutions representative&#8221; for help. At that point, you&#8217;re thinking &#8220;Microsoft solutions representative? Who said I committed to Microsoft?! I&#8217;m just trying to figure out <em>what in the blue hell your product even <strong>does</strong></em>.&#8221;</p>

<p>If you do find a vendor that maybe sorta-kinda-hard-to-tell meets your solutions, then you can expect days of scheduling WebEx teleconferences and meetings and run-around with your &#8220;account rep&#8221; so that they can determine how much you&#8217;re worth and willing to pay so that <a href="http://www.endicia.com/Developers/">they can charge you a completely different amount</a> than what they charged Bob next door for the same services and bits. Trying to extract &#8220;$X/user&#8221; and &#8220;the login starts working on MM/DD/YYYY&#8221; and &#8220;the developer get a demo account so if you can know if this is feasible&#8221; answers from these people seems to require a hammer in one hand and their genitals in the other. We both know that to add a new account, they&#8217;re pressing a button that says &#8220;they really bought into that &#8216;enterprise&#8217; crap&#8221; and poof! a new account is created. Let&#8217;s quit pretending that the world&#8217;s carbon footprint has increased ten-fold by us merely asking to be on the platform.</p>

<p>Trying to extract technical capabilities from these salespeople is nigh-impossible either. I think part of the problem is that they seem to actually believe that the features that they are promising really exist, when in reality I just need them to show me what the data dictionary looks like and how the session needs to be handled and then I can tell for myself whether or not my scenario is actually supported. Instead? I&#8217;m waiting on a &#8220;discovery session&#8221; teleconference with an &#8220;engineer&#8221; tomorrow.</p>

<h2>Conclusions and Delusions</h2>

<p>It has to be easier than this. No wonder there are so many not-invented-here software solutions in the world today&#8211;custom crap that barely works at home may yet indeed be better than generic crap that you have to waste hundreds of dollars on in productivity time and research before you even get it in your hands and realize that it is also crap, just with a maintenance contract.</p>

<p>If it takes a consultant to help people decide what software to buy, or which of your products is right for them, or whether or not your product <em>even applies to their problem domain</em>, then your marketing <em>simply does not work.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2010/01/buying-software-sucks/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Integration Testing with SQL Server Express 2008, NHibernate, and MSTEST</title>
		<link>http://nicholas.piasecki.name/blog/2010/01/integration-testing-with-sql-server-express-2008-nhibernate-and-mstest/</link>
		<comments>http://nicholas.piasecki.name/blog/2010/01/integration-testing-with-sql-server-express-2008-nhibernate-and-mstest/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 03:14:21 +0000</pubDate>
		<dc:creator>Nicholas Piasecki</dc:creator>
				<category><![CDATA[Programming]]></category>
		<category><![CDATA[csharp]]></category>
		<category><![CDATA[nhibernate]]></category>
		<category><![CDATA[testing]]></category>

		<guid isPermaLink="false">http://nicholas.piasecki.name/blog/?p=508</guid>
		<description><![CDATA[When dealing with NHibernate, I find that it&#8217;s important to write tests to make sure that I&#8217;ve created my mapping files correctly&#8211;that is, that properties actually are mapped correctly, that I remembered to specify an IUserType where appropriate, that I &#8230; <a href="http://nicholas.piasecki.name/blog/2010/01/integration-testing-with-sql-server-express-2008-nhibernate-and-mstest/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>When dealing with NHibernate, I find that it&#8217;s important to write tests to make sure that I&#8217;ve created my mapping files correctly&#8211;that is, that properties actually are mapped correctly, that I remembered to specify an <code>IUserType</code> where appropriate, that I remembered to make my properties <code>virtual</code>, that I remembered to add a parameterless constructor, that I set the right <code>cascade</code> option on an association, and so on.</p>

<p>It would be nice if I could run an automated test that would &#8220;exercise&#8221; my NHibernate mapping file against an actual database to see if it all worked. It&#8217;s not really a unit test&#8211;I&#8217;m not testing NHibernate itself, I&#8217;m testing my <em>configuration</em> of NHIbernate&#8211;but it&#8217;s still appropriate as an integration test.</p>

<p><a href="http://ayende.com/Blog/archive/2009/04/28/nhibernate-unit-testing.aspx">Ayende Rahien has a spiffy implementation</a> of an in-memory database test that uses NHibernate&#8217;s <code>SchemaExport</code> to build up an empty, in-memory SQLite database at the start of each NUnit test. His implementation serves as the inspiration for my example.</p>

<p>In my case, I&#8217;m working on a little moonlighting project that uses some database-specific features of SQL Server Express 2008, in particular the <code>GEOGRAPHY</code> type and <code>SPATIAL</code> indexes. SQLite wouldn&#8217;t help me here&#8211;unless I just didn&#8217;t want to use it for those particular tests&#8211;but I figure that if I&#8217;m bothering to write an integration test, then it should actually test the integration against the database that I&#8217;m actually using. Additionally, unlike Ayende&#8217;s example, I&#8217;m using MSTest instead of nUnit because it&#8217;s built into Visual Studio and I am a masochist.</p>

<h2>Understanding SQL Server Express User Instances</h2>

<p>SQL Server Express has the concept of a &#8220;user instance&#8221; that allows a non-administrator user to attach and detach an *.mdf file to the local SQL Server Express instance. I thought this was what I needed. But there are some things to understand about user instances that confused me and probably confuse other people as well:</p>

<ul>
<li>They&#8217;re not the same thing as an in-memory database or even a &#8220;file-based&#8221; database like SQLite. It&#8217;s a regular SQL Server database file.</li>
<li>The file has to exist. Unlike SQLite, if you tell SQL Server Express to attach to an *.mdf that isn&#8217;t there, you&#8217;ll get an error instead of having the database created for you just in time.</li>
<li>To access the database, it has to be attached to a SQL Server instance. This means downloading SQL Server Express and installing the service on the machine. It&#8217;s not as if your application can just directly access the *.mdf file through some special DLL or anything like that. It really is still client/server.</li>
<li>Permissions can still be an issue. The SQL Server instance will need to be able to read the *.mdf file, so the NTFS permissions need to be set appropriately; in most cases, this means that <code>NETWORK SERVICE</code> will need to be able to read and write to it.</li>
</ul>

<p>After spending a few hours learning such things the hard way, I realized that user instances were not necessary for me (VS already runs as administrator, can&#8217;t debug in IIS without it). Instead I&#8217;ll just use <a href="http://msdn.microsoft.com/en-us/library/ms162169.aspx">SQL Server Management Objects</a> (SMO) to programmatically set up the database at the start of each test. (More on this later.)</p>

<h2>Understanding MSTest Execution Order</h2>

<p>On my first attempt, I put my database and NHibernate set-up and tear-down code in methods decorated with the MSTest <code>[TestInitialize]</code> and <code>[TestCleanup]</code> attributes. And this does indeed work well when a single <code>[TestMethod]</code> is executed in isolation. But if I executed more than one test in a single test run, all hell would break loose because the <code>[TestInitialize]</code> for a test that is scheduled to execute might get executed before the <code>[TestCleanup]</code> from a test that has already run.</p>

<p>This seemed like astonishing behavior to me and seems to be just a quirk of Microsoft&#8217;s design of MSTest. In nUnit and pretty much any other xUnit framework I&#8217;ve tried, the initialize/test/cleanup triumvirate is guaranteed to execute &#8220;atomically&#8221; before any part of any other test triumvirate is executed. In other words, if you&#8217;re running a test run with two tests A and B, then you <em>might</em> see this behavior in the two testing frameworks:</p>

<ul>
<li>nUnit: Initialize A > Test A > Cleanup A > Initialize B > Test B > Cleanup B</li>
<li>MSTest: Initialize A > Test A > Initialize B > Cleanup A > Test B > Cleanup B</li>
</ul>

<p>That&#8217;s because MSTest executes tests in multiple threads, and while for a particular test method you&#8217;re guaranteed that its <code>[TestInitialize]</code> and <code>[TestCleanup]</code> methods will be called before and after the test itself executes, respectively, <a href="http://blogs.msdn.com/nnaderi/archive/2007/02/17/explaining-execution-order.aspx">there is no guarantee about its relationship with the other simultaneously executing test methods</a>.</p>

<p>This causes a problem when the test method is assuming exclusive access to a shared system resource, like a test SQL Server Express database that has just been set up for that test method&#8217;s exclusive use. My brute force workaround is to use <code>Monitor.Enter()</code> and <code>Monitor.Exit()</code> in the <code>[TestInitialize]</code> and <code>[TestCleanup]</code> methods to force MSTest to execute them in the correct order:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">object</span> lockObject <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> <span style="color: #6666cc; font-weight: bold;">object</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #008000;">&#91;</span>TestInitialize<span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> TestInitialize<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	Monitor<span style="color: #008000;">.</span><span style="color: #0000FF;">Enter</span><span style="color: #008000;">&#40;</span>lockObject<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">try</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">// TODO: Delete any pre-existing SQL Server Express Instance</span>
		<span style="color: #008080; font-style: italic;">// TODO: Set up the SQL Server Express Instance</span>
		<span style="color: #008080; font-style: italic;">// TODO: Set up NHibernate</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #0600FF; font-weight: bold;">catch</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">// If something went horribly wrong, release the lock</span>
		<span style="color: #008080; font-style: italic;">// or else MSTest will never finish the test run!</span>
		Monitor<span style="color: #008000;">.</span><span style="color: #0000FF;">Exit</span><span style="color: #008000;">&#40;</span>lockObject<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #0600FF; font-weight: bold;">throw</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #008000;">&#91;</span>TestCleanup<span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> TestCleanup<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	<span style="color: #008080; font-style: italic;">// TODO: Delete the SQL Server Express instance</span>
	Monitor<span style="color: #008000;">.</span><span style="color: #0000FF;">Exit</span><span style="color: #008000;">&#40;</span>lockObject<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<h2>Using SMO to Bind It All Together</h2>

<p>All that was left was to fill in those TODOs.</p>

<h3>Deleting an Existing Database</h3>

<p>First up is deleting an existing instance, which is pretty trivial with SMO (just add a reference to <code>Microsoft.SqlServer.Smo.dll</code>, which is available after you installing SQL Server Express, and you&#8217;re set):</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">string</span> serverInstance <span style="color: #008000;">=</span> <span style="color: #666666;">@&quot;(local)\SQLEXPRESS&quot;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #0600FF; font-weight: bold;">static</span> <span style="color: #0600FF; font-weight: bold;">readonly</span> <span style="color: #6666cc; font-weight: bold;">string</span> databaseName <span style="color: #008000;">=</span> <span style="color: #666666;">&quot;EquineTest&quot;</span><span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> dataFilePath<span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> logFilePath<span style="color: #008000;">;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> DeleteDatabaseIfExists<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	var server <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Server<span style="color: #008000;">&#40;</span>serverInstance<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>server<span style="color: #008000;">.</span><span style="color: #0000FF;">Databases</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Contains</span><span style="color: #008000;">&#40;</span>databaseName<span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #008080; font-style: italic;">// Something might be caching an open connection, so tell everyone</span>
		<span style="color: #008080; font-style: italic;">// to screw off by forcing their connections shut. If we don't do this,</span>
		<span style="color: #008080; font-style: italic;">// the DetachDatabase() call could faile.</span>
		var sql <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span>
			CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">InvariantCulture</span>,
			<span style="color: #666666;">&quot;ALTER DATABASE {0} SET SINGLE_USER WITH ROLLBACK IMMEDIATE&quot;</span>,
			databaseName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		server<span style="color: #008000;">.</span><span style="color: #0000FF;">Databases</span><span style="color: #008000;">&#91;</span>databaseName<span style="color: #008000;">&#93;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ExecuteNonQuery</span><span style="color: #008000;">&#40;</span>sql<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		server<span style="color: #008000;">.</span><span style="color: #0000FF;">DetachDatabase</span><span style="color: #008000;">&#40;</span>databaseName, <span style="color: #0600FF; font-weight: bold;">true</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		File<span style="color: #008000;">.</span><span style="color: #0000FF;">Delete</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">dataFilePath</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		File<span style="color: #008000;">.</span><span style="color: #0000FF;">Delete</span><span style="color: #008000;">&#40;</span><span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">logFilePath</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>Why check for an delete an existing database at the start of a test? In case a previous test failed. Shockingly, MSTest won&#8217;t call <code>[TestCleanup]</code> if a test method explodes with an exception. I know, I&#8217;m in total agreement with you, what were they thinking?</p>

<h3>Figuring Out Where to Put the Files</h3>

<p>Simple enough, but you&#8217;ll notice that my <code>dataFilePath</code> and <code>logFilePath</code> variables, which should be pointing to my *.mdf and *.ldf database files, respectively, aren&#8217;t initialized in my above example. Prior to calling this function, I make sure that my <code>InitializePaths()</code> method is called:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">string</span> GetExecutingDirectory<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	var path <span style="color: #008000;">=</span> Assembly<span style="color: #008000;">.</span><span style="color: #0000FF;">GetExecutingAssembly</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetName</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CodeBase</span><span style="color: #008000;">;</span>
	<span style="color: #0600FF; font-weight: bold;">return</span> Path<span style="color: #008000;">.</span><span style="color: #0000FF;">GetDirectoryName</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> Uri<span style="color: #008000;">&#40;</span>path<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">LocalPath</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span>
&nbsp;
<span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> InitializePaths<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	var directoryPath <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">GetExecutingDirectory</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">dataFilePath</span> <span style="color: #008000;">=</span> Path<span style="color: #008000;">.</span><span style="color: #0000FF;">Combine</span><span style="color: #008000;">&#40;</span>directoryPath, databaseName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;.mdf&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">logFilePath</span> <span style="color: #008000;">=</span> Path<span style="color: #008000;">.</span><span style="color: #0000FF;">Combine</span><span style="color: #008000;">&#40;</span>directoryPath, databaseName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;_log.ldf&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>This is convoluted way of determining the directory that MSTest created for the current test run. (MSTest sets the working directory to some nonsense in Program Files, so no help there. And <code>[DeploymentItem()]</code> is an absolute nightmare!)</p>

<h3>Creating the Test Database</h3>

<p>The code for creating the database via SMO is similarly straightforward:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #0600FF; font-weight: bold;">private</span> <span style="color: #6666cc; font-weight: bold;">void</span> CreateDatabase<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	var server <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Server<span style="color: #008000;">&#40;</span>serverInstance<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	var database <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Database<span style="color: #008000;">&#40;</span>server, databaseName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var fileGroup <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> FileGroup<span style="color: #008000;">&#40;</span>database, <span style="color: #666666;">&quot;PRIMARY&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	database<span style="color: #008000;">.</span><span style="color: #0000FF;">FileGroups</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>fileGroup<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var dataFile <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> DataFile<span style="color: #008000;">&#40;</span>fileGroup, databaseName, <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">dataFilePath</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	dataFile<span style="color: #008000;">.</span><span style="color: #0000FF;">Growth</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span>
	dataFile<span style="color: #008000;">.</span><span style="color: #0000FF;">GrowthType</span> <span style="color: #008000;">=</span> FileGrowthType<span style="color: #008000;">.</span><span style="color: #0000FF;">Percent</span><span style="color: #008000;">;</span>
	fileGroup<span style="color: #008000;">.</span><span style="color: #0000FF;">Files</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>dataFile<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	var logFile <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> LogFile<span style="color: #008000;">&#40;</span>database, databaseName <span style="color: #008000;">+</span> <span style="color: #666666;">&quot;_log&quot;</span>, <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">logFilePath</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	logFile<span style="color: #008000;">.</span><span style="color: #0000FF;">Growth</span> <span style="color: #008000;">=</span> <span style="color: #FF0000;">10</span><span style="color: #008000;">;</span>
	logFile<span style="color: #008000;">.</span><span style="color: #0000FF;">GrowthType</span> <span style="color: #008000;">=</span> FileGrowthType<span style="color: #008000;">.</span><span style="color: #0000FF;">Percent</span><span style="color: #008000;">;</span>
	database<span style="color: #008000;">.</span><span style="color: #0000FF;">LogFiles</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Add</span><span style="color: #008000;">&#40;</span>logFile<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	database<span style="color: #008000;">.</span><span style="color: #0000FF;">Create</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>The only quirk is that I explicitly set the <code>Growth</code> and <code>GrowthType</code> because on some machines it was defaulting to <code>None</code> causing the integration tests to fail when lots of data is inserted under some circumstances. It seems to be a per-server default setting, but I haven&#8217;t bothered to figure out why the default behavior is different among the multiple machines that I own; setting it here guarantees the tests will work consistently.</p>

<h3>Initializing the Database and Configuring NHibernate</h3>

<p>The last piece of the puzzle is to configure NHibernate and set up the freshly-minted database&#8217;s schema. I use the NHibernate&#8217;s <code>SchemaExport</code> tool to create the schema for me based on my mapping files. The only caveat is that when using SQL <code>SCHEMA</code>s, the <code>SchemaExport</code> tool won&#8217;t create those for you, so they have to be handled explicitly:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>TestInitialize<span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> TestInitialize<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
<span style="color: #008000;">&#123;</span>
	Monitor<span style="color: #008000;">.</span><span style="color: #0000FF;">Enter</span><span style="color: #008000;">&#40;</span>lockObject<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
	<span style="color: #0600FF; font-weight: bold;">try</span>
	<span style="color: #008000;">&#123;</span>
		<span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">InitializePaths</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">DeleteDatabaseIfExists</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CreateDatabase</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #008080; font-style: italic;">// The configuration is a static variable, I don't care if the</span>
		<span style="color: #008080; font-style: italic;">// configuration is shared among test methods</span>
		<span style="color: #0600FF; font-weight: bold;">if</span> <span style="color: #008000;">&#40;</span>configuration <span style="color: #008000;">==</span> <span style="color: #0600FF; font-weight: bold;">null</span><span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			<span style="color: #008080; font-style: italic;">// Disabling connection pooling is important</span>
			var connectionString <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span>
				CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">InvariantCulture</span>,
				<span style="color: #666666;">@&quot;Data Source={0}; Integrated Security=true; Initial Catalog={1}; Connection Timeout=120; Pooling=false;&quot;</span>,
				serverInstance,
				databaseName<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
			configuration <span style="color: #008000;">=</span> <span style="color: #008000;">new</span> Configuration<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
				<span style="color: #008000;">.</span><span style="color: #0000FF;">SetProperty</span><span style="color: #008000;">&#40;</span>Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">ReleaseConnections</span>, <span style="color: #666666;">&quot;on_close&quot;</span><span style="color: #008000;">&#41;</span>
				<span style="color: #008000;">.</span><span style="color: #0000FF;">SetProperty</span><span style="color: #008000;">&#40;</span>Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">Dialect</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>MsSql2008Dialect<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AssemblyQualifiedName</span><span style="color: #008000;">&#41;</span>
				<span style="color: #008000;">.</span><span style="color: #0000FF;">SetProperty</span><span style="color: #008000;">&#40;</span>Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">ConnectionDriver</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>SqlClientDriver<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AssemblyQualifiedName</span><span style="color: #008000;">&#41;</span>
				<span style="color: #008000;">.</span><span style="color: #0000FF;">SetProperty</span><span style="color: #008000;">&#40;</span>Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">ConnectionString</span>, connectionString<span style="color: #008000;">&#41;</span>
				<span style="color: #008000;">.</span><span style="color: #0000FF;">SetProperty</span><span style="color: #008000;">&#40;</span>Environment<span style="color: #008000;">.</span><span style="color: #0000FF;">ProxyFactoryFactoryClass</span>, <span style="color: #008000;">typeof</span><span style="color: #008000;">&#40;</span>ProxyFactoryFactory<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">AssemblyQualifiedName</span><span style="color: #008000;">&#41;</span>
				<span style="color: #008000;">.</span><span style="color: #0000FF;">AddAssembly</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;EquineBusinessBureau.Model&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
			sessionFactory <span style="color: #008000;">=</span> configuration<span style="color: #008000;">.</span><span style="color: #0000FF;">BuildSessionFactory</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #008000;">&#125;</span>
&nbsp;
		<span style="color: #008080; font-style: italic;">// We definitely need a new session for each test method, though</span>
		<span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">session</span> <span style="color: #008000;">=</span> sessionFactory<span style="color: #008000;">.</span><span style="color: #0000FF;">OpenSession</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #008080; font-style: italic;">// SchemaExport won't create the database schemas for us</span>
		<span style="color: #0600FF; font-weight: bold;">foreach</span> <span style="color: #008000;">&#40;</span><span style="color: #6666cc; font-weight: bold;">string</span> schema <span style="color: #0600FF; font-weight: bold;">in</span> schemas<span style="color: #008000;">&#41;</span>
		<span style="color: #008000;">&#123;</span>
			var sql <span style="color: #008000;">=</span> <span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Format</span><span style="color: #008000;">&#40;</span>CultureInfo<span style="color: #008000;">.</span><span style="color: #0000FF;">InvariantCulture</span>, <span style="color: #666666;">&quot;CREATE SCHEMA {0}&quot;</span>, schema<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
			<span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">session</span><span style="color: #008000;">.</span><span style="color: #0000FF;">CreateSQLQuery</span><span style="color: #008000;">&#40;</span>sql<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">ExecuteUpdate</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
		<span style="color: #008000;">&#125;</span>
&nbsp;
		<span style="color: #008000;">new</span> SchemaExport<span style="color: #008000;">&#40;</span>configuration<span style="color: #008000;">&#41;</span><span style="color: #008000;">.</span><span style="color: #0000FF;">Execute</span><span style="color: #008000;">&#40;</span>
			<span style="color: #0600FF; font-weight: bold;">true</span>,
			<span style="color: #0600FF; font-weight: bold;">true</span>,
			<span style="color: #0600FF; font-weight: bold;">false</span>,
			session<span style="color: #008000;">.</span><span style="color: #0000FF;">Connection</span>,
			Console<span style="color: #008000;">.</span><span style="color: #0600FF; font-weight: bold;">Out</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
	<span style="color: #0600FF; font-weight: bold;">catch</span>
	<span style="color: #008000;">&#123;</span>
&nbsp;
		Monitor<span style="color: #008000;">.</span><span style="color: #0000FF;">Exit</span><span style="color: #008000;">&#40;</span>lockObject<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
		<span style="color: #0600FF; font-weight: bold;">throw</span><span style="color: #008000;">;</span>
	<span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<h2>Conclusions and Delusions</h2>

<p>Wrap all of this up in an abstract class called <code>IntegrationTestBase</code>, and you&#8217;ve got an easy way to write integration tests in a style that&#8217;s similar to what Ayende originally posted:</p>


<div class="wp_syntax"><div class="code"><pre class="csharp" style="font-family:monospace;"><span style="color: #008000;">&#91;</span>TestClass<span style="color: #008000;">&#93;</span>
<span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">class</span> RoleTest <span style="color: #008000;">:</span> InMemoryDatabaseTestBase
<span style="color: #008000;">&#123;</span>
    <span style="color: #008000;">&#91;</span>TestMethod<span style="color: #008000;">&#93;</span>
    <span style="color: #0600FF; font-weight: bold;">public</span> <span style="color: #6666cc; font-weight: bold;">void</span> CanSaveAndLoadRole<span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span>
    <span style="color: #008000;">&#123;</span>
        <span style="color: #6666cc; font-weight: bold;">object</span> identity<span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var tx <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">session</span><span style="color: #008000;">.</span><span style="color: #0000FF;">BeginTransaction</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            identity <span style="color: #008000;">=</span> session<span style="color: #008000;">.</span><span style="color: #0000FF;">Save</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">new</span> Role<span style="color: #008000;">&#40;</span>EquineRoles<span style="color: #008000;">.</span><span style="color: #0000FF;">Administrator</span>, <span style="color: #666666;">&quot;Administrator&quot;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            tx<span style="color: #008000;">.</span><span style="color: #0000FF;">Commit</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
&nbsp;
        session<span style="color: #008000;">.</span><span style="color: #0000FF;">Clear</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
        <span style="color: #0600FF; font-weight: bold;">using</span> <span style="color: #008000;">&#40;</span>var tx <span style="color: #008000;">=</span> <span style="color: #0600FF; font-weight: bold;">this</span><span style="color: #008000;">.</span><span style="color: #0000FF;">session</span><span style="color: #008000;">.</span><span style="color: #0000FF;">BeginTransaction</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">&#41;</span>
        <span style="color: #008000;">&#123;</span>
            var role <span style="color: #008000;">=</span> session<span style="color: #008000;">.</span><span style="color: #0000FF;">Get</span><span style="color: #008000;">&lt;</span>role<span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>identity<span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            Assert<span style="color: #008000;">.</span><span style="color: #0000FF;">AreEqual</span><span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span>EquineRoles<span style="color: #008000;">.</span><span style="color: #0000FF;">Administrator</span>, role<span style="color: #008000;">.</span><span style="color: #0000FF;">RoleEnum</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
            Assert<span style="color: #008000;">.</span><span style="color: #0000FF;">AreEqual</span><span style="color: #008000;">&lt;</span><span style="color: #6666cc; font-weight: bold;">string</span><span style="color: #008000;">&gt;</span><span style="color: #008000;">&#40;</span><span style="color: #666666;">&quot;Administrator&quot;</span>, role<span style="color: #008000;">.</span><span style="color: #0000FF;">RoleName</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
&nbsp;
            tx<span style="color: #008000;">.</span><span style="color: #0000FF;">Commit</span><span style="color: #008000;">&#40;</span><span style="color: #008000;">&#41;</span><span style="color: #008000;">;</span>
        <span style="color: #008000;">&#125;</span>
    <span style="color: #008000;">&#125;</span>
<span style="color: #008000;">&#125;</span></pre></div></div>


<p>The first test in a test run takes a while to run, on the order of 6 &#8211; 8 seconds. Painful, but this is also an integration test, so it&#8217;s not like I&#8217;m running them every five minutes, and it&#8217;s faster than spinning up the Web site and seeing if it crashed. Subsequent tests, since the NHibernate configuration is already initialized in the static variable, execute much more quickly, about one second per test.</p>

<p>Hope this saves someone a few hours of putting the puzzle pieces together.</p>

<p><a href='http://nicholas.piasecki.name/blog/wp-content/uploads/2010/01/IntegrationTestBase.cs_.txt'>Download the IntegrationTestBase example source file.</a></p>
]]></content:encoded>
			<wfw:commentRss>http://nicholas.piasecki.name/blog/2010/01/integration-testing-with-sql-server-express-2008-nhibernate-and-mstest/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

