<?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>JohnnyCoder &#187; C#</title>
	<atom:link href="http://johnnycoder.com/blog/category/c/feed/" rel="self" type="application/rss+xml" />
	<link>http://johnnycoder.com/blog</link>
	<description></description>
	<lastBuildDate>Wed, 03 Nov 2010 17:07:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>C# Multiple Property Sort</title>
		<link>http://johnnycoder.com/blog/2010/03/30/c-multiple-property-sort/</link>
		<comments>http://johnnycoder.com/blog/2010/03/30/c-multiple-property-sort/#comments</comments>
		<pubDate>Tue, 30 Mar 2010 19:14:25 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[LINQ]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2010/03/30/c-multiple-property-sort/</guid>
		<description><![CDATA[As you can see in the snippet below, sorting is easy with Linq.&#160; Simply provide your OrderBy criteria and you’re done.&#160; If you want a secondary sort field, add a ThenBy expression to the chain.&#160; Want a third level sort?&#160; Just add ThenBy along with another sort expression. var projects = new List&#60;Project&#62; &#160;&#160;&#160;&#160;{ &#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;new [...]]]></description>
			<content:encoded><![CDATA[<p>As you can see in the snippet below, sorting is easy with Linq.&#160; Simply provide your OrderBy criteria and you’re done.&#160; If you want a secondary sort field, add a ThenBy expression to the chain.&#160; Want a third level sort?&#160; Just add ThenBy along with another sort expression. </p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:edf411d9-baf9-43aa-8b61-1e9cc28fa0c4" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px; white-space: nowrap">
<li><span style="color:#0000ff">var</span> projects = <span style="color:#0000ff">new</span> <span style="color:#2b91af">List</span>&lt;<span style="color:#2b91af">Project</span>&gt;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;{</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">new</span> <span style="color:#2b91af">Project</span> {Description = <span style="color:#a31515">&quot;A&quot;</span>, ProjectStatusTypeId = 1},</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">new</span> <span style="color:#2b91af">Project</span> {Description = <span style="color:#a31515">&quot;B&quot;</span>, ProjectStatusTypeId = 3},</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">new</span> <span style="color:#2b91af">Project</span> {Description = <span style="color:#a31515">&quot;C&quot;</span>, ProjectStatusTypeId = 3},</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">new</span> <span style="color:#2b91af">Project</span> {Description = <span style="color:#a31515">&quot;C&quot;</span>, ProjectStatusTypeId = 2},</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">new</span> <span style="color:#2b91af">Project</span> {Description = <span style="color:#a31515">&quot;E&quot;</span>, ProjectStatusTypeId = 1},</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">new</span> <span style="color:#2b91af">Project</span> {Description = <span style="color:#a31515">&quot;A&quot;</span>, ProjectStatusTypeId = 2},</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">new</span> <span style="color:#2b91af">Project</span> {Description = <span style="color:#a31515">&quot;C&quot;</span>, ProjectStatusTypeId = 4},</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">new</span> <span style="color:#2b91af">Project</span> {Description = <span style="color:#a31515">&quot;A&quot;</span>, ProjectStatusTypeId = 3}</li>
<li>&#160;&#160;&#160;&#160;};</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>projects = projects</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;.OrderBy(x =&gt; x.Description)</li>
<li>&#160;&#160;&#160;&#160;.ThenBy(x =&gt; x.ProjectStatusTypeId)</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;.ToList();</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">foreach</span> (<span style="color:#0000ff">var</span> project <span style="color:#0000ff">in</span> projects)</li>
<li>{</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#2b91af">Console</span>.Out.WriteLine(<span style="color:#a31515">&quot;{0} {1}&quot;</span>, project.Description, </li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;project.ProjectStatusTypeId);</li>
<li style="background: #f3f3f3">}</li>
</ol></div>
</p></div>
</p></div>
</p>
<p>Linq offers a great sort solution most of the time, but what if you want or need to do it the old fashioned way?</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:b7f47fbe-e63f-4f84-94e6-3d104a894e9d" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px; white-space: nowrap">
<li>projects.Sort ((x, y) =&gt;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#2b91af">Comparer</span>&lt;<span style="color:#2b91af">String</span>&gt;.Default</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;.Compare(x.Description, y.Description) != 0 ?</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#2b91af">Comparer</span>&lt;<span style="color:#2b91af">String</span>&gt;.Default</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;.Compare(x.Description, y.Description) :</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#2b91af">Comparer</span>&lt;<span style="color:#2b91af">Int32</span>&gt;.Default</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;.Compare(x.ProjectStatusTypeId, y.ProjectStatusTypeId));</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#0000ff">foreach</span> (<span style="color:#0000ff">var</span> project <span style="color:#0000ff">in</span> projects)</li>
<li style="background: #f3f3f3">{</li>
<li>&#160;&#160;&#160;&#160;<span style="color:#2b91af">Console</span>.Out.WriteLine(<span style="color:#a31515">&quot;{0} {1}&quot;</span>, project.Description,</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;project.ProjectStatusTypeId);</li>
<li>}</li>
</ol></div>
</p></div>
</p></div>
<p>It’s not that bad, right?</p>
<p>Just for fun, let add some additional logic to our sort.&#160; Let’s say we wanted our secondary sort to be based on the name associated with the ProjectStatusTypeId.&#160; </p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:5c063938-9011-4e96-a0e7-52986cc8be0c" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #fff; overflow: auto">
<ol style="background: #ffffff; margin: 0; padding: 0 0 0 5px; white-space: nowrap">
<li>projects.Sort((x, y) =&gt;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#2b91af">Comparer</span>&lt;<span style="color:#2b91af">String</span>&gt;.Default</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;.Compare(x.Description, y.Description) != 0 ?</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#2b91af">Comparer</span>&lt;<span style="color:#2b91af">String</span>&gt;.Default</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;.Compare(x.Description, y.Description) :</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#2b91af">Comparer</span>&lt;<span style="color:#2b91af">String</span>&gt;.Default</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;.Compare(GetProjectStatusTypeName(x.ProjectStatusTypeId), </li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;GetProjectStatusTypeName(y.ProjectStatusTypeId)));</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">foreach</span> (<span style="color:#0000ff">var</span> project <span style="color:#0000ff">in</span> projects)</li>
<li>{</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#2b91af">Console</span>.Out.WriteLine(<span style="color:#a31515">&quot;{0} {1}&quot;</span>, project.Description, </li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;GetProjectStatusTypeName(project.ProjectStatusTypeId));</li>
<li style="background: #f3f3f3">}</li>
</ol></div>
</p></div>
</p></div>
<p>The comparer will now consider the result of the GetProjectStatusTypeName and order the list accordingly.&#160; Of course, you can take this same approach with Linq as well.</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2010/03/30/c-multiple-property-sort/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>ASP.NET Meta Keywords and Description</title>
		<link>http://johnnycoder.com/blog/2010/01/05/aspnet-meta-keywords-and-description/</link>
		<comments>http://johnnycoder.com/blog/2010/01/05/aspnet-meta-keywords-and-description/#comments</comments>
		<pubDate>Tue, 05 Jan 2010 17:11:23 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2010/01/05/aspnet-meta-keywords-and-description/</guid>
		<description><![CDATA[Some of the ASP.NET 4 improvements around SEO are neat.&#160; The ASP.NET 4 Page.MetaKeywords and Page.MetaDescription properties, for example, are a welcomed change.&#160; There’s nothing earth-shattering going on here – you can now set these meta tags via your Master page’s code behind rather than relying on updates to your markup alone.&#160; It isn’t difficult [...]]]></description>
			<content:encoded><![CDATA[<p>Some of the ASP.NET 4 improvements around SEO are neat.&#160; The <a href="http://weblogs.asp.net/scottgu/archive/2010/01/05/asp-net-4-seo-improvements-vs-2010-and-net-4-0-series.aspx">ASP.NET 4 Page.MetaKeywords and Page.MetaDescription properties</a>, for example, are a welcomed change.&#160; There’s nothing earth-shattering going on here – you can now set these meta tags via your Master page’s code behind rather than relying on updates to your markup alone.&#160; It isn’t difficult to manage meta keywords and descriptions without these ASP.NET 4 properties but I still appreciate the attention SEO is getting.&#160; It’s nice to get gentle reminder via new coding features that some of the more subtle aspects of one’s application deserve thought and attention too.&#160; </p>
<p>For the record, this is how I currently manage my meta:    </p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:ac73426b-7c10-4b24-b793-734651a91082" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #ddd; max-height: 400px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2em; padding: 0 0 0 5px; white-space: nowrap">
<li><span style="color:#0000ff">&lt;</span><span style="color:#a31515">meta</span> <span style="color:#ff0000">name</span><span style="color:#0000ff">=&quot;keywords&quot;</span> </li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#ff0000">content</span><span style="color:#0000ff">=&quot;</span><span style="background:#ffee62">&lt;%</span>= Html.Encode(ConfigurationManager.AppSettings[&quot;Meta.Keywords&quot;]) <span style="background:#ffee62">%&gt;</span><span style="color:#0000ff">&quot;</span> <span style="color:#0000ff">/&gt;</span></li>
<li><span style="color:#0000ff">&lt;</span><span style="color:#a31515">meta</span> <span style="color:#ff0000">name</span><span style="color:#0000ff">=&quot;description&quot;</span> </li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#ff0000">content</span><span style="color:#0000ff">=&quot;</span><span style="background:#ffee62">&lt;%</span>= Html.Encode(ConfigurationManager.AppSettings[&quot;Meta.Description&quot;]) <span style="background:#ffee62">%&gt;</span><span style="color:#0000ff">&quot;</span> <span style="color:#0000ff">/&gt;</span></li>
</ol></div>
</p></div>
</p></div>
</p>
<p>All Master pages assume the same keywords and description values as defined by the application settings.&#160; Nothing fancy. Nothing dynamic. But it’s manageable.&#160; It works, but I’m looking forward to the new way in ASP.NET 4.</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2010/01/05/aspnet-meta-keywords-and-description/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>C# HashSet&lt;T&gt;</title>
		<link>http://johnnycoder.com/blog/2009/12/22/c-hashsett/</link>
		<comments>http://johnnycoder.com/blog/2009/12/22/c-hashsett/#comments</comments>
		<pubDate>Tue, 22 Dec 2009 23:19:26 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2009/12/22/c-hashsett/</guid>
		<description><![CDATA[I hadn’t done much (read: anything) with the C# generic HashSet until I recently needed to produce a distinct collection.&#160; As it turns out, HashSet&#60;T&#62; was the perfect tool. As the following snippet demonstrates, this collection type offers a lot: // Using HashSet&#60;T&#62;: // http://www.albahari.com/nutshell/ch07.aspx var letters = new HashSet&#60;char&#62;(&#34;the quick brown fox&#34;); &#160; Console.WriteLine(letters.Contains(&#39;t&#39;)); [...]]]></description>
			<content:encoded><![CDATA[<p>I hadn’t done much (read: anything) with the C# generic HashSet until I recently needed to produce a distinct collection.&#160; As it turns out, HashSet&lt;T&gt; was the perfect tool.</p>
<p>As <a href="http://www.albahari.com/nutshell/ch07.aspx">the following snippet</a> demonstrates, this collection type offers a lot:</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:f1e70c38-3d90-4db4-9252-736d0bbfc11e" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #ddd; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px; white-space: nowrap">
<li><span style="color:#008000">// Using HashSet&lt;T&gt;:</span></li>
<li style="background: #f3f3f3"><span style="color:#008000">// http://www.albahari.com/nutshell/ch07.aspx</span></li>
<li><span style="color:#0000ff">var</span> letters = <span style="color:#0000ff">new</span> <span style="color:#2b91af">HashSet</span>&lt;<span style="color:#0000ff">char</span>&gt;(<span style="color:#a31515">&quot;the quick brown fox&quot;</span>);</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#2b91af">Console</span>.WriteLine(letters.Contains(<span style="color:#a31515">&#39;t&#39;</span>)); <span style="color:#008000">// true</span></li>
<li style="background: #f3f3f3"><span style="color:#2b91af">Console</span>.WriteLine(letters.Contains(<span style="color:#a31515">&#39;j&#39;</span>)); <span style="color:#008000">// false</span></li>
<li>&nbsp;</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">foreach</span> (<span style="color:#0000ff">char</span> c <span style="color:#0000ff">in</span> letters) <span style="color:#2b91af">Console</span>.Write(c); <span style="color:#008000">// the quickbrownfx</span></li>
<li><span style="color:#2b91af">Console</span>.WriteLine();</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>letters = <span style="color:#0000ff">new</span> <span style="color:#2b91af">HashSet</span>&lt;<span style="color:#0000ff">char</span>&gt;(<span style="color:#a31515">&quot;the quick brown fox&quot;</span>);</li>
<li style="background: #f3f3f3">letters.IntersectWith(<span style="color:#a31515">&quot;aeiou&quot;</span>);</li>
<li><span style="color:#0000ff">foreach</span> (<span style="color:#0000ff">char</span> c <span style="color:#0000ff">in</span> letters) <span style="color:#2b91af">Console</span>.Write(c); <span style="color:#008000">// euio</span></li>
<li style="background: #f3f3f3"><span style="color:#2b91af">Console</span>.WriteLine();</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">letters = <span style="color:#0000ff">new</span> <span style="color:#2b91af">HashSet</span>&lt;<span style="color:#0000ff">char</span>&gt;(<span style="color:#a31515">&quot;the quick brown fox&quot;</span>);</li>
<li>letters.ExceptWith(<span style="color:#a31515">&quot;aeiou&quot;</span>);</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">foreach</span> (<span style="color:#0000ff">char</span> c <span style="color:#0000ff">in</span> letters) <span style="color:#2b91af">Console</span>.Write(c); <span style="color:#008000">// th qckbrwnfx</span></li>
<li><span style="color:#2b91af">Console</span>.WriteLine();</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>letters = <span style="color:#0000ff">new</span> <span style="color:#2b91af">HashSet</span>&lt;<span style="color:#0000ff">char</span>&gt;(<span style="color:#a31515">&quot;the quick brown fox&quot;</span>);</li>
<li style="background: #f3f3f3">letters.SymmetricExceptWith(<span style="color:#a31515">&quot;the lazy brown fox&quot;</span>);</li>
<li><span style="color:#0000ff">foreach</span> (<span style="color:#0000ff">char</span> c <span style="color:#0000ff">in</span> letters) <span style="color:#2b91af">Console</span>.Write(c); <span style="color:#008000">// quicklazy</span></li>
<li style="background: #f3f3f3"><span style="color:#2b91af">Console</span>.WriteLine();</li>
</ol></div>
</p></div>
</p></div>
<p>The MSDN documentation is a bit light on HashSet&lt;T&gt; documentation but if you search hard enough you can find <a href="http://www.stumbleupon.com/su/2LkQ6v/www.vcskicks.com/hashset.php">some interesting information and benchmarks</a>.</p>
<p>But back to that distinct list I needed…</p>
</p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:8a25ddd4-9440-4d17-8743-c027fba26f12" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #ddd; max-height: 300px; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px;">
<li><span style="color:#0000ff">var</span> coderA = <span style="color:#0000ff">new</span> <span style="color:#2b91af">Employee</span> { Id = 1, Name = <span style="color:#a31515">&quot;Coder A&quot;</span> };</li>
<li style="background: #f3f3f3"><span style="color:#0000ff">var</span> coderB = <span style="color:#0000ff">new</span> <span style="color:#2b91af">Employee</span> { Id = 2, Name = <span style="color:#a31515">&quot;Coder B&quot;</span> };</li>
<li><span style="color:#0000ff">var</span> coderC = <span style="color:#0000ff">new</span> <span style="color:#2b91af">Employee</span> { Id = 3, Name = <span style="color:#a31515">&quot;Coder C&quot;</span> };</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#008000">// Coder A is being added to both lists</span></li>
<li style="background: #f3f3f3"><span style="color:#0000ff">var</span> cSharpCoders = <span style="color:#0000ff">new</span> <span style="color:#2b91af">List</span>&lt;<span style="color:#2b91af">Employee</span>&gt; { coderA, coderB };</li>
<li><span style="color:#0000ff">var</span> fSharpCoders = <span style="color:#0000ff">new</span> <span style="color:#2b91af">List</span>&lt;<span style="color:#2b91af">Employee</span>&gt; { coderA, coderC };</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#0000ff">var</span> coders = <span style="color:#0000ff">new</span> <span style="color:#2b91af">HashSet</span>&lt;<span style="color:#2b91af">Employee</span>&gt;();</li>
<li style="background: #f3f3f3">cSharpCoders.ForEach(x =&gt; coders.Add(x));</li>
<li>fSharpCoders.ForEach(x =&gt; coders.Add(x));</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li><span style="color:#0000ff">foreach</span> (<span style="color:#2b91af">Employee</span> c <span style="color:#0000ff">in</span> coders) <span style="color:#2b91af">Console</span>.WriteLine(c);</li>
<li style="background: #f3f3f3"><span style="color:#008000">// Returns a unique list set &#8212; Coder A Coder B Coder C </span></li>
</ol></div>
</p></div>
</p></div>
<p>The Add Method returns true on success and, you guessed it, false if the item couldn’t be added to the collection.&#160; I’m using the Linq ForEach syntax to add all valid items to the employees HashSet.&#160; It works really great.&#160; </p>
<p>This is just a rough sample, but you may have noticed I’m using Employee, a reference type.&#160; Most samples demonstrate the power of the HashSet with a collection of integers which is kind of cheating.&#160; With value types you don’t have to worry about defining your own equality members.&#160; With reference types, you do. </p>
<div style="padding-bottom: 0px; margin: 0px; padding-left: 0px; padding-right: 0px; display: inline; float: none; padding-top: 0px" id="scid:9ce6104f-a9aa-4a17-a79f-3a39532ebf7c:0fd83c1c-da3d-406c-81e2-7bfe400386e5" class="wlWriterEditableSmartContent">
<div style="border: #000080 1px solid; color: #000; font-family: 'Courier New', Courier, Monospace; font-size: 10pt">
<div style="background: #ddd; overflow: auto">
<ol style="background: #ffffff; margin: 0 0 0 2.5em; padding: 0 0 0 5px; white-space: nowrap">
<li><span style="color:#0000ff">internal</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">Employee</span></li>
<li style="background: #f3f3f3">{</li>
<li>&#160;&#160;&#160;&#160;<span style="color:#0000ff">public</span> <span style="color:#0000ff">int</span> Id { <span style="color:#0000ff">get</span>; <span style="color:#0000ff">set</span>; }</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#0000ff">public</span> <span style="color:#0000ff">string</span> Name { <span style="color:#0000ff">get</span>; <span style="color:#0000ff">set</span>; }</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#0000ff">public</span> <span style="color:#0000ff">override</span> <span style="color:#0000ff">string</span> ToString()</li>
<li>&#160;&#160;&#160;&#160;{</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">return</span> Name;</li>
<li>&#160;&#160;&#160;&#160;}</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;</li>
<li>&#160;&#160;&#160;&#160;<span style="color:#0000ff">public</span> <span style="color:#0000ff">bool</span> Equals(<span style="color:#2b91af">Employee</span> other)</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;{</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">if</span> (ReferenceEquals(<span style="color:#0000ff">null</span>, other)) <span style="color:#0000ff">return</span> <span style="color:#0000ff">false</span>;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">if</span> (ReferenceEquals(<span style="color:#0000ff">this</span>, other)) <span style="color:#0000ff">return</span> <span style="color:#0000ff">true</span>;</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">return</span> other.Id == Id;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;}</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#0000ff">public</span> <span style="color:#0000ff">override</span> <span style="color:#0000ff">bool</span> Equals(<span style="color:#0000ff">object</span> obj)</li>
<li>&#160;&#160;&#160;&#160;{</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">if</span> (ReferenceEquals(<span style="color:#0000ff">null</span>, obj)) <span style="color:#0000ff">return</span> <span style="color:#0000ff">false</span>;</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">if</span> (ReferenceEquals(<span style="color:#0000ff">this</span>, obj)) <span style="color:#0000ff">return</span> <span style="color:#0000ff">true</span>;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">if</span> (obj.GetType() != <span style="color:#0000ff">typeof</span> (<span style="color:#2b91af">Employee</span>)) <span style="color:#0000ff">return</span> <span style="color:#0000ff">false</span>;</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">return</span> Equals((<span style="color:#2b91af">Employee</span>) obj);</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;}</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#0000ff">public</span> <span style="color:#0000ff">override</span> <span style="color:#0000ff">int</span> GetHashCode()</li>
<li>&#160;&#160;&#160;&#160;{</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">return</span> Id;</li>
<li>&#160;&#160;&#160;&#160;}</li>
<li style="background: #f3f3f3">&nbsp;</li>
<li>&#160;&#160;&#160;&#160;<span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">bool</span> <span style="color:#0000ff">operator</span> ==(<span style="color:#2b91af">Employee</span> left, <span style="color:#2b91af">Employee</span> right)</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;{</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">return</span> Equals(left, right);</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;}</li>
<li>&nbsp;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#0000ff">public</span> <span style="color:#0000ff">static</span> <span style="color:#0000ff">bool</span> <span style="color:#0000ff">operator</span> !=(<span style="color:#2b91af">Employee</span> left, <span style="color:#2b91af">Employee</span> right)</li>
<li>&#160;&#160;&#160;&#160;{</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">return</span> !Equals(left, right);</li>
<li>&#160;&#160;&#160;&#160;}</li>
<li style="background: #f3f3f3">}</li>
</ol></div>
</p></div>
</p></div>
<p>Fortunately, with Resharper, it’s a snap. Click on the class name, ALT+INS and then follow with the handy dialogues.</p>
<p><a href="http://johnnycoder.com/blog/wp-content/uploads/2009/12/image4.png"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="image" border="0" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2009/12/image-thumb4.png" width="380" height="258" /></a> </p>
<p>That’s it. Try out the HashSet&lt;T&gt;. It’s good stuff.</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2009/12/22/c-hashsett/feed/</wfw:commentRss>
		<slash:comments>14</slash:comments>
		</item>
		<item>
		<title>C# HybridDictionary Collection</title>
		<link>http://johnnycoder.com/blog/2009/04/24/c-hybriddictionary-collection/</link>
		<comments>http://johnnycoder.com/blog/2009/04/24/c-hybriddictionary-collection/#comments</comments>
		<pubDate>Sat, 25 Apr 2009 05:12:06 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2009/04/24/c-hybriddictionary-collection/</guid>
		<description><![CDATA[As an icebreaker question, I’ve asked several interviewees to name classes that one might find in the System.Collections namespace.&#160; There a quite a few answers to this questions – especially if you start to explore the System.Collections.Specialized namespace.&#160; Though I completely understand why folks might immediately shout out answers like Hashtable, Stack, Queue or ArrayList, [...]]]></description>
			<content:encoded><![CDATA[<p>As an icebreaker question, I’ve asked several interviewees to name classes that one might find in the System.Collections namespace.&#160; There a quite a few answers to this questions – especially if you start to explore the System.Collections.Specialized namespace.&#160; Though I completely understand why folks might immediately shout out answers like Hashtable, Stack, Queue or ArrayList, I am still surprised that never once did any candidate every mention System.Collections.Specialized.HybridDictionary.&#160; It’s a shame, too, because it’s pretty cool.</p>
<p>One should consider the size of the collection before choosing a container.&#160; If, for example, you are dealing with a small number of items, you might not want to use a Hashtable since there are some noted inefficiencies.&#160; On the other hand, using ListDictionary for larger lists it is not efficient at all.&#160; Therefore, one might appropriately chose a ListDictionary for small collections and a Hashtable for larger ones.&#160; But what do you do if you aren’t sure how large your collection is going to be?&#160; </p>
<p>That’s where the HybridDictionary comes in.&#160; The HybridDictionary – emphasis on Hybrid – will internally use a ListDictionary while the count is less than or equal to 10 and only when the list becomes larger does it convert to using a Hashtable. The HybridDictionary is best used in situations where some lists are small and others are very large or you just aren’t sure how big a list might eventually grow.&#160; </p>
<p>If you ask me, the HybridDictionary’s ability to migrate from one type to another is a neat trick.&#160; Of course, there are a couple of things you still need to consider:</p>
<ol>
<li>What’s the overhead associated with the conversion?&#160; Fortunately, if the starting item count is greater than 10, the HybridDictionary will start out with the Hashtable to reduce the overhead generated by the conversion.&#160; However you still have to ask if the cost of further conversions is greater than, say, having a Hashtable manage a small sample of data?&#160;&#160; </li>
<li>We have to consider generics.&#160; If you are wondering about the HybridDictionary’s generic equivalent, it’s the Dictionary&lt;&gt;.&#160; The same goes for the Hashtable and ListDictionary; their generic complement is Dictionary&lt;&gt; as well. The point is once you start using generic equivalents, the choice of which collection type to use is pretty much decided for you.&#160; </li>
</ol>
<p>All the same, the HybridDictionary is really slick even if the only time you get to use it is on an interview.</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2009/04/24/c-hybriddictionary-collection/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>.NET MailMessage, LinkedResources, AlternateViews and Exceptions</title>
		<link>http://johnnycoder.com/blog/2009/04/15/net-mailmessage-linkedresources-alternateviews-and-exceptions/</link>
		<comments>http://johnnycoder.com/blog/2009/04/15/net-mailmessage-linkedresources-alternateviews-and-exceptions/#comments</comments>
		<pubDate>Thu, 16 Apr 2009 05:05:34 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Library]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2009/04/15/net-mailmessage-linkedresources-alternateviews-and-exceptions/</guid>
		<description><![CDATA[It doesn’t take much to hack together email functionality using the .NET framework.&#160; In most cases you can new-up a MailMessage reference, assign sender and recipient addresses, provide a subject and a message body, configure your SMTP settings and then send.&#160; Done and done. But let’s say you need to provide both plain text and [...]]]></description>
			<content:encoded><![CDATA[<p>It doesn’t take much to hack together email functionality using the .NET framework.&#160; In most cases you can new-up a MailMessage reference, assign sender and recipient addresses, provide a subject and a message body, configure your SMTP settings and then send.&#160; Done and done.</p>
<p>But let’s say you need to provide both plain text and HTML versions of your message body.&#160; Or maybe you would like to embed an image or two within the message body.&#160; Or, what if, for some reason, you actually want to handle exceptions appropriately.&#160; Well, there’s more to it then.</p>
<p>There are a numerous ways to better organize the following code.&#160; In fact, we just went through an exercise at work where we refactored the heck out of the core email functionality and produce a really clean usable component which can be easily mocked, configured and leverages email templates.&#160; It’s pretty cool.&#160; That being said, I believe the following sample demonstrates the aforementioned core features of .NET emailing.&#160; </p>
<p>I hope it helps. Let me know if I missed anything or it the example could be more clear.</p>
<pre class="code"><span style="color: blue">try
</span>{
    <span style="color: green">// Assign a sender, recipient and subject to new mail message
    </span><span style="color: #2b91af">MailAddress </span>sender =
        <span style="color: blue">new </span><span style="color: #2b91af">MailAddress</span>(<span style="color: #a31515">&quot;sender@johnnycoder.com&quot;</span>, <span style="color: #a31515">&quot;Sender&quot;</span>);

    <span style="color: #2b91af">MailAddress </span>recipient =
        <span style="color: blue">new </span><span style="color: #2b91af">MailAddress</span>(<span style="color: #a31515">&quot;recipient@johnnycoder.com&quot;</span>, <span style="color: #a31515">&quot;Recipient&quot;</span>);

    <span style="color: #2b91af">MailMessage </span>m = <span style="color: blue">new </span><span style="color: #2b91af">MailMessage</span>(sender, recipient);
    m.Subject = <span style="color: #a31515">&quot;Test Message&quot;</span>;

    <span style="color: green">// Define the plain text alternate view and add to message
    </span><span style="color: blue">string </span>plainTextBody =
        <span style="color: #a31515">&quot;You must use an email client that supports HTML messages&quot;</span>;

    <span style="color: #2b91af">AlternateView </span>plainTextView =
        <span style="color: #2b91af">AlternateView</span>.CreateAlternateViewFromString(
            plainTextBody, <span style="color: blue">null</span>, <span style="color: #2b91af">MediaTypeNames</span>.<span style="color: #2b91af">Text</span>.Plain);

    m.AlternateViews.Add(plainTextView);

    <span style="color: green">// Define the html alternate view with embedded image and
    // add to message. To reference images attached as linked
    // resources from your HTML message body, use &quot;cid:contentID&quot;
    // in the &lt;img&gt; tag...
    </span><span style="color: blue">string </span>htmlBody =
        <span style="color: #a31515">&quot;&lt;html&gt;&lt;body&gt;&lt;h1&gt;Picture&lt;/h1&gt;&lt;br&gt;&quot; </span>+
        <span style="color: #a31515">&quot;&lt;img src=\&quot;cid:SampleImage\&quot;&gt;&lt;/body&gt;&lt;/html&gt;&quot;</span>;

    <span style="color: #2b91af">AlternateView </span>htmlView =
        <span style="color: #2b91af">AlternateView</span>.CreateAlternateViewFromString(
            htmlBody, <span style="color: blue">null</span>, <span style="color: #2b91af">MediaTypeNames</span>.<span style="color: #2b91af">Text</span>.Html);

    <span style="color: green">// ...and then define the actual LinkedResource matching the
    // ContentID property as found in the image tag. In this case,
    // the HTML message includes the tag
    // &lt;img src=\&quot;cid:SampleImage\&quot;&gt; and the following
    // LinkedResource.ContentId is set to &quot;SampleImage&quot;
    </span><span style="color: #2b91af">LinkedResource </span>sampleImage =
        <span style="color: blue">new </span><span style="color: #2b91af">LinkedResource</span>(<span style="color: #a31515">&quot;sample.jpg&quot;</span>,
            <span style="color: #2b91af">MediaTypeNames</span>.<span style="color: #2b91af">Image</span>.Jpeg);
    sampleImage.ContentId = <span style="color: #a31515">&quot;SampleImage&quot;</span>;

    htmlView.LinkedResources.Add(sampleImage);

    m.AlternateViews.Add(htmlView);

    <span style="color: green">// Finally, configure smtp or alternatively use the
    // system.net mailSettings
    </span><span style="color: #2b91af">SmtpClient </span>smtp = <span style="color: blue">new </span><span style="color: #2b91af">SmtpClient
          </span>{
              Host = <span style="color: #a31515">&quot;smtp.bigcompany.com&quot;</span>,
              UseDefaultCredentials = <span style="color: blue">false</span>,
              Credentials =
                  <span style="color: blue">new </span><span style="color: #2b91af">NetworkCredential</span>(<span style="color: #a31515">&quot;username&quot;</span>, <span style="color: #a31515">&quot;password&quot;</span>)
          };

    <span style="color: green">//&lt;system.net&gt;
    //    &lt;mailSettings&gt;
    //        &lt;smtp deliveryMethod=&quot;Network&quot;&gt;
    //            &lt;network host=&quot;smtp.bigcompany.com&quot;
    //              port=&quot;25&quot; defaultCredentials=&quot;true&quot;/&gt;
    //        &lt;/smtp&gt;
    //    &lt;/mailSettings&gt;
    //&lt;/system.net&gt;

    </span>smtp.Send(m);
}
<span style="color: blue">catch </span>(<span style="color: #2b91af">ArgumentException</span>)
{
    <span style="color: blue">throw new
        </span><span style="color: #2b91af">ArgumentException</span>(<span style="color: #a31515">&quot;Undefined sender and/or recipient.&quot;</span>);
}
<span style="color: blue">catch </span>(<span style="color: #2b91af">FormatException</span>)
{
    <span style="color: blue">throw new
        </span><span style="color: #2b91af">FormatException</span>(<span style="color: #a31515">&quot;Invalid sender and/or recipient.&quot;</span>);
}
<span style="color: blue">catch </span>(<span style="color: #2b91af">InvalidOperationException</span>)
{
    <span style="color: blue">throw new
        </span><span style="color: #2b91af">InvalidOperationException</span>(<span style="color: #a31515">&quot;Undefined SMTP server.&quot;</span>);
}
<span style="color: blue">catch </span>(<span style="color: #2b91af">SmtpFailedRecipientException</span>)
{
    <span style="color: blue">throw new </span><span style="color: #2b91af">SmtpFailedRecipientException</span>(
        <span style="color: #a31515">&quot;The mail server says that there is no mailbox for recipient&quot;</span>);
}
<span style="color: blue">catch </span>(<span style="color: #2b91af">SmtpException </span>ex)
{
    <span style="color: green">// Invalid hostnames result in a WebException InnerException that
    // provides a more descriptive error, so get the base exception
    </span><span style="color: #2b91af">Exception </span>inner = ex.GetBaseException();
    <span style="color: blue">throw new </span><span style="color: #2b91af">SmtpException</span>(<span style="color: #a31515">&quot;Could not send message: &quot; </span>+ inner.Message);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2009/04/15/net-mailmessage-linkedresources-alternateviews-and-exceptions/feed/</wfw:commentRss>
		<slash:comments>34</slash:comments>
		</item>
		<item>
		<title>15 Random Things I&#8217;ve Learned from Jeffrey Richter</title>
		<link>http://johnnycoder.com/blog/2009/04/08/15-random-things-ive-learned-from-jeffrey-richter/</link>
		<comments>http://johnnycoder.com/blog/2009/04/08/15-random-things-ive-learned-from-jeffrey-richter/#comments</comments>
		<pubDate>Thu, 09 Apr 2009 06:28:28 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[Books]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[CLR]]></category>
		<category><![CDATA[Recommended]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2009/04/08/15-random-things-ive-learned-from-jeffrey-richter/</guid>
		<description><![CDATA[I read through Jeffrey Richter’s CLR via C# not too long ago.&#160; This evening I cracked it open again and jotted down a few notes on what I personally took away from the book. Of course, if I spent the time to write down everything I learned, I might still be busy writing.&#160; I’ve thrown [...]]]></description>
			<content:encoded><![CDATA[<p>I read through Jeffrey Richter’s CLR via C# not too long ago.&#160; This evening I cracked it open again and jotted down a few notes on what I personally took away from the book. Of course, if I spent the time to write down <u>everything</u> I learned, I might still be busy writing.&#160; I’ve thrown in the towel and though I’m probably not doing the book justice, here are <strong>15 random things I have learned from Jeffrey Richter</strong>:<a href="http://search.barnesandnoble.com/CLR-Via-C/Jeffrey-Richter/e/9780735621633/?itm=1"><img style="display: inline; margin: 0px 20px 15px" height="156" alt="CLR Via C# by Richter Richter: Book Cover" src="http://images.barnesandnoble.com/images/34720000/34724778.JPG" width="128" align="right" border="0" /></a></p>
<p>Page 3 – Way more than I ever wanted to know about the CLR’s execution model.&#160; That is, everything about Managed Modules, Assemblies, Intermediate Language (IL), Framework Class Library (FCL), Common Type System (CTS) and Common Language Specification (CLS.)&#160; </p>
<p>Page 56 – How to properly version your assemblies – including a breakdown of the assembly version resource information, how/when to increment the major, minor, build and revision numbers, and the distinction between AssemblyFileVersion, AssemblyInfomationVersion and AssemblyVersion numbers. </p>
<p>Page 144 – Best practices on how to write code to compare objects.&#160; Here, Richter drills into object equality, identity and hash codes. </p>
<p>Page 177 – How the compiler handles constants – their values are embedded inside the IL code at compile time.&#160; </p>
<p>Page 185 – Why one must beware of code explosion with initializing fields within classes with multiple constructors.&#160; Key points: Any fields that the constructor doesn’t explicitly overwrite are guaranteed to have a value of 0 or null.&#160; The compiler embeds, at the beginning of all constructor methods, field initialization code.&#160; You should consider not initializing the default field value at the point of field declaration and instead perform the common initialization in a single constructor and have all other constructors explicitly call the common initialization constructor before overriding varying defaults.&#160; </p>
<pre class="code"><span style="color: blue">internal sealed class </span><span style="color: #2b91af">SomeType
</span>{
    <span style="color: green">// Do not explicitly initialize the fields here
    </span><span style="color: blue">private </span><span style="color: #2b91af">Int32 </span>x;
    <span style="color: blue">private </span><span style="color: #2b91af">String </span>y;
    <span style="color: blue">private </span><span style="color: #2b91af">Double </span>z;

    <span style="color: green">// Sets all fields to their default
    // All constructors explicitly invoke this constructor
    </span><span style="color: blue">public </span>SomeType()
    {
        x = 5;
        y = <span style="color: #a31515">&quot;Ben&quot;</span>;
        z = 3.14159;
    }

    <span style="color: green">// Sets all fields to their default, then changes x
    </span><span style="color: blue">public </span>SomeType(<span style="color: #2b91af">Int32 </span>x) : <span style="color: blue">this</span>()
    {
        <span style="color: blue">this</span>.x = x;
    }

    <span style="color: green">// Sets all fields to their default, then changes y
    </span><span style="color: blue">public </span>SomeType(<span style="color: #2b91af">String </span>y) : <span style="color: blue">this</span>()
    {
        <span style="color: blue">this</span>.y = y;
    }

    <span style="color: green">// Sets all fields to their default, then changes x, y
    </span><span style="color: blue">public </span>SomeType(<span style="color: #2b91af">Int32 </span>x, <span style="color: #2b91af">String </span>y) : <span style="color: blue">this</span>()
    {
        <span style="color: blue">this</span>.x = x;
        <span style="color: blue">this</span>.y = y;
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Page 254 – The power of string interning and string&#160; pooling. </p>
<p>Page 309 – How to perform unsafe array access and fixed-sized arrays. </p>
<p>Page 322 – How to implement multiple interfaces that have the same method name and signature and… </p>
<p>Page 325 – Why you need to be really careful when using explicit interface method implementations.</p>
<p>Page 365 – A quick introduction into <a href="http://www.wintellect.com/PowerCollections.aspx" target="_blank">Wintellect’s Power Collections</a> library which extends the .NET Framework’s Class Library with an assortment of collection classes. The Power Collections library, documentation, and licensing information is available on <a href="http://www.codeplex.com/PowerCollections">CodePlex</a>. </p>
<p>Page 411 – How the CLR provides special support for Nullable value types. </p>
<p>Page 431 – A little background on System.Exception, System.SystemException and System.ApplicationException and how Microsoft through the basic principles out the window. </p>
<p>Page 457 – Way more information than any single person should know about Garbage Collection (GC).</p>
<p>Page 562 – How to build a system which support add-ins. </p>
<p>Though it wasn’t mentioned in the book, Richter’s <a href="http://www.wintellect.com/PowerThreading.aspx" target="_blank">Power Threading library (DLL)</a> contains many classes to help with threading and asynchronous programming for the .NET Framework, Silverlight, and the .NET Compact Framework. Jeffrey has described many of the classes contained in the library by way of his <a href="http://msdn.microsoft.com/en-us/magazine/cc301191.aspx">MSDN Magazine Concurrent Affairs columns</a> and I found his <a href="http://tinyurl.com/6ku9k2" target="_blank">Channel 9 overview on the AsyncEnumerator class</a> (which uses Yield to simplify multithreading) absolutely fascinating.&#160; The Power Threading Library is available for download <a href="http://www.wintellect.com/Downloads/PowerThreadingAttachments/Wintellect_Power_Threading_Library_(March_7,_2009).zip">here</a>. </p>
<p>That’s fifteen.&#160; I should probably drill into a couple of these with code samples…or you could just get a copy of the book. <img src='http://johnnycoder.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>Random closing thought: When I was flipping through the book today I found a spider smashed between pages 72 and 73.&#160; Ironic?</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2009/04/08/15-random-things-ive-learned-from-jeffrey-richter/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Expand Urls with C# and LongUrlPlease</title>
		<link>http://johnnycoder.com/blog/2009/02/25/expand-urls-with-c-and-longurlplease/</link>
		<comments>http://johnnycoder.com/blog/2009/02/25/expand-urls-with-c-and-longurlplease/#comments</comments>
		<pubDate>Wed, 25 Feb 2009 22:44:46 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[Services]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2009/02/25/expand-urls-with-c-and-longurlplease/</guid>
		<description><![CDATA[I think everyone is familiar with those short urls which are being passed around in applications like Twitter.&#160; It’s pretty neat that there are dozens of services willing to shorten urls for us, but what about lengthening them?&#160; That’s where longurlplease.com comes in.&#160; As they say, they promote safer and productive browsing by lengthening short [...]]]></description>
			<content:encoded><![CDATA[<p>I think everyone is familiar with those short urls which are being passed around in applications like Twitter.&#160; It’s pretty neat that there are dozens of services willing to shorten urls for us, but what about lengthening them?&#160; That’s where <a href="http://www.longurlplease.com/">longurlplease.com</a> comes in.&#160; As they say, they promote safer and productive browsing by lengthening short urls so that you don’t have to.&#160; The good folks at longurlplease provide an <a href="http://www.longurlplease.com/docs">API documentation and demos</a> on their site. I looked around a bit but I didn’t find a .NET/C# implementer so I put one together last night.</p>
<p>The included sample application merely requests that longurlplease lengthens 1+ short urls using the wrappers class which follows:</p>
<p>&#160;</p>
<pre class="code"><span style="color: blue">public class </span><span style="color: #2b91af">LongUrlPlease
</span>{
    <span style="color: blue">private const </span><span style="color: #2b91af">String </span>LongUrlPleaseUri = <span style="color: #a31515">&quot;http://www.longurlplease.com/api/v1.1?{0}&quot;</span>;

    <span style="color: blue">public static </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">String</span>, <span style="color: #2b91af">String</span>&gt; ExpandUrls(<span style="color: blue">params </span><span style="color: #2b91af">String</span>[] shortUrls)
    {
        <span style="color: blue">var </span>longUrls = <span style="color: blue">new </span><span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">String</span>, <span style="color: #2b91af">String</span>&gt;();

        <span style="color: #2b91af">HttpWebRequest </span>webRequest = GetLongUrlPleaseRequest(shortUrls);
        <span style="color: blue">var </span>response = (<span style="color: #2b91af">HttpWebResponse</span>) webRequest.GetResponse();

        <span style="color: blue">try
        </span>{
            <span style="color: blue">using </span>(<span style="color: blue">var </span>sr = <span style="color: blue">new </span><span style="color: #2b91af">StreamReader</span>(response.GetResponseStream()))
            {
               longUrls = <span style="color: blue">new </span><span style="color: #2b91af">JavaScriptSerializer</span>().Deserialize&lt;<span style="color: #2b91af">Dictionary</span>&lt;<span style="color: #2b91af">String</span>, <span style="color: #2b91af">String</span>&gt;&gt;(sr.ReadToEnd());
            }
        }
        <span style="color: blue">catch </span>(<span style="color: #2b91af">WebException </span>ex)
        {
        }

        <span style="color: blue">return </span>longUrls;
    }

    <span style="color: blue">private static </span><span style="color: #2b91af">HttpWebRequest </span>GetLongUrlPleaseRequest(<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">string</span>&gt; shortUrls)
    {
        <span style="color: #2b91af">Uri </span>longUrlPleaseUri = GetLongUrlPleaseUri(shortUrls);

        <span style="color: blue">return </span>(<span style="color: #2b91af">HttpWebRequest</span>) <span style="color: #2b91af">WebRequest</span>.Create(longUrlPleaseUri);
    }

    <span style="color: blue">private static </span><span style="color: #2b91af">Uri </span>GetLongUrlPleaseUri(<span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: #2b91af">String</span>&gt; shortUrls)
    {
       <span style="color: blue">var </span>parameters = <span style="color: blue">new </span><span style="color: #2b91af">StringBuilder</span>();

        <span style="color: #2b91af">String </span>delimiter = <span style="color: blue">string</span>.Empty;
        <span style="color: blue">foreach </span>(<span style="color: blue">var </span>url <span style="color: blue">in </span>shortUrls)
        {
            parameters.Append(delimiter).AppendFormat(<span style="color: #a31515">&quot;q={0}&quot;</span>, url);
            delimiter = <span style="color: #a31515">&quot;&amp;&quot;</span>;
        }

        <span style="color: blue">return new </span><span style="color: #2b91af">Uri</span>(<span style="color: blue">string</span>.Format(LongUrlPleaseUri, parameters), <span style="color: #2b91af">UriKind</span>.Absolute);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a>And here are a couple sample calls:</p>
<pre class="code"><span style="color: blue">var </span>singleUrl = <span style="color: #2b91af">LongUrlPlease</span>.ExpandUrls(<span style="color: #a31515">&quot;http://tinyurl.com/87lb2n&quot;</span>);

<span style="color: blue">var </span>multipleUrls = <span style="color: #2b91af">LongUrlPlease</span>.ExpandUrls(<span style="color: #a31515">&quot;http://tinyurl.com/87lb2n&quot;</span>,
                                            <span style="color: #a31515">&quot;http://short.ie/cww8ag&quot;</span>);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code">&#160;</pre>
<p>Note the code comments as I needed to use the JavaScriptSerializer rather than the DataContractJsonSerializer due to the fact that longurlplease was essentially returning anonymous types back in the response.&#160; </p>
<div class="wlWriterEditableSmartContent" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:29b2d428-c0f6-461e-a1dd-84fd360d3ff2" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div>Download LongUrlPlease Sample:<a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/longurlplease.zip" target="_self">LongUrlPlease.zip</a></div>
</p>
</div>
<p>&#160;</p>
<div class="wlWriterEditableSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:1c3e9b77-b581-4484-a2c5-5ca35b0dbdaf" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2009/02/25/expand-urls-with-c-and-longurlplease/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2009/02/25/expand-urls-with-c-and-longurlplease/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2009/02/25/expand-urls-with-c-and-longurlplease/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>StringBuilder Required Capacity Algorithm</title>
		<link>http://johnnycoder.com/blog/2009/01/05/stringbuilder-required-capacity-algorithm/</link>
		<comments>http://johnnycoder.com/blog/2009/01/05/stringbuilder-required-capacity-algorithm/#comments</comments>
		<pubDate>Mon, 05 Jan 2009 18:56:56 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[Algorithms]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2009/01/05/stringbuilder-required-capacity-algorithm/</guid>
		<description><![CDATA[.NET Strings are immutable.&#160; StringBuilder should be used to better performance.&#160; Blah&#8230; Blah&#8230; Blah&#8230;&#160; You&#8217;ve heard it all before, but what you might not know is how StringBuilder dynamically allocates its capacity.&#160; The simple answer is StringBuilder will double its capacity when its capacity is reached.&#160; In other words, if you add 1 byte to [...]]]></description>
			<content:encoded><![CDATA[<p>.NET Strings are immutable.&nbsp; StringBuilder should be used to better performance.&nbsp; Blah&#8230; Blah&#8230; Blah&#8230;&nbsp; <a href="http://johnnycoder.com/blog/2006/08/09/improve-string-management-with-stringbuilder/">You&#8217;ve heard it all before</a>, but what you might not know is how StringBuilder dynamically allocates its capacity.&nbsp; The simple answer is StringBuilder will double its capacity when its capacity is reached.&nbsp; In other words, if you add 1 byte to a StringBuilder with 32 bytes of storage, the allocation will double to 64.&nbsp; You might be wondering what happens if doubling isn&#8217;t enough?&nbsp; Will storage just keep doubling until the required capacity is met?&nbsp; Nope.&nbsp; In this case, StringBuilder will only allocate exactly what is needed.&nbsp; The algorithm is arguably dumb &#8212; double the allocation and, if that&#8217;s not enough, add as much as needed.&nbsp; So, if you add 64 bytes to a StringBuilder with 16 bytes of storage, the allocation will double to 32 and then jump to 80 (16+64) bytes.&nbsp; In other words, and this is the arguable dumb part, if you add even one more byte, reallocation is required with the next Append(). I personally think the algorithm should continue to double the storage until the required capacity is met or exceeded rather than merely meet the need.</p>
<p>Here&#8217;s the code (compliments of Reflector)&#8230;</p>
<pre class="code"><span style="color: blue">private string </span>GetNewString(<span style="color: blue">string </span>currentString, <span style="color: blue">int </span>requiredLength)
{
    <span style="color: blue">int </span>maxCapacity = <span style="color: blue">this</span>.m_MaxCapacity;
    <span style="color: blue">if </span>(requiredLength &lt; 0)
    {
        <span style="color: blue">throw new </span><span style="color: #2b91af">OutOfMemoryException</span>();
    }
    <span style="color: blue">if </span>(requiredLength &gt; maxCapacity)
    {
        <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentOutOfRangeException</span>(<span style="color: #a31515">"requiredLength"</span>,
            <span style="color: #2b91af">Environment</span>.GetResourceString(<span style="color: #a31515">"ArgumentOutOfRange_SmallCapacity"</span>));
    }
    <span style="color: blue">int </span>capacity = currentString.Capacity * 2;
    <span style="color: blue">if </span>(capacity &lt; requiredLength)
    {
        capacity = requiredLength;
    }
    <span style="color: blue">if </span>(capacity &gt; maxCapacity)
    {
        capacity = maxCapacity;
    }
    <span style="color: blue">if </span>(capacity &lt;= 0)
    {
        <span style="color: blue">throw new </span><span style="color: #2b91af">ArgumentOutOfRangeException</span>(<span style="color: #a31515">"newCapacity"</span>,
            <span style="color: #2b91af">Environment</span>.GetResourceString(<span style="color: #a31515">"ArgumentOutOfRange_NegativeCapacity"</span>));
    }
    <span style="color: blue">return string</span>.GetStringForStringBuilder(currentString, capacity);
}
</pre>
<p>You can read more <a href="http://knitinr.blogspot.com/2008/06/examining-stringbuilder-class.html">here</a> and <a href="http://weblogs.asp.net/mreynolds/archive/2003/07/25/10528.aspx">here</a>.</p>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:b393db48-4637-4141-80fc-e76cb4817567" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2009/01/05/stringbuilder-required-capacity-algorithm/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2009/01/05/stringbuilder-required-capacity-algorithm/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2009/01/05/stringbuilder-required-capacity-algorithm/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>jTemplates with jQuery, AJAX and Json</title>
		<link>http://johnnycoder.com/blog/2008/12/18/jtemplates-with-jquery-ajax-and-json/</link>
		<comments>http://johnnycoder.com/blog/2008/12/18/jtemplates-with-jquery-ajax-and-json/#comments</comments>
		<pubDate>Fri, 19 Dec 2008 04:22:17 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[AJAX]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Json]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/12/18/jtemplates-with-jquery-ajax-and-json/</guid>
		<description><![CDATA[jTemplates is a jQuery plugin and template engine for Javascript.&#160; If you keep up with Dave Ward and/or Rick Strahl you may already be familiar with jTemplates as they have both highlighted the plugin on their respective bolgs.&#160; About 1.5 months ago, however, I got into the action and started using jTemplates in conjunction with [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://jtemplates.tpython.com/">jTemplates</a> is a jQuery plugin and template engine for Javascript.&nbsp; If you keep up with <a href="http://encosia.com/">Dave Ward</a> and/or <a href="http://www.west-wind.com/Weblog">Rick Strahl</a> you may already be familiar with jTemplates as they have both highlighted the plugin on their respective bolgs.&nbsp; About 1.5 months ago, however, I got into the action and started using jTemplates in conjunction with jQuery, AJAX and Json to dynamically populate dropdowns and tables on the client side. </p>
<p>As you&#8217;ll see in the examples, jTemplates provides custom syntax to do such things as iterate through Json data and populate a predefined template.&nbsp; Once you get a grasp of the syntax and the proper usage, you will be ready to roll.&nbsp; Getting started is easy &#8212; just download the latest <a href="http://code.google.com/p/jqueryjs/">jQuery</a> and <a href="http://jtemplates.tpython.com/">jTemplate</a> bits and reference them within your html or aspx file. </p>
<p>Next, you need to define and host your templates.&nbsp; In the included sample project, I&#8217;ve defined two templates to aid in the population of my dropdown and my table respectively.&nbsp; Here you will notice the dropdown template merely adds a singe &#8220;Select One&#8221; entry and then iterates over all project results adding a new option for each:</p>
<pre class="code"><span style="background: #ffee62">&lt;%</span><span style="color: green">-- Project Dropdown Template --</span><span style="background: #ffee62">%&gt;
</span><span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">type</span><span style="color: blue">="text/html" </span><span style="color: red">id</span><span style="color: blue">="TemplateProjectSelect"&gt;
</span>&lt;option value=""&gt;Select One&lt;/option&gt;
{#foreach $T.result as project}
    &lt;option value="{$T.project.id}"&gt;{$T.project.name}&lt;/option&gt;
{#/for}
<span style="color: blue">&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>And the following table template is a little more complex but still very to interpret.&nbsp; Here, we are iterating over each task row and appending a new row to the table for each.&nbsp; Notice there&#8217;s a MAIN template and a ROW template.&nbsp; The MAIN template passes along the current record to the ROW template.&nbsp; The ROW template sets the appropriate class (think table zebra stripes) and column values based on the current &#8220;cycle.&#8221;</p>
<pre class="code"><span style="background: #ffee62">&lt;%</span><span style="color: green">-- Results Table Template --</span><span style="background: #ffee62">%&gt;
</span><span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">type</span><span style="color: blue">="text/html" </span><span style="color: red">id</span><span style="color: blue">="TemplateResultsTable"&gt;
</span>{#template MAIN}
&lt;table width="500" border="0" cellpadding="5" cellspacing="0"&gt;
  &lt;tr&gt;
    &lt;th width="50"&gt;ID&lt;/th&gt;
    &lt;th width="300"&gt;Task&lt;/th&gt;
    &lt;th width="104"&gt;Hours&lt;/th&gt;
  &lt;/tr&gt;
  {#foreach $T.result as task}
    {#include ROW root=$T.task}
  {#/for}
&lt;/table&gt;
{#/template MAIN}

{#template ROW}
&lt;tr class="{#cycle values=['','evenRow']}"&gt;
  &lt;td&gt;{$T.id}&lt;/td&gt;
  &lt;td&gt;{$T.name}&lt;/td&gt;
  &lt;td&gt;{$T.hours}&lt;/td&gt;
&lt;/tr&gt;
{#/template ROW}
<span style="color: blue">&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>How&#8217;s about hosting the templates?&nbsp; You have a few options.&nbsp; First, you could save the templates off in their own file.&nbsp; This is <a href="http://encosia.com/2008/06/26/use-jquery-and-aspnet-ajax-to-build-a-client-side-repeater/">the approach Dave Ward took in his article</a>. Though this approach is clean, it doesn&#8217;t perform all that well.&nbsp; The preferred approach is to &#8220;embed&#8221; your templates within the html/aspx file by wrapping each of the above templates with a script tag like so:</p>
<p><span style="color: blue"></span></p>
<pre class="code"><span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">type</span><span style="color: blue">="text/html" </span><span style="color: red">id</span><span style="color: blue">="TemplateResultsTable"&gt; 

</span>... template here ...

<span style="color: blue">&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt; </span></pre>
<p>As <a href="http://www.west-wind.com/Weblog/posts/509108.aspx">shared on Rick Strahl&#8217;s post</a>, this is the preferred approach as using &lt;script type=”text/html”&gt; that allows hiding any markup in the document without interfering with HTML validators. The script can be accessed by its ID and the content retrieved using the jQuery .html() syntax.</p>
<p>Once your template is in place, you simply need to assign your template to your container (a div) and then process the template using your Json data.&nbsp; As noted above, you may reference an external template using the following:</p>
<pre class="code">$(<span style="color: #a31515">'#tasks'</span>).setTemplate(<span style="color: #a31515">'Template.htm'</span>);</pre>
<p><a href="http://11011.net/software/vspaste"></a>Or you may select the template from the html/aspx itself:</p>
<pre class="code">$(<span style="color: #a31515">'#tasks'</span>).setTemplate($(<span style="color: #a31515">"#TemplateResultsTable"</span>).html());</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Again, the preferred approach is the latter.&nbsp; In either case, you process the template data (results) as follows:</p>
<pre class="code">$(<span style="color: #a31515">'#tasks'</span>).processTemplate(results);</pre>
<p><a href="http://11011.net/software/vspaste"></a>
<pre class="code"><span style="color: blue"></span></pre>
<p>A quick note on .processTemplate.&nbsp; You don&#8217;t actually have to provide any data.&nbsp; You can send null into the processTemplate method if, for example, no processing is required.&nbsp; In the downloadable example, I create a static template which acts as a place holder when my page first loads and no table data is available. Here&#8217;s the sample template and javascript:</p>
<pre class="code"><span style="background: #ffee62">&lt;%</span><span style="color: green">-- Emtpy Table Template --</span><span style="background: #ffee62">%&gt;
</span><span style="color: blue">&lt;</span><span style="color: #a31515">script </span><span style="color: red">type</span><span style="color: blue">="text/html" </span><span style="color: red">id</span><span style="color: blue">="TemplateResultsEmpty"&gt;
</span>Select a client and project...
<span style="color: blue">&lt;/</span><span style="color: #a31515">script</span><span style="color: blue">&gt;</span></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a>
<pre class="code">$(<span style="color: #a31515">'#tasks'</span>).setTemplate($(<span style="color: #a31515">"#TemplateResultsEmpty"</span>).html());
$(<span style="color: #a31515">'#tasks'</span>).processTemplate(<span style="color: blue">null</span>);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Before I wrap things up, I should mention the downloadable sample project doesn&#8217;t only show off jTemplates.&nbsp; It also demonstrates how to use jQuery and an &#8220;parameterized&#8221; HTTPHandler to pull back Json data which is somewhat an extension of <a href="http://johnnycoder.com/blog/2008/12/16/httphandler-json-data/">my earlier HTTPHandler post</a>.</p>
</p>
<div class="wlWriterSmartContent" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:6a5b99e2-f002-4bf1-86f5-f79ddb7cf63b" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div>Download jTemplates Sample Project: <a href="http://johnnycoder.com/blog/wp-content/uploads/2008/12/jtemplates.zip" target="_blank">jTemplates.zip</a></div>
</p>
</div>
<p>&nbsp;</p>
</p>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:a6aa7101-097f-4c86-bb3c-9a91e2bc6568" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/12/18/jtemplates-with-jquery-ajax-and-json/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/12/18/jtemplates-with-jquery-ajax-and-json/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/12/18/jtemplates-with-jquery-ajax-and-json/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>HTTPHandler with JSON Data</title>
		<link>http://johnnycoder.com/blog/2008/12/16/httphandler-json-data/</link>
		<comments>http://johnnycoder.com/blog/2008/12/16/httphandler-json-data/#comments</comments>
		<pubDate>Tue, 16 Dec 2008 17:24:17 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[jQuery]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/12/16/httphandler-json-data/</guid>
		<description><![CDATA[As javascript libraries, particularly jQuery, increase in popularity so do web techniques using AJAX and JSON. Have you ever seen this code?&#160; It is front and back of an ASPX file with the single responsibility to return JSON data per an AJAX request. GetDataPage.aspx &#60;%@ Page Language="C#" AutoEventWireup="true" CodeFile="GetDataPage.aspx.cs" Inherits="GetDataPage" %&#62; &#60;%-- This minimal code [...]]]></description>
			<content:encoded><![CDATA[<p>As javascript libraries, particularly jQuery, increase in popularity so do web techniques using AJAX and JSON.</p>
<p>Have you ever seen this code?&nbsp; It is front and back of an ASPX file with the single responsibility to return JSON data per an AJAX request.</p>
<p><span style="text-decoration: underline">GetDataPage.aspx</span></p>
<pre class="code"><span style="background: #ffee62">&lt;%</span><span style="color: blue">@ </span><span style="color: #a31515">Page </span><span style="color: red">Language</span><span style="color: blue">="C#" </span><span style="color: red">AutoEventWireup</span><span style="color: blue">="true"
    </span><span style="color: red">CodeFile</span><span style="color: blue">="GetDataPage.aspx.cs" </span><span style="color: red">Inherits</span><span style="color: blue">="GetDataPage" </span><span style="background: #ffee62">%&gt;
&lt;%</span><span style="color: green">--
    This minimal code is here to prevent the following error:
     "Using themed css files requires a header control on the page"
     Please see http://www.west-wind.com/WebLog/posts/4662.aspx
     for more information --</span><span style="background: #ffee62">%&gt;
</span><span style="color: blue">&lt;</span><span style="color: #a31515">head </span><span style="color: red">id</span><span style="color: blue">="Head1" </span><span style="color: red">runat</span><span style="color: blue">="server" </span><span style="color: red">visible</span><span style="color: blue">="false" /&gt;
</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p><span style="text-decoration: underline">GetDataPage.aspx.cs</span></p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">using </span>System.Web;
<span style="color: blue">using </span>System.Text;

<span style="color: blue">public partial class </span><span style="color: #2b91af">GetDataPage </span>: System.Web.UI.<span style="color: #2b91af">Page
</span>{
    <span style="color: blue">protected void </span>Page_Load(<span style="color: blue">object </span>sender, <span style="color: #2b91af">EventArgs </span>e)
    {
        <span style="color: green">// Clear out the buffer
        </span>Response.ClearHeaders();
        Response.ClearContent();
        Response.Clear();

        <span style="color: green">// Do not cache response
        </span>Response.Cache.SetCacheability(<span style="color: #2b91af">HttpCacheability</span>.NoCache);

        <span style="color: green">// Set the content type and encoding for JSON
        </span>Response.ContentType = <span style="color: #a31515">"application/json"</span>;
        Response.ContentEncoding = <span style="color: #2b91af">Encoding</span>.UTF8;

        <span style="color: blue">int </span>page = <span style="color: blue">int</span>.Parse(Request[<span style="color: #a31515">"p"</span>]);
        <span style="color: blue">string </span>results = <span style="color: #2b91af">DataAccess</span>.GetResults(page);

        Response.Write(results);

        <span style="color: green">// Flush the response buffer
        </span>Response.Flush();

        <span style="color: green">// Complete the request.  NOTE: Do not use Response.End() here,
        // because it throws a ThreadAbortException, which cannot be caught!
        </span><span style="color: #2b91af">HttpContext</span>.Current.ApplicationInstance.CompleteRequest();
    }
}
</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>You may have noticed there&#8217;s a comment for nearly every code block.&nbsp; At first, one may find the comments redundant and unnecessary, but really they are call for help.&nbsp; A code:comment ratio like this usually indicates you really need to focus on what&#8217;s happening with the code because if you aren&#8217;t paying attention, bad things might happen.</p>
<p>As you have undoubtedly concluded, there&#8217;s a lot of overhead associated with returning JSON data from an ASPX file.&nbsp; This statement is especially true if you consider the alternative, an HTTPHandler.&nbsp; Here&#8217;s a cleaner, best-practices approach which provides the same outcome with less code, comments and risk.</p>
<p><span style="text-decoration: underline">GetDataHandler.ashx</span></p>
<pre class="code"><span style="background: #ffee62">&lt;%</span><span style="color: blue">@ </span><span style="color: #a31515">WebHandler </span><span style="color: red">Language</span><span style="color: blue">="C#" </span><span style="color: red">Class</span><span style="color: blue">="GetDataHandler" </span><span style="background: #ffee62">%&gt;

</span><span style="color: blue">using </span>System.Text;
<span style="color: blue">using </span>System.Web;

<span style="color: blue">public class </span><span style="color: #2b91af">GetDataHandler </span>: <span style="color: #2b91af">IHttpHandler
</span>{
    <span style="color: blue">public bool </span>IsReusable
    {
        <span style="color: blue">get </span>{ <span style="color: blue">return false</span>; }
    }

    <span style="color: blue">public void </span>ProcessRequest (<span style="color: #2b91af">HttpContext </span>context)
    {
        context.Response.ContentType = <span style="color: #a31515">"application/json"</span>;
        context.Response.ContentEncoding = <span style="color: #2b91af">Encoding</span>.UTF8;

        <span style="color: blue">int </span>page = <span style="color: blue">int</span>.Parse(context.Request[<span style="color: #a31515">"p"</span>]);
        <span style="color: blue">string </span>results = <span style="color: #2b91af">DataAccess</span>.GetResults(page);

        context.Response.Write(results);
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>If you are already accustomed to using generic handlers to stream back images, XML, JSON data, etc, this post was probably a bore. But it&#8217;s sometimes easy to forget what&#8217;s available to <a href="http://johnnycoder.com/blog/wp-content/uploads/2008/12/image2.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="160" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2008/12/image-thumb2.png" width="244" align="right" border="0"></a>you in the vast .NET stack, so hopefully you appreciate the friendly reminder.&nbsp; In either case, it still surprises me how many examples use the ASPX approach.&nbsp; In fact, the practice is common enough that I sometimes wonder if there&#8217;s an HTTPHandler gotcha to which I&#8217;m not privy .&nbsp; If I am missing something, please let me know.</p>
<p>If you&#8217;re still interested, attached you&#8217;ll find code which populates two jQuery Flexbox controls using JSON data provided through an ASPX and ASHX files.&nbsp; This may be worthwhile download if you&#8217;re interest in the generic handler code or you want a further look at Flexbox in action after <a href="http://johnnycoder.com/blog/2008/12/13/flexbox-jquery-plugin/">last week&#8217;s post</a>.</p>
<div class="wlWriterSmartContent" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:c1d080fd-bc5d-4b7d-8d47-abe9f5cfbce0" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div>Download JsonHandler Sample Project: <a href="http://johnnycoder.com/blog/wp-content/uploads/2008/12/jsonhandler1.zip" target="_blank">JsonHandler.zip</a></div>
</p>
</div>
</p>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:36b47f1d-cc23-4bfb-aa40-0ace90b1e1c5" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/12/16/httphandler-json-data/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/12/16/httphandler-json-data/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/12/16/httphandler-json-data/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>C# Cache Helper Class Revisited</title>
		<link>http://johnnycoder.com/blog/2008/12/12/c-cache-helper-class-revisited/</link>
		<comments>http://johnnycoder.com/blog/2008/12/12/c-cache-helper-class-revisited/#comments</comments>
		<pubDate>Fri, 12 Dec 2008 17:57:38 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Library]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/12/12/c-cache-helper-class-revisited/</guid>
		<description><![CDATA[The Cache Helper Class has been updated so that it is no longer limited by the generic constraint.&#160; The original post has been updated along with a sample project for download.&#160; Let me know what think.&#160; I know I&#8217;m much happy with this solution.&#160; As always, thanks for your comments and thanks for letting me [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/">Cache Helper Class</a> has been updated so that it is no longer limited by the generic constraint.&nbsp; The <a href="http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/">original post</a> has been updated along with a sample project for </p>
<p><img height="291" src="http://expressive-designs.com/wordpress/wp-content/uploads/2008/05/golf_funny.jpg" width="354" align="right"></p>
<p>download.&nbsp; Let me know what think.&nbsp; I know I&#8217;m much happy with this solution.&nbsp; As always, thanks for your comments and thanks for letting me <a href="http://golf.about.com/cs/2003seniortour/g/bldef_mulligan.htm">take a mulligan</a>.</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>.</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/12/12/c-cache-helper-class-revisited/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>C# Cache Helper Class</title>
		<link>http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/</link>
		<comments>http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/#comments</comments>
		<pubDate>Wed, 10 Dec 2008 18:14:24 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Library]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/</guid>
		<description><![CDATA[Do you need a quick and cache wrapper class? Here&#8217;s a static class which I included in my more recent C# web application.&#160; You&#8217;ll notice the class uses generics to allow for some, umm, generic functionality.&#160; public static class CacheHelper { /// &#60;summary&#62; /// Insert value into the cache using /// appropriate name/value pairs /// [...]]]></description>
			<content:encoded><![CDATA[<p>Do you need a quick and cache wrapper class? Here&#8217;s a static class which I included in my more recent C# web application.&nbsp; You&#8217;ll notice the class uses generics to allow for some, umm, generic functionality.&nbsp; </p>
<pre class="code"><span style="color: blue">public static class </span><span style="color: #2b91af">CacheHelper
</span>{
    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Insert value into the cache using
    </span><span style="color: gray">/// </span><span style="color: green">appropriate name/value pairs
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;</span><span style="color: green">Type of cached item</span><span style="color: gray">&lt;/typeparam&gt;
    /// &lt;param name="o"&gt;</span><span style="color: green">Item to be cached</span><span style="color: gray">&lt;/param&gt;
    /// &lt;param name="key"&gt;</span><span style="color: green">Name of item</span><span style="color: gray">&lt;/param&gt;
    </span><span style="color: blue">public static void </span>Add&lt;T&gt;(T o, <span style="color: blue">string </span>key) <span style="color: blue">where </span>T : <span style="color: blue">class
    </span>{
        <span style="color: green">// NOTE: Apply expiration parameters as you see fit.
        // In this example, I want an absolute
        // timeout so changes will always be reflected
        // at that time. Hence, the NoSlidingExpiration.
        </span><span style="color: #2b91af">HttpContext</span>.Current.Cache.Insert(
            key,
            o,
            <span style="color: blue">null</span>,
            <span style="color: #2b91af">DateTime</span>.Now.AddMinutes(
                <span style="color: #2b91af">ConfigurationHelper</span>.CacheExpirationMinutes),
            System.Web.Caching.<span style="color: #2b91af">Cache</span>.NoSlidingExpiration);
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Remove item from cache
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;param name="key"&gt;</span><span style="color: green">Name of cached item</span><span style="color: gray">&lt;/param&gt;
    </span><span style="color: blue">public static void </span>Clear(<span style="color: blue">string </span>key)
    {
        <span style="color: #2b91af">HttpContext</span>.Current.Cache.Remove(key);
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Check for item in cache
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;param name="key"&gt;</span><span style="color: green">Name of cached item</span><span style="color: gray">&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    </span><span style="color: blue">public static bool </span>Exists(<span style="color: blue">string </span>key)
    {
        <span style="color: blue">return </span><span style="color: #2b91af">HttpContext</span>.Current.Cache[key] != <span style="color: blue">null</span>;
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Retrieve cached item
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;</span><span style="color: green">Type of cached item</span><span style="color: gray">&lt;/typeparam&gt;
    /// &lt;param name="key"&gt;</span><span style="color: green">Name of cached item</span><span style="color: gray">&lt;/param&gt;
    /// &lt;returns&gt;</span><span style="color: green">Cached item as type</span><span style="color: gray">&lt;/returns&gt;
    </span><span style="color: blue">public static </span>T Get&lt;T&gt;(<span style="color: blue">string </span>key) <span style="color: blue">where </span>T : <span style="color: blue">class
    </span>{
        <span style="color: blue">try
        </span>{
            <span style="color: blue">return </span>(T) <span style="color: #2b91af">HttpContext</span>.Current.Cache[key];
        }
        <span style="color: blue">catch
        </span>{
            <span style="color: blue">return null</span>;
        }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>And here is a relatively standard sample usage of the library.&nbsp; </p>
<pre class="code"><span style="color: blue">public override </span><span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Employee</span>&gt; GetEmployeeList()
{
    <span style="color: blue">string </span>key = <span style="color: #2b91af">ConfigurationHelper</span>.CacheKeyEmployeeList;

    <span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Employee</span>&gt; employees = <span style="color: #2b91af">CacheHelper</span>.Get&lt;<span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Employee</span>&gt;&gt;(key);

    <span style="color: blue">if </span>(employees == <span style="color: blue">null</span>)
    {
        employees = instance.GetEmployeeList();
        <span style="color: #2b91af">CacheHelper</span>.Add(employees, key);
    }

    <span style="color: blue">return </span>employees;
}</pre>
<p>Notice how I&#8217;m grabbing the cached value, storing it in a local variable and then checking if it is equal to null rather than using the CacheHelper.Exists() method.&nbsp; If I used the CacheHelper.Exists() method, the cached object could expire between the time I check its existence and the time I get its value through the CacheHelper.Get() method.&nbsp; Therefore, the above approach is the safest strategy to use when retrieving cached values.&nbsp; CacheHelper.Exists() should really only be used for quick existence checks which are unrelated to the fetch.</p>
<p>But if you want to use the code CORRECTLY there&#8217;s a catch.&nbsp; Did you notice the &#8220;class&#8221; constraint on the CacheHelper.Get() and CacheHelper.Add() methods?&nbsp;&nbsp; I did this because you can&#8217;t always return null from a generic method.&nbsp; If the return type were always a reference type it would be fine, but comparing a non-nullable value type to null would throw a runtime exception or would always evaluate to false.&nbsp; Therefore, I&#8217;ve constrainted CacheHelper which limits its functionality but unsure safe use of the cache.&nbsp; If you&#8217;re feeling dangerous, you&#8217;re welcome to remove the constraints.</p>
<p>I&#8217;ll update the library once I come up with a good work around.&nbsp; Speaking of, any suggestions?</p>
<p>Let me know if you have any questions and/or this type of post is helpful.&nbsp; Thanks.</p>
<p><strong>UPDATE 12/10:</strong></p>
<p>After further review, I&#8217;ve removed the &#8220;class&#8221; constraint from the CacheHelper.&nbsp; The Get() method now follows the common Try(x, out y) pattern where x is what you wish to operate on, y is the resulting value and the method return success or failure.&nbsp; Here&#8217;s a sample call:</p>
<pre class="code"><span style="color: blue">string </span>key = <span style="color: #a31515">"EmployeeList"</span>;
<span style="color: #2b91af">List</span>&lt;<span style="color: #2b91af">Employee</span>&gt; employees;

<span style="color: blue">if </span>(!<span style="color: #2b91af">CacheHelper</span>.Get(key, <span style="color: blue">out </span>employees))
{
    employees = <span style="color: #2b91af">DataAccess</span>.GetEmployeeList();
    <span style="color: #2b91af">CacheHelper</span>.Add(employees, key);
    Message.Text =
        <span style="color: #a31515">"Employees not found but retrieved and added to cache for next lookup."</span>;
}
<span style="color: blue">else
</span>{
    Message.Text = <span style="color: #a31515">"Employees pulled from cache."</span>;
}
</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>And here&#8217;s the updated class.&nbsp; Note, I&#8217;ve also provided a sample project for download.&nbsp; Thanks for your comments!</p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">using </span>System.Web;

<span style="color: blue">public static class </span><span style="color: #2b91af">CacheHelper
</span>{
    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Insert value into the cache using
    </span><span style="color: gray">/// </span><span style="color: green">appropriate name/value pairs
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;</span><span style="color: green">Type of cached item</span><span style="color: gray">&lt;/typeparam&gt;
    /// &lt;param name="o"&gt;</span><span style="color: green">Item to be cached</span><span style="color: gray">&lt;/param&gt;
    /// &lt;param name="key"&gt;</span><span style="color: green">Name of item</span><span style="color: gray">&lt;/param&gt;
    </span><span style="color: blue">public static void </span>Add&lt;T&gt;(T o, <span style="color: blue">string </span>key)
    {
        <span style="color: green">// NOTE: Apply expiration parameters as you see fit.
        // I typically pull from configuration file.

        // In this example, I want an absolute
        // timeout so changes will always be reflected
        // at that time. Hence, the NoSlidingExpiration.
        </span><span style="color: #2b91af">HttpContext</span>.Current.Cache.Insert(
            key,
            o,
            <span style="color: blue">null</span>,
            <span style="color: #2b91af">DateTime</span>.Now.AddMinutes(1440),
            System.Web.Caching.<span style="color: #2b91af">Cache</span>.NoSlidingExpiration);
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Remove item from cache
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;param name="key"&gt;</span><span style="color: green">Name of cached item</span><span style="color: gray">&lt;/param&gt;
    </span><span style="color: blue">public static void </span>Clear(<span style="color: blue">string </span>key)
    {
        <span style="color: #2b91af">HttpContext</span>.Current.Cache.Remove(key);
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Check for item in cache
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;param name="key"&gt;</span><span style="color: green">Name of cached item</span><span style="color: gray">&lt;/param&gt;
    /// &lt;returns&gt;&lt;/returns&gt;
    </span><span style="color: blue">public static bool </span>Exists(<span style="color: blue">string </span>key)
    {
        <span style="color: blue">return </span><span style="color: #2b91af">HttpContext</span>.Current.Cache[key] != <span style="color: blue">null</span>;
    }

    <span style="color: gray">/// &lt;summary&gt;
    /// </span><span style="color: green">Retrieve cached item
    </span><span style="color: gray">/// &lt;/summary&gt;
    /// &lt;typeparam name="T"&gt;</span><span style="color: green">Type of cached item</span><span style="color: gray">&lt;/typeparam&gt;
    /// &lt;param name="key"&gt;</span><span style="color: green">Name of cached item</span><span style="color: gray">&lt;/param&gt;
    /// &lt;param name="value"&gt;</span><span style="color: green">Cached value. Default(T) if
    </span><span style="color: gray">/// </span><span style="color: green">item doesn't exist.</span><span style="color: gray">&lt;/param&gt;
    /// &lt;returns&gt;</span><span style="color: green">Cached item as type</span><span style="color: gray">&lt;/returns&gt;
    </span><span style="color: blue">public static bool </span>Get&lt;T&gt;(<span style="color: blue">string </span>key, <span style="color: blue">out </span>T value)
    {
        <span style="color: blue">try
        </span>{
            <span style="color: blue">if </span>(!Exists(key))
            {
                value = <span style="color: blue">default</span>(T);
                <span style="color: blue">return false</span>;
            }

            value =  (T) <span style="color: #2b91af">HttpContext</span>.Current.Cache[key];
        }
        <span style="color: blue">catch
        </span>{
            value = <span style="color: blue">default</span>(T);
            <span style="color: blue">return false</span>;
        }

        <span style="color: blue">return true</span>;
    }
}
</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<div class="wlWriterSmartContent" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:6561c66c-ff96-448b-bcce-b95ce9e6ad74" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div>Download CacheHelper Sample Project:<a href="http://johnnycoder.com/blog/wp-content/uploads/2008/12/cachehelperclass.zip" target="_blank">CacheHelperClass.zip</a></div>
</p>
</div>
<p>&nbsp;</p>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:5dc6af14-55df-41a8-9c4f-0017144e9d44" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/12/10/c-cache-helper-class/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Guarding Against Multiple Empty Strings</title>
		<link>http://johnnycoder.com/blog/2008/11/12/guarding-against-multiple-empty-strings/</link>
		<comments>http://johnnycoder.com/blog/2008/11/12/guarding-against-multiple-empty-strings/#comments</comments>
		<pubDate>Thu, 13 Nov 2008 06:08:42 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/11/12/guarding-against-multiple-empty-strings/</guid>
		<description><![CDATA[Many of my C# methods include what is referred to as a guard clause.&#160; It isn&#8217;t a complicated concept.&#160; Simply the first few statements of a routine validates passed-in parameters and/or state of the object and immediately returns an error or gracefully exits to the function is constraints aren&#8217;t met.&#160; If I&#8217;m not mistaken, this [...]]]></description>
			<content:encoded><![CDATA[<p>Many of my C# methods include what is referred to as a <a href="http://c2.com/cgi/wiki?GuardClause">guard clause</a>.&nbsp; It isn&#8217;t a complicated concept.&nbsp; Simply the first few statements of a routine validates passed-in parameters and/or state of the object and immediately returns an error or gracefully exits to the function is constraints aren&#8217;t met.&nbsp; If I&#8217;m not mistaken, this plays nicely with the <a href="http://en.wikipedia.org/wiki/Design_by_contract">Design by Contract</a> approach to software design, but I no expect on the subject.&nbsp; The bottom line is, a guard clause can really tighten and clean up your code because it will undoubtedly eliminate any number of nested conditional statements.</p>
<p>Consider the following sample taken directly from <a href="http://c2.com/cgi/wiki?GuardClause">c2.com</a>:</p>
<pre class="code"><span style="color: blue">public </span>Foo merge(Foo a, Foo b)
{
    Foo result;
    <span style="color: blue">if </span>(a != <span style="color: blue">null</span>)
    {
        <span style="color: blue">if </span>(b != <span style="color: blue">null</span>)
        {
            <span style="color: green">// complicated merge code goes here.
        </span>}
        <span style="color: blue">else
        </span>{
            result = a;
        }
    }
    <span style="color: blue">else
    </span>{
        result = b;
    }
    <span style="color: blue">return </span>result;
}
</pre>
<p>Now with the guard clause&#8230;</p>
<pre class="code"><span style="color: blue">public </span>Foo merge(Foo a, Foo b)
{
    <span style="color: blue">if </span>(a == <span style="color: blue">null</span>) <span style="color: blue">return </span>b;
    <span style="color: blue">if </span>(b == <span style="color: blue">null</span>) <span style="color: blue">return </span>a;
    <span style="color: green">// complicated merge code goes here.
</span>}</pre>
<p>Much cleaner, eh? And that&#8217;s only two conditionals! Back to my point.&nbsp; Many of my method include guard clauses.&nbsp; Today I needed to validate that all three string parameters had a value.&nbsp; In other words, each string&#8217;s length was greater than 0. </p>
<p>I started with my faithful Is-Not-Null-Or-Empty check:</p>
<pre class="code"><span style="color: blue">string </span>a = <span style="color: #a31515">"a"</span>;
<span style="color: blue">string </span>b = <span style="color: #a31515">"b"</span>;
<span style="color: blue">string </span>c = <span style="color: #a31515">""</span>;

<span style="color: blue">if </span>(<span style="color: blue">string</span>.IsNullOrEmpty(a) ||
    <span style="color: blue">string</span>.IsNullOrEmpty(b) ||
    <span style="color: blue">string</span>.IsNullOrEmpty(c))
    <span style="color: blue">return</span>;</pre>
<p>But then I settled on this:</p>
<pre class="code"><span style="color: blue">string </span>a = <span style="color: #a31515">"a"</span>;
<span style="color: blue">string </span>b = <span style="color: #a31515">"b"</span>;
<span style="color: blue">string </span>c = <span style="color: #a31515">""</span>;

<span style="color: blue">if </span>(a.Length * b.Length * c.Length == 0) <span style="color: blue">return</span>;</pre>
<p><font color="#000000">What do you think?&nbsp; Pretty hokey, right?</font></p>
<p>&nbsp;</p>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:3f97a782-1b95-4fd7-a838-6c2c1c8ca986" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/11/12/guarding-against-multiple-empty-strings/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/11/12/guarding-against-multiple-empty-strings/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/11/12/guarding-against-multiple-empty-strings/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Export GridView to Excel within an UpdatePanel</title>
		<link>http://johnnycoder.com/blog/2008/07/25/export-gridview-to-excel-within-an-updatepanel/</link>
		<comments>http://johnnycoder.com/blog/2008/07/25/export-gridview-to-excel-within-an-updatepanel/#comments</comments>
		<pubDate>Sat, 26 Jul 2008 02:15:51 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Gridview]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/07/25/export-gridview-to-excel-within-an-updatepanel/</guid>
		<description><![CDATA[There&#8217;s a ton of information online about exporting a DataGrid or GridView to Excel, but most variations do not consider the GridView may reside within an UpdatePanel.  It goes without saying, but I was disappointed when I recently dusted off my &#8220;Export GridView to Excel&#8221; code snippet and encountered a number of exceptions.  So I [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a ton of information online about exporting a DataGrid or GridView to Excel, but most variations do not consider the GridView may reside within an UpdatePanel.  It goes without saying, but I was disappointed when I recently dusted off my &#8220;Export GridView to Excel&#8221; code snippet and encountered a number of exceptions.  So I revisited a number of links and I collected a working solution.  If you need a &#8220;simple&#8221; way to export your GridView to Excel and you are using an UpdatePanel, I hope the following code finds you well:</p>
<pre class="code"><span style="color: #0000ff;">protected void </span>btnExport_Click(<span style="color: #0000ff;">object </span>sender, <span style="color: #2b91af;">EventArgs </span>e)
{
    <span style="color: #008000;">// Reference your own GridView here
    </span><span style="color: #0000ff;">if </span>(AccountGrid.Rows.Count &gt; 65535)
    {
        DisplayError(<span style="color: #a31515;">"Export to Excel is not allowed" </span>+
            <span style="color: #a31515;">"due to excessive number of rows."</span>);
        <span style="color: #0000ff;">return</span>;
    }

    <span style="color: #0000ff;">string </span>filename = <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">"Results_{0}_{1}.xls"</span>,
        <span style="color: #2b91af;">DateTime</span>.Today.Month.ToString(), <span style="color: #2b91af;">DateTime</span>.Today.Year.ToString());

    Response.Clear();
    Response.AddHeader(<span style="color: #a31515;">"Content-Disposition"</span>, <span style="color: #a31515;">"attachment;filename=" </span>+ filename);
    Response.Charset = <span style="color: #a31515;">""</span>;

    <span style="color: #008000;">// SetCacheability doesn't seem to make a difference (see update)
    </span>Response.Cache.SetCacheability(System.Web.<span style="color: #2b91af;">HttpCacheability</span>.NoCache);  

    Response.ContentType = <span style="color: #a31515;">"application/vnd.xls"</span>;

    System.IO.<span style="color: #2b91af;">StringWriter </span>stringWriter = <span style="color: #0000ff;">new </span>System.IO.<span style="color: #2b91af;">StringWriter</span>();
    System.Web.UI.<span style="color: #2b91af;">HtmlTextWriter </span>htmlWriter = <span style="color: #0000ff;">new </span><span style="color: #2b91af;">HtmlTextWriter</span>(stringWriter);

    <span style="color: #008000;">// Replace all gridview controls with literals
    </span>ClearControls(AccountGrid);

    <span style="color: #008000;">// Throws exception: Control 'ComputerGrid' of type 'GridView'
    // must be placed inside a form tag with runat=server.
    // ComputerGrid.RenderControl(htmlWrite);

    // Alternate to ComputerGrid.RenderControl above
    </span>System.Web.UI.HtmlControls.<span style="color: #2b91af;">HtmlForm </span>form
        = <span style="color: #0000ff;">new </span>System.Web.UI.HtmlControls.<span style="color: #2b91af;">HtmlForm</span>();
    Controls.Add(form);
    form.Controls.Add(AccountGrid);
    form.RenderControl(htmlWriter);

    Response.Write(stringWriter.ToString());
    Response.End();
}

<span style="color: #0000ff;">private void </span>ClearControls(<span style="color: #2b91af;">Control </span>control)
{
    <span style="color: #0000ff;">for </span>(<span style="color: #0000ff;">int </span>i = control.Controls.Count - 1; i &gt;= 0; i--)
    {
        ClearControls(control.Controls[i]);
    }

    <span style="color: #0000ff;">if </span>(!(control <span style="color: #0000ff;">is </span><span style="color: #2b91af;">TableCell</span>))
    {
        <span style="color: #0000ff;">if </span>(control.GetType().GetProperty(<span style="color: #a31515;">"SelectedItem"</span>) != <span style="color: #0000ff;">null</span>)
        {
            <span style="color: #2b91af;">LiteralControl </span>literal = <span style="color: #0000ff;">new </span><span style="color: #2b91af;">LiteralControl</span>();
            control.Parent.Controls.Add(literal);
            <span style="color: #0000ff;">try
            </span>{
                literal.Text =
                    (<span style="color: #0000ff;">string</span>)control.GetType().GetProperty(<span style="color: #a31515;">"SelectedItem"</span>).
                        GetValue(control, <span style="color: #0000ff;">null</span>);
            }
            <span style="color: #0000ff;">catch
            </span>{}
            control.Parent.Controls.Remove(control);
        }
        <span style="color: #0000ff;">else if </span>(control.GetType().GetProperty(<span style="color: #a31515;">"Text"</span>) != <span style="color: #0000ff;">null</span>)
        {
            <span style="color: #2b91af;">LiteralControl </span>literal = <span style="color: #0000ff;">new </span><span style="color: #2b91af;">LiteralControl</span>();
            control.Parent.Controls.Add(literal);
            literal.Text =
                (<span style="color: #0000ff;">string</span>)control.GetType().GetProperty(<span style="color: #a31515;">"Text"</span>).
                    GetValue(control, <span style="color: #0000ff;">null</span>);
            control.Parent.Controls.Remove(control);
        }
    }
    <span style="color: #0000ff;">return</span>;
}</pre>
<pre class="code"> </pre>
<h3>Update: 7/30/2008</h3>
<p>I previously noted that SetCacheability doesn&#8217;t seem to make a difference.  Well, I was right&#8230;until I deployed my code to a site behind SSL.  As it turns out, in order for Internet Explorer to open documents in Office (or any out-of-process, ActiveX document server), Internet Explorer must save the file to the local cache directory and ask the associated application to load the file by using IPersistFile::Load.</p>
<p><a href="http://support.microsoft.com/default.aspx?scid=KB;EN-US;q316431&amp;">http://support.microsoft.com/default.aspx?scid=KB;EN-US;q316431&amp;</a></p>
<p>If the file is not stored to disk, this operation fails. When Internet Explorer communicates with a secure Web site through SSL, Internet Explorer enforces any no-cache request. If the header or headers are present, Internet Explorer does not cache the file. Consequently, Office cannot open the file.</p>
<p>RESOLUTION: Web sites that want to allow this type of operation should remove the no-cache header or headers. In other words, comment out the following line of code particularly if you are running under SSL:</p>
<p>Response.Cache.SetCacheability(System.Web.HttpCacheability.NoCache); </p>
<p> </p>
<h3>Additional Comments</h3>
<p>Per <a href="http://jinath.wordpress.com/2008/02/18/export-gridview-to-excel-inside-an-update-panel/">Jinath Blog</a>, if you are using an UpdatePanel, you may get a System.WebForms.PageRequestManagerParserErrorException exception.  The solution is to add a PostBackTrigger and give it’s ControlID as the excel export button’s ID or you can move your excel export button out side of the update panel.  I verified both options and they work great.  I ultimately went with the former option as such:</p>
<pre class="code">    ...
    <span style="color: #0000ff;">&lt;/</span><span style="color: #a31515;">ContentTemplate</span><span style="color: #0000ff;">&gt;
    &lt;</span><span style="color: #a31515;">Triggers</span><span style="color: #0000ff;">&gt;
        &lt;</span><span style="color: #a31515;">asp</span><span style="color: #0000ff;">:</span><span style="color: #a31515;">PostBackTrigger </span><span style="color: #ff0000;">ControlID</span><span style="color: #0000ff;">="btnExport" /&gt;
    &lt;/</span><span style="color: #a31515;">Triggers</span><span style="color: #0000ff;">&gt;
&lt;/</span><span style="color: #a31515;">asp</span><span style="color: #0000ff;">:</span><span style="color: #a31515;">UpdatePanel</span><span style="color: #0000ff;">&gt;
</span>...</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Per <a href="http://aspalliance.com/771_CodeSnip_Exporting_GridView_to_Excel">ASPAlliance</a>, you may encounter issues a number of issues which require the following solution.  Check out the link (and the comments) for more details if you get stuck.  I only encountered #1 on the list.</p>
<ol>
<li>You may get an exception which states your Control &#8216;Grid&#8217; of type &#8216;GridView&#8217; must be placed inside a form tag with runat=server.  I overcame this by dynamically adding a form to the page and then the GridView to the form before RenderContent().  This solution came per the aforementioned post&#8217;s comments.</li>
<li>You may need to included the following page directive: EnableEventValidation=&#8221;false&#8221;.  I didn&#8217;t need to include this directive.</li>
<li>You may need Override the VerifyRenderingInServerForm Method.  I didn&#8217;t need to do so because I added my GridView control to a &#8220;mocked&#8221; form.<br />
 </li>
</ol>
<p>Per <a href="http://www.c-sharpcorner.com/UploadFile/DipalChoksi/ExportASPNetDataGridToExcel11222005041447AM/ExportASPNetDataGridToExcel.aspx">Dipal Choksi</a>, one can format the spreadsheet results in a generic manner by replacing all controls within the GridView with Literals.  This is reflected in the ClearControls() method above.  My prior implementation merely cleaned up the links associated with the sort functionality tied to the sortable headers.  This solution tackles all cells.</p>
<p>Additional Reference: <a href="http://gridviewguy.com/ArticleDetails.aspx?articleID=26">GridViewGuy</a> </p>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:00b54b2d-1096-495d-bdd6-aac1a8f61396" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/07/25/export-gridview-to-excel-within-an-updatepanel/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/07/25/export-gridview-to-excel-within-an-updatepanel/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/07/25/export-gridview-to-excel-within-an-updatepanel/feed/</wfw:commentRss>
		<slash:comments>44</slash:comments>
		</item>
		<item>
		<title>C# Encryption / Decryption Helper Class</title>
		<link>http://johnnycoder.com/blog/2008/07/03/c-encryption-decryption-helper-class/</link>
		<comments>http://johnnycoder.com/blog/2008/07/03/c-encryption-decryption-helper-class/#comments</comments>
		<pubDate>Fri, 04 Jul 2008 06:09:30 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Library]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/07/03/c-encryption-decryption-helper-class/</guid>
		<description><![CDATA[I have collected a reasonably good size library of C# helper files over the years.  The EncryptionHelper below is one of many which I plan to share. using System; using System.Security.Cryptography; using System.Text; namespace Common { public static class EncryptionHelper { private const string cryptoKey = "cryptoKey"; // The Initialization Vector for the DES encryption [...]]]></description>
			<content:encoded><![CDATA[<p>I have collected a reasonably good size library of C# helper files over the years.  The EncryptionHelper below is one of many which I plan to share.</p>
<pre class="code"><span style="color: #0000ff;">using </span>System;
<span style="color: #0000ff;">using </span>System.Security.Cryptography;
<span style="color: #0000ff;">using </span>System.Text;

<span style="color: #0000ff;">namespace </span>Common
{
    <span style="color: #0000ff;">public static class </span><span style="color: #2b91af;">EncryptionHelper
    </span>{
        <span style="color: #0000ff;">private const string </span>cryptoKey = <span style="color: #a31515;">"cryptoKey"</span>;

        <span style="color: #008000;">// The Initialization Vector for the DES encryption routine
        </span><span style="color: #0000ff;">private static readonly byte</span>[] IV =
            <span style="color: #0000ff;">new byte</span>[8] { 240, 3, 45, 29, 0, 76, 173, 59 };

        <span style="color: #808080;">/// &lt;summary&gt;
        /// </span><span style="color: #008000;">Encrypts provided string parameter
        </span><span style="color: #808080;">/// &lt;/summary&gt;
        </span><span style="color: #0000ff;">public static string </span>Encrypt(<span style="color: #0000ff;">string </span>s)
        {
            <span style="color: #0000ff;">if </span>(s == <span style="color: #0000ff;">null </span>|| s.Length == 0) <span style="color: #0000ff;">return string</span>.Empty;

            <span style="color: #0000ff;">string </span>result = <span style="color: #0000ff;">string</span>.Empty;

            <span style="color: #0000ff;">try
            </span>{
                <span style="color: #0000ff;">byte</span>[] buffer = <span style="color: #2b91af;">Encoding</span>.ASCII.GetBytes(s);

                <span style="color: #2b91af;">TripleDESCryptoServiceProvider </span>des =
                    <span style="color: #0000ff;">new </span><span style="color: #2b91af;">TripleDESCryptoServiceProvider</span>();

                <span style="color: #2b91af;">MD5CryptoServiceProvider </span>MD5 =
                    <span style="color: #0000ff;">new </span><span style="color: #2b91af;">MD5CryptoServiceProvider</span>();

                des.Key =
                    MD5.ComputeHash(<span style="color: #2b91af;">ASCIIEncoding</span>.ASCII.GetBytes(cryptoKey));

                des.IV = IV;
                result = <span style="color: #2b91af;">Convert</span>.ToBase64String(
                    des.CreateEncryptor().TransformFinalBlock(
                        buffer, 0, buffer.Length));
            }
            <span style="color: #0000ff;">catch
            </span>{
                <span style="color: #0000ff;">throw</span>;
            }

            <span style="color: #0000ff;">return </span>result;
        }

        <span style="color: #808080;">/// &lt;summary&gt;
        /// </span><span style="color: #008000;">Decrypts provided string parameter
        </span><span style="color: #808080;">/// &lt;/summary&gt;
        </span><span style="color: #0000ff;">public static string </span>Decrypt(<span style="color: #0000ff;">string </span>s)
        {
            <span style="color: #0000ff;">if </span>(s == <span style="color: #0000ff;">null </span>|| s.Length == 0) <span style="color: #0000ff;">return string</span>.Empty;

            <span style="color: #0000ff;">string </span>result = <span style="color: #0000ff;">string</span>.Empty;

            <span style="color: #0000ff;">try
            </span>{
                <span style="color: #0000ff;">byte</span>[] buffer = <span style="color: #2b91af;">Convert</span>.FromBase64String(s);

                <span style="color: #2b91af;">TripleDESCryptoServiceProvider </span>des =
                    <span style="color: #0000ff;">new </span><span style="color: #2b91af;">TripleDESCryptoServiceProvider</span>();

                <span style="color: #2b91af;">MD5CryptoServiceProvider </span>MD5 =
                    <span style="color: #0000ff;">new </span><span style="color: #2b91af;">MD5CryptoServiceProvider</span>();

                des.Key =
                    MD5.ComputeHash(<span style="color: #2b91af;">ASCIIEncoding</span>.ASCII.GetBytes(cryptoKey));

                des.IV = IV;

                result = <span style="color: #2b91af;">Encoding</span>.ASCII.GetString(
                    des.CreateDecryptor().TransformFinalBlock(
                    buffer, 0, buffer.Length));
            }
            <span style="color: #0000ff;">catch
            </span>{
                <span style="color: #0000ff;">throw</span>;
            }

            <span style="color: #0000ff;">return </span>result;
        }
    }
}</pre>
<p>You may have noticed that my recent posts have been short and provide little more than featured code.   This is a new approach for me.  What do you think?  Should I continue to pepper in these quick code snippet posts with little commentary?</p>
<p> </p>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:d5536c35-ddc0-49be-934c-23ab9c843238" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/07/03/c-encryption-decryption-helper-class/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/07/03/c-encryption-decryption-helper-class/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/07/03/c-encryption-decryption-helper-class/feed/</wfw:commentRss>
		<slash:comments>18</slash:comments>
		</item>
		<item>
		<title>Check Status of Windows Service</title>
		<link>http://johnnycoder.com/blog/2008/07/01/check-status-of-windows-service/</link>
		<comments>http://johnnycoder.com/blog/2008/07/01/check-status-of-windows-service/#comments</comments>
		<pubDate>Wed, 02 Jul 2008 06:12:08 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[Services]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/07/01/check-status-of-windows-service/</guid>
		<description><![CDATA[In the same vein as my last post on how to programmatically update a service startup type, here&#8217;s how one might determine if a service is currently stopped in C#: using System.Management; /// &#60;summary&#62; /// This routine checks if the provided service is stopped. /// &#60;/summary&#62; /// &#60;param name="serviceName"&#62;Name of the service to be checked&#60;/param&#62; [...]]]></description>
			<content:encoded><![CDATA[<p>In the same vein as my last post on how to programmatically <a href="http://johnnycoder.com/blog/2008/07/01/update-service-startup-type/">update a service startup type</a>, here&#8217;s how one might determine if a service is currently stopped in C#:</p>
<pre class="code"><span style="color: #0000ff;">using </span>System.Management;</pre>
<pre class="code"><span style="color: #808080;">/// &lt;summary&gt;
/// </span><span style="color: #008000;">This routine checks if the provided service is stopped.
</span><span style="color: #808080;">/// &lt;/summary&gt;
/// &lt;param name="serviceName"&gt;</span><span style="color: #008000;">Name of the service to be checked</span><span style="color: #808080;">&lt;/param&gt;
/// &lt;param name="errorMsg"&gt;</span><span style="color: #008000;">If applicable, error message assoicated with exception</span><span style="color: #808080;">&lt;/param&gt;
/// &lt;returns&gt;</span><span style="color: #008000;">Stopped = true else false</span><span style="color: #808080;">&lt;/returns&gt;
</span><span style="color: #0000ff;">public static bool </span>IsServiceStopped(<span style="color: #0000ff;">string </span>serviceName, <span style="color: #0000ff;">out string </span>errorMsg)
{
    <span style="color: #0000ff;">bool </span>isStopped = <span style="color: #0000ff;">false</span>;
    errorMsg = <span style="color: #0000ff;">string</span>.Empty;

    <span style="color: #0000ff;">string </span>filter =
        <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">"SELECT * FROM Win32_Service WHERE Name = '{0}'"</span>, serviceName);

    <span style="color: #2b91af;">ManagementObjectSearcher </span>query = <span style="color: #0000ff;">new </span><span style="color: #2b91af;">ManagementObjectSearcher</span>(filter);

    <span style="color: #008000;">// No match = stopped
    </span><span style="color: #0000ff;">if </span>(query == <span style="color: #0000ff;">null</span>) <span style="color: #0000ff;">return false</span>;

    <span style="color: #0000ff;">try
    </span>{
        <span style="color: #2b91af;">ManagementObjectCollection </span>services = query.Get();

        <span style="color: #0000ff;">foreach </span>(<span style="color: #2b91af;">ManagementObject </span>service <span style="color: #0000ff;">in </span>services)
        {
            <span style="color: #0000ff;">string </span>currentStatus = <span style="color: #2b91af;">Convert</span>.ToString(service[<span style="color: #a31515;">"State"</span>]);
            isStopped = (currentStatus.ToLower() == <span style="color: #a31515;">"stopped"</span>);
        }
    }
    <span style="color: #0000ff;">catch </span>(<span style="color: #2b91af;">Exception </span>ex)
    {
        errorMsg = ex.Message;
        <span style="color: #0000ff;">throw</span>;
    }

    <span style="color: #0000ff;">return </span>isStopped;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:a87487cf-58bd-48c2-8888-f2a9054bd2cc" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/07/01/check-status-of-windows-service/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/07/01/check-status-of-windows-service/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/07/01/check-status-of-windows-service/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Update Service Startup Type</title>
		<link>http://johnnycoder.com/blog/2008/07/01/update-service-startup-type/</link>
		<comments>http://johnnycoder.com/blog/2008/07/01/update-service-startup-type/#comments</comments>
		<pubDate>Wed, 02 Jul 2008 05:48:16 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[Services]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/07/01/update-service-startup-type/</guid>
		<description><![CDATA[For the past six years I&#8217;ve been focused on web applications.  My current project, however, has me splitting time between the web and the desktop.  Today, I needed to programmatically toggle the Startup Type of my service between Manual and Automatic based on business conditions.   Here&#8217;s how I did it: /// &#60;summary&#62; /// This routine [...]]]></description>
			<content:encoded><![CDATA[<p>For the past six years I&#8217;ve been focused on web applications.  My current project, however, has me splitting time between the web and the desktop.  Today, I needed to programmatically toggle the Startup Type of my service between Manual and Automatic based on business conditions.   Here&#8217;s how I did it:</p>
<pre class="code"><span style="color: #808080;">/// &lt;summary&gt;
/// </span><span style="color: #008000;">This routine updates the start mode of the provided service.
</span><span style="color: #808080;">/// &lt;/summary&gt;
/// &lt;param name="serviceName"&gt;</span><span style="color: #008000;">Name of the service to be updated</span><span style="color: #808080;">&lt;/param&gt;
/// &lt;param name="startMode"&gt;</span><span style="color: #008000;">Manual or Automatic. This parameter could probably use
</span><span style="color: #808080;">/// </span><span style="color: #008000;">an enum.</span><span style="color: #808080;">&lt;/param&gt;
/// &lt;param name="errorMsg"&gt;</span><span style="color: #008000;">If applicable, error message assoicated with exception</span><span style="color: #808080;">&lt;/param&gt;
/// &lt;returns&gt;</span><span style="color: #008000;">Success or failure.  False is returned if service is not found.</span><span style="color: #808080;">&lt;/returns&gt;
</span><span style="color: #0000ff;">public bool </span>ServiceStartModeUpdate(<span style="color: #0000ff;">string </span>serviceName, <span style="color: #0000ff;">string </span>startMode,
    <span style="color: #0000ff;">out string </span>errorMsg)
{
    <span style="color: #0000ff;">uint </span>success = 1;
    errorMsg = <span style="color: #0000ff;">string</span>.Empty;

    <span style="color: #0000ff;">string </span>filter =
        <span style="color: #2b91af;">String</span>.Format(<span style="color: #a31515;">"SELECT * FROM Win32_Service WHERE Name = '{0}'"</span>, serviceName);

    <span style="color: #2b91af;">ManagementObjectSearcher </span>query = <span style="color: #0000ff;">new </span><span style="color: #2b91af;">ManagementObjectSearcher</span>(filter);

    <span style="color: #008000;">// No match = failed condition
    </span><span style="color: #0000ff;">if </span>(query == <span style="color: #0000ff;">null</span>) <span style="color: #0000ff;">return false</span>; 

    <span style="color: #0000ff;">try
    </span>{
        <span style="color: #2b91af;">ManagementObjectCollection </span>services = query.Get();

        <span style="color: #0000ff;">foreach </span>(<span style="color: #2b91af;">ManagementObject </span>service <span style="color: #0000ff;">in </span>services)
        {
            <span style="color: #2b91af;">ManagementBaseObject </span>inParams =
                service.GetMethodParameters(<span style="color: #a31515;">"ChangeStartMode"</span>);
            inParams[<span style="color: #a31515;">"startmode"</span>] = startMode;

            <span style="color: #2b91af;">ManagementBaseObject </span>outParams =
                service.InvokeMethod(<span style="color: #a31515;">"ChangeStartMode"</span>, inParams, <span style="color: #0000ff;">null</span>);
            success = <span style="color: #2b91af;">Convert</span>.ToUInt16(outParams.Properties[<span style="color: #a31515;">"ReturnValue"</span>].Value);
        }
    }
    <span style="color: #0000ff;">catch </span>(<span style="color: #2b91af;">Exception </span>ex)
    {
        errorMsg = ex.Message;
        <span style="color: #0000ff;">throw</span>;
    }

    <span style="color: #0000ff;">return </span>(success == 0);
}</pre>
<p>As I&#8217;ve been doing a lot with services and windows applications lately, don&#8217;t be surprised in up coming posts start moving down this track.  Oh yes, I&#8217;ve done a lot with custom installers which I&#8217;m sure to write about as well.</p>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:4f985222-689f-4d7b-b8e0-aab080b88467" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/07/01/update-service-startup-type/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/07/01/update-service-startup-type/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
<p><a href="http://11011.net/software/vspaste"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/07/01/update-service-startup-type/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Safe Cast for No Good Reason</title>
		<link>http://johnnycoder.com/blog/2008/06/10/safe-cast-for-no-good-reason/</link>
		<comments>http://johnnycoder.com/blog/2008/06/10/safe-cast-for-no-good-reason/#comments</comments>
		<pubDate>Wed, 11 Jun 2008 03:17:15 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[Best Practices]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/06/10/safe-cast-for-no-good-reason/</guid>
		<description><![CDATA[I&#8217;m not sure I can come up with a good argument to ever use Safe Casting.  Per my earlier post, I&#8217;m not able to convert the result of the following Predicate, List&#60;MachineProduct&#62;, to a MachineProductCollection even though MachineProductCollection inherits from List&#60;MachineProduct&#62;.   // Code complies and the invalid Cast results in // machineProducts being set to [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m not sure I can come up with a good argument to ever use Safe Casting.  Per my <a href="http://johnnycoder.com/blog/2008/06/10/invalidcastexception-though-same-base-class/">earlier post</a>, I&#8217;m not able to convert the result of the following Predicate, List&lt;MachineProduct&gt;, to a MachineProductCollection even though MachineProductCollection inherits from List&lt;MachineProduct&gt;.  </p>
<pre class="code"><span style="color: #008000;">// Code complies and the invalid Cast results in
// machineProducts being set to null instead of an
// exception being thrown.
</span><span style="color: #2b91af;">MachineProductCollection </span>machineProducts =
    MachineProductList.FindAll(c =&gt; c.MachineID == MachineID)
    <span style="color: #0000ff;">as </span><span style="color: #2b91af;">MachineProductCollection</span>;</pre>
<p>As statement in the above comment, the invalid cast is essentially masked due to the Safe Cast or the convert using the &#8220;as&#8221; operator.  Alternative implementations, I believe, are more appropriate as an implicit conversion causes a pre-runtime, compilation error and a &#8220;traditional&#8221; cast throws an InvalidCastException at runtime, respectively:</p>
<pre class="code"><span style="color: #008000;">// Compiler complains since it knows List&lt;MachineProduct&gt; can not
// be converted to MachineProductCollection
</span><span style="color: #2b91af;">MachineProductCollection </span>machineProducts =
        MachineProductList.FindAll(c =&gt; c.MachineID == MachineID);

<span style="color: #008000;">// Code compiles but a runtime InvalidCastException is thrown
// since List&lt;MachineProduct&gt; can not be converted to
// MachineProductCollection
</span><span style="color: #2b91af;">MachineProductCollection </span>machineProducts = (<span style="color: #2b91af;">MachineProductCollection</span>)
        MachineProductList.FindAll(c =&gt; c.MachineID == MachineID);</pre>
<p>I&#8217;m probably missing something but I can&#8217;t think of a scenario in which I would <span style="text-decoration: underline;">intentionally</span> want to assign a null value if my cast is invalid.  Why &#8220;swallow&#8221; the exception and work with bad data?  It doesn&#8217;t make sense to me.</p>
<p>I&#8217;ve read that one should use the &#8220;is&#8221; operator in conjunction with the &#8220;as&#8221; operator.  Basically, this ensures the conversion is valid before it is executed, but what is the point.  Do more work to get the same lousy, invalid result?</p>
<pre class="code"><span style="color: #008000;">// What is the point of this?
</span><span style="color: #2b91af;">MachineProductCollection </span>machineProducts = <span style="color: #0000ff;">null</span>;

<span style="color: #0000ff;">if </span>(MachineProductList.FindAll(c =&gt;
    c.MachineID == MachineID) <span style="color: #0000ff;">is </span><span style="color: #2b91af;">MachineProductCollection</span>)
{
    machineProducts = MachineProductList.FindAll(c =&gt; c.MachineID == MachineID)
        <span style="color: #0000ff;">as </span><span style="color: #2b91af;">MachineProductCollection</span>;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Perhaps I should have taken more CS classes in college&#8230;</p>
<p><em>Additional References:</em></p>
<ul>
<li><a href="http://www.aspheute.com/english/20001019.asp"><em>Safe Conversion of Reference Types</em></a><em>
<p></em></li>
</ul>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:ac4ef825-870b-42b2-a8bc-774c061bced1" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/06/10/safe-cast-for-no-good-reason/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/06/10/safe-cast-for-no-good-reason/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/06/10/safe-cast-for-no-good-reason/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>InvalidCastException Though Same Base Class</title>
		<link>http://johnnycoder.com/blog/2008/06/10/invalidcastexception-though-same-base-class/</link>
		<comments>http://johnnycoder.com/blog/2008/06/10/invalidcastexception-though-same-base-class/#comments</comments>
		<pubDate>Tue, 10 Jun 2008 19:41:28 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[Brain Scratcher]]></category>
		<category><![CDATA[C#]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/06/10/invalidcastexception-though-same-base-class/</guid>
		<description><![CDATA[The following code throws an InvalidCastException. public static MachineProductCollection MachineProductsForMachine( MachineProductCollection MachineProductList, int MachineID) { return (MachineProductCollection) MachineProductList.FindAll(c =&#62; c.MachineID == MachineID); } This surprises me since MachineProductCollection is merely a generic List of MachineProducts which is exactly FindAll() returns.  Here&#8217;s the full MachineProductCollection source code: [Serializable] public partial classMachineProductCollection : List&#60;MachineProduct&#62; { public MachineProductCollection() [...]]]></description>
			<content:encoded><![CDATA[<p>The following code throws an <a href="http://msdn.microsoft.com/en-us/library/system.invalidcastexception.aspx">InvalidCastException</a>.</p>
<pre class="code"><span style="color: #0000ff;">public static </span><span style="color: #2b91af;">MachineProductCollection </span>MachineProductsForMachine(
    <span style="color: #2b91af;">MachineProductCollection </span>MachineProductList, <span style="color: #0000ff;">int </span>MachineID)
{
    <span style="color: #0000ff;">return </span>(<span style="color: #2b91af;">MachineProductCollection</span>)
        MachineProductList.FindAll(c =&gt; c.MachineID == MachineID);
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>This surprises me since MachineProductCollection is merely a generic List of MachineProducts which is exactly FindAll() returns.  Here&#8217;s the full MachineProductCollection source code:</p>
<pre class="code">[<span style="color: #2b91af;">Serializable</span>]
<span style="color: #0000ff;">public </span>partial classMachineProductCollection :
        <span style="color: #2b91af;">List</span>&lt;<span style="color: #2b91af;">MachineProduct</span>&gt;
{
    <span style="color: #0000ff;">public </span>MachineProductCollection() { }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>I resorted to the following which basically loops through the resulting List&lt;MachineProduct&gt; and adds them to my MachineProductCollection.  Obviously, I don&#8217;t like the required iteration. </p>
<pre class="code"><span style="color: #0000ff;">public static </span><span style="color: #2b91af;">MachineProductCollection
    </span>MachineProductForMachine(<span style="color: #2b91af;">MachineProductCollection
    </span>MachineProductList, <span style="color: #0000ff;">int </span>MachineID)
{
    <span style="color: #2b91af;">MachineProductCollection </span>result =
        <span style="color: #0000ff;">new </span><span style="color: #2b91af;">MachineProductCollection</span>();

    <span style="color: #0000ff;">foreach </span>(<span style="color: #2b91af;">MachineProduct </span>machineProduct <span style="color: #0000ff;">in
        </span>MachineProductList.FindAll(c =&gt; c.MachineID == MachineID))
    {
        result.Add(machineProduct);
    }

    <span style="color: #0000ff;">return </span>result;
}</pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Documentation states an InvalidCastException is thrown when a failure occurs during an explicit reference conversion. Reference conversions are conversions from one reference type to another. While they may change the type of the reference, they never change the type or value of the conversion&#8217;s target. Casting objects from one type to another is a frequent cause for this exception.</p>
<p>Considering List&lt;MachineProduct&gt; is MachineProductCollection&#8217;s base, should this really be an InvalidCastException?</p>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:97a7d253-415f-4e3d-95e6-368a570c477a" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/06/10/invalidcastexception-though-same-base-class/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/06/10/invalidcastexception-though-same-base-class/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
<p><a href="http://johnnycoder.com/blog/wp-content/uploads/2008/06/image9.png"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/06/10/invalidcastexception-though-same-base-class/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>C# Serializing Nullable Types</title>
		<link>http://johnnycoder.com/blog/2008/06/09/c-serializing-nullable-types/</link>
		<comments>http://johnnycoder.com/blog/2008/06/09/c-serializing-nullable-types/#comments</comments>
		<pubDate>Mon, 09 Jun 2008 19:53:07 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/06/09/c-serializing-nullable-types/</guid>
		<description><![CDATA[There&#8217;s a lot of information (including sample routines) on how to serialize/deserialize objects in C#.  Hunt down a couple of routines that accept generic types and add them to your personal utility class and reuse them forever.  Be aware, however, that there&#8217;s an issue with serializing nullable types. Basically it can&#8217;t be done if an [...]]]></description>
			<content:encoded><![CDATA[<p>There&#8217;s a lot of information (including sample routines) on how to serialize/deserialize objects in C#.  Hunt down a couple of routines that accept generic types and add them to your personal utility class and reuse them forever.  Be aware, however, that there&#8217;s an issue with serializing nullable types. Basically it can&#8217;t be done if an object&#8217;s property is marked with an XmlAttribute.  You will need to mark the property as an XmlElement.</p>
<p>[<span style="color: #2b91af;">XmlElement</span>(IsNullable=<span style="color: #0000ff;">true</span>)] <span style="color: #0000ff;">public </span><span style="color: #2b91af;">DateTime</span>? MachineDateChange { <span style="color: #0000ff;">get </span>; <span style="color: #0000ff;">set </span>; }</p>
<p>And use some caution as the property datatype must match the IsNullable setting for the XmlElement markup.  Believe it or not, the following &#8220;type mismatch&#8221; will throw an exception when serializing since MachineDateChange, in the following case, isn&#8217;t actually nullable like it is above:</p>
<p>[<span style="color: #2b91af;">XmlElement</span>(IsNullable = <span style="color: #0000ff;">true</span>)] <span style="color: #0000ff;">public </span><span style="color: #2b91af;">DateTime </span>MachineDateChange { <span style="color: #0000ff;">get</span>; <span style="color: #0000ff;">set</span>; }</p>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Here are a couple of good resources:</p>
<ul>
<li><a href="http://www.alteridem.net/2007/08/13/introduction-to-xml-serialization/">Introduction to XML Serialization</a></li>
<li><a href="http://andrewgunn.blogspot.com/2008/06/xml-serialization-in-cnet.html">XML Serialization in C# .NET</a> </li>
</ul>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:4ff351c3-d239-46f8-933f-2d241fc9f198" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/06/09/c-serializing-nullable-types/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/06/09/c-serializing-nullable-types/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/06/09/c-serializing-nullable-types/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>C# Coalesce Operator</title>
		<link>http://johnnycoder.com/blog/2008/06/09/c-coalesce-operator/</link>
		<comments>http://johnnycoder.com/blog/2008/06/09/c-coalesce-operator/#comments</comments>
		<pubDate>Mon, 09 Jun 2008 18:14:53 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/06/09/c-coalesce-operator/</guid>
		<description><![CDATA[My favorite TSQL Function is COALESCE which returns the first non-null expression among its arguments.  If all arguments are null, null is returned.  Here are a couple of simple examples: declare @a varchar(25); set @a = null; declare @b varchar(25); set @b = null; declare @c varchar(25); set @c = 'I am not null'; select [...]]]></description>
			<content:encoded><![CDATA[<p>My favorite TSQL Function is COALESCE which returns the first non-null expression among its arguments.  If all arguments are null, null is returned.  Here are a couple of simple examples:</p>
<pre class="code"><span style="color: #0000ff;">declare </span>@a <span style="color: #0000ff;">varchar</span><span style="color: #808080;">(</span>25<span style="color: #808080;">); </span><span style="color: #0000ff;">set </span>@a <span style="color: #808080;">= null;
</span><span style="color: #0000ff;">declare </span>@b <span style="color: #0000ff;">varchar</span><span style="color: #808080;">(</span>25<span style="color: #808080;">); </span><span style="color: #0000ff;">set </span>@b <span style="color: #808080;">= null;
</span><span style="color: #0000ff;">declare </span>@c <span style="color: #0000ff;">varchar</span><span style="color: #808080;">(</span>25<span style="color: #808080;">); </span><span style="color: #0000ff;">set </span>@c <span style="color: #808080;">= </span><span style="color: #ff0000;">'I am not null'</span><span style="color: #808080;">;

</span><span style="color: #0000ff;">select </span><span style="color: #ff00ff;">coalesce</span><span style="color: #808080;">(</span>@a<span style="color: #808080;">, </span>@b<span style="color: #808080;">, </span>@c<span style="color: #808080;">);

</span><span style="color: #008000;">-------------------------
</span>I am <span style="color: #808080;">not null            

(</span>1 row<span style="color: #808080;">(</span>s<span style="color: #808080;">) </span>affected<span style="color: #808080;">)

</span><span style="color: #0000ff;">select </span><span style="color: #ff00ff;">coalesce</span><span style="color: #808080;">(</span>@a<span style="color: #808080;">, </span>@b<span style="color: #808080;">);

</span><span style="color: #008000;">-------------------------
</span><span style="color: #808080;">NULL

(</span>1 row<span style="color: #808080;">(</span>s<span style="color: #808080;">) </span>affected<span style="color: #808080;">)</span></pre>
<p>Coalesce can be really slick especially if you want to <a href="http://johnnycoder.com/blog/2006/09/05/concatenate-multiple-rows-into-a-single-string/">concatenate multiple rows into a single string</a>.</p>
<p>As of .NET 2.0 we can use the C# Coalesce Operator.  The same concept applies &#8212; provided arguments are evaluated and the first non-null argument is returned.</p>
<pre class="code"><span style="color: #2b91af;">RegistryKey </span>regKey = <span style="color: #2b91af;">Registry</span>.LocalMachine.OpenSubKey(baseKey, <span style="color: #0000ff;">true</span>) ??
                     <span style="color: #2b91af;">Registry</span>.LocalMachine.CreateSubKey(baseKey);</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>Above you will notice &#8220;??&#8221; is the delimiter.  If the baseKey can&#8217;t be found, the first argument evaluates to null.  In turn, the second argument will create the baseKey and return the reference.  I&#8217;ve found this particular pattern (return reference if it exists, else create reference and return) to be most useful. </p>
<p>The above code snippet is for demonstration purposes only.  It should be noted that the CreateSubKey function creates a new subkey or opens an existing subkey on its own.  Perhaps CreateSubKey uses a form of the Coalesce Operator itself&#8230;</p>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:aebeed5c-b1c1-4d66-b02f-e77e8d868f61" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/06/09/c-coalesce-operator/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/06/09/c-coalesce-operator/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/06/09/c-coalesce-operator/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Path.Combine() for URLs</title>
		<link>http://johnnycoder.com/blog/2008/06/08/pathcombine-for-urls/</link>
		<comments>http://johnnycoder.com/blog/2008/06/08/pathcombine-for-urls/#comments</comments>
		<pubDate>Sun, 08 Jun 2008 22:03:39 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/06/08/pathcombine-for-urls/</guid>
		<description><![CDATA[You are familiar with System.IO.Path.Combine() method which combines two path strings and manages the trailing separator character (a.k.a. a backslash (&#8220;\&#8221;)), right?  Here&#8217;s an example of what I am talking about: System.IO.Path.Combine("C:\temp", "subdir\file.txt");// output = "c:\temp\subdir\file.txt" Are you bored yet?   Okay, pop quiz. In my current project, I need to download a file and [...]]]></description>
			<content:encoded><![CDATA[<p>You are familiar with <a href="http://msdn.microsoft.com/en-us/library/system.io.path.combine.aspx">System.IO.Path.Combine() method</a> which combines two path strings and manages the trailing separator character (a.k.a. a backslash (&#8220;\&#8221;)), right?  Here&#8217;s an example of what I am talking about:</p>
<pre class="code">System.IO.<span style="color: #2b91af;">Path</span>.Combine(<span style="color: #a31515;">"C:\temp"</span>, <span style="color: #a31515;">"subdir\file.txt"</span>);<span style="color: #008000;">// output = "c:\temp\subdir\file.txt"</span></pre>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>Are you bored yet? <img src='http://johnnycoder.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  </p>
<p>Okay, pop quiz. In my current project, I need to download a file and I would like to effortlessly add-or-not-add-the-trailing-slash when building my URL.  I would think there would be a URL equivalent but I haven&#8217;t uncovered one.  Using <span style="color: #2b91af;">Path</span>.Combine() as-is gets me close although backslashes get mixed with my forward slashes:</p>
<p><span style="color: #0000ff;">string </span>output = System.IO.<span style="color: #2b91af;">Path</span>.Combine(<span style="color: #a31515;">&#8220;http://www.abc.com/msi&#8221;</span>, <span style="color: #a31515;">&#8220;app.msi&#8221;</span>);</p>
<p><span style="color: #008000;">// output = http://www.abc.com/msi\\app.msi</span></p>
<p><a href="http://11011.net/software/vspaste"></a><a href="http://11011.net/software/vspaste"></a></p>
<p>So, I threw in a replace which seems to work well although it smells really bad to me. (Hence this post.)  Below you will find my, um, findings.  Is there a better way or does using Replace() smell okay to you?</p>
<pre class="code"><span style="color: #0000ff;">string </span>pathWithEndingSlash = <span style="color: #a31515;">"http://www.abc.com/msi/"</span>;
<span style="color: #0000ff;">string </span>file = <span style="color: #a31515;">"app.msi"</span>;
<span style="color: #0000ff;">string </span>output = System.IO.<span style="color: #2b91af;">Path</span>.Combine(pathWithEndingSlash, file).Replace(<span style="color: #a31515;">"\\"</span>, <span style="color: #a31515;">"/"</span>);
<span style="color: #008000;">// output = http://www.abc.com/msi/app.msi

</span><span style="color: #0000ff;">string </span>pathWithoutEndingSlash = <span style="color: #a31515;">"http://www.abc.com/msi"</span>;
output = System.IO.<span style="color: #2b91af;">Path</span>.Combine(pathWithoutEndingSlash, file).Replace(<span style="color: #a31515;">"\\"</span>, <span style="color: #a31515;">"/"</span>);
<span style="color: #008000;">// output = http://www.abc.com/msi/app.msi

</span><span style="color: #0000ff;">string </span>pathEmpty = <span style="color: #0000ff;">string</span>.Empty;
output = System.IO.<span style="color: #2b91af;">Path</span>.Combine(pathEmpty, file).Replace(<span style="color: #a31515;">"\\"</span>, <span style="color: #a31515;">"/"</span>);
<span style="color: #008000;">// output = Returns app.msi

</span><span style="color: #0000ff;">try
</span>{
    <span style="color: #0000ff;">string </span>pathNull = <span style="color: #0000ff;">null</span>;
    output = System.IO.<span style="color: #2b91af;">Path</span>.Combine(pathNull, file).Replace(<span style="color: #a31515;">"\\"</span>, <span style="color: #a31515;">"/"</span>);
}
<span style="color: #0000ff;">catch
</span>{
    <span style="color: #008000;">// Throws exception as would same statement without the .Replace()
</span>}

<span style="color: #0000ff;">string </span>fileEmpty = <span style="color: #0000ff;">string</span>.Empty;
output = System.IO.<span style="color: #2b91af;">Path</span>.Combine(pathWithoutEndingSlash, fileEmpty).Replace(<span style="color: #a31515;">"\\"</span>, <span style="color: #a31515;">"/"</span>);
<span style="color: #008000;">// output = http://www.abc.com/msi

</span><span style="color: #0000ff;">try
</span>{
    <span style="color: #0000ff;">string </span>fileNull = <span style="color: #0000ff;">null</span>;
    output = System.IO.<span style="color: #2b91af;">Path</span>.Combine(pathWithoutEndingSlash, fileNull).Replace(<span style="color: #a31515;">"\\"</span>, <span style="color: #a31515;">"/"</span>);
}
<span style="color: #0000ff;">catch
</span>{
    <span style="color: #008000;">// Throws exception as would same statement without the .Replace()
</span>}</pre>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:22530cba-3aee-4e2b-b395-0410434873e4" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px"><a href="http://www.dotnetkicks.com/kick/?url=http://johnnycoder.com/blog/2008/06/08/pathcombine-for-urls/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/06/08/pathcombine-for-urls/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
<p><a href="http://11011.net/software/vspaste"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/06/08/pathcombine-for-urls/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>It&#8217;s 4pm. Your Access is Denied.</title>
		<link>http://johnnycoder.com/blog/2008/01/08/its-4pm-your-access-is-denied/</link>
		<comments>http://johnnycoder.com/blog/2008/01/08/its-4pm-your-access-is-denied/#comments</comments>
		<pubDate>Wed, 09 Jan 2008 01:42:49 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Humor]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/01/08/its-4pm-your-access-is-denied/</guid>
		<description><![CDATA[The following defect was logged yesterday: Each day at 4pm PST our users are denied seamless access into [third party website]. Though I am sure the author of the code may be of another opinion, aren&#8217;t these types of defects kind of fun?  They are like brain-teasers which you want to solve without looking at [...]]]></description>
			<content:encoded><![CDATA[<p>The following defect was logged yesterday: <em>Each day at 4pm PST our users are denied seamless access into [third party website].</em></p>
<p>Though I am sure the author of the code may be of another opinion, aren&#8217;t these types of defects kind of fun?  They are like brain-teasers which you want to solve without looking at the answer &#8212; in this case is the code.  As a bonus, you can bring these riddles home and share over dinner with family and friends.  Everyone gets to play along.   </p>
<p>Here&#8217;s the answer:</p>
<pre class="code"><span style="color: #008000;">// Encryption uses GMT time in verifying timestamp.
</span><span style="color: #008080;">DateTime</span>    dtNow      = <span style="color: #008080;">DateTime</span>.Now ;
<span style="color: #0000ff;">string</span>      sMonth     = <span style="color: #800000;">"0"</span> + dtNow.Month.ToString() ;
<span style="color: #0000ff;">string</span>      sDay       = <span style="color: #800000;">"0"</span> + dtNow.Day.ToString() ;
<span style="color: #008000;">// Do not make changes to hour when switching to daylight savings time.
</span><span style="color: #008080;">DateTime</span>    dtUTC      = dtNow.ToUniversalTime();
<span style="color: #0000ff;">string</span>      sHour      = <span style="color: #800000;">"0"</span> + (dtUTC.Hour).ToString() ;
<span style="color: #0000ff;">string</span>      sMinute    = <span style="color: #800000;">"0"</span> + dtNow.Minute.ToString() ;
<span style="color: #0000ff;">string</span>      sSecond    = <span style="color: #800000;">"0"</span> + dtNow.Second.ToString() ;

<span style="color: #008000;">// timestamp t, in format "yyyymmddhhmmss"
</span><span style="color: #0000ff;">string</span> sTimeStamp = dtNow.Year.ToString() +
    sMonth.Substring( ( ( sMonth.Length == 2 ) ? 0 : 1 ) , 2 ) +
    sDay.Substring( ( ( sDay.Length == 2 ) ? 0 : 1 ) , 2 ) +
    sHour.Substring( ( ( sHour.Length == 2 ) ? 0 : 1 ) , 2 ) +
    sMinute.Substring( ( ( sMinute.Length == 2 ) ? 0 : 1 ) , 2 ) +
    sSecond.Substring( ( ( sSecond.Length == 2 ) ? 0 : 1 ) , 2 ) ;</pre>
<p><a href="http://11011.net/software/vspaste"></a>Neat formatting routine, eh?<a href="http://11011.net/software/vspaste"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/01/08/its-4pm-your-access-is-denied/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Undo Functionality with a Limited Stack</title>
		<link>http://johnnycoder.com/blog/2008/01/07/undo-functionality-with-a-limited-stack/</link>
		<comments>http://johnnycoder.com/blog/2008/01/07/undo-functionality-with-a-limited-stack/#comments</comments>
		<pubDate>Tue, 08 Jan 2008 02:00:32 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Library]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/01/07/undo-functionality-with-a-limited-stack/</guid>
		<description><![CDATA[After hours of discussions and documentation, we had a good understanding of the functional requirements.  The ask was for a very complex, intelligent and &#8220;AJAXy&#8221; web application which would give financial advisors the ability to rebalance their clients&#8217; portfolios based on a specified investment objective.  Everyone was excited (especially me) until the final requirement was [...]]]></description>
			<content:encoded><![CDATA[<p>After hours of discussions and documentation, we had a good understanding of the functional requirements.  The ask was for a very complex, intelligent and &#8220;AJAXy&#8221; web application which would give financial advisors the ability to rebalance their clients&#8217; portfolios based on a specified investment objective.  Everyone was excited (especially me) until the final requirement was issued: &#8220;We would like the ability to undo actions.&#8221;</p>
<p>The request was reasonable.  If I were an advisor I would wish for this feature as well, but this was a web application with literally dozens of ways to extend, manipulate and delete data. I had concerns but I agree to evaluate and potentially prototype.  Before the meeting closed I was able to set the expectation that we would most likely need to limit the number of undos &#8212; after all we weren&#8217;t dealing with a web application with unlimited resources.</p>
<p>As it turned out, the implementation worked itself out nicely.  Rather than &#8220;logging&#8221; each action, I opted to store the state of the data AFTER each action.  For example, instead of being concerned about how a security was added to the client&#8217;s portfolio, I started caring only about the resulting new data item.  As form changes were made, I pushed a copy of the new state onto a &#8220;LimitedStack.&#8221;  When the undo action was triggered, I would then pop the previous state off the stack and update the form accordingly.  Finally, as the stack approach the maximum number of undos, the item in the first position would be removed in order to make room for the new item being push into the last position. </p>
<p>At the moment, we are allowing for up to 6 undos.  Each undo is being managed within the LimitedStack in Session State.  I am concerned that we are effectively using ~6 times more memory to accommodate this requirement, but I&#8217;m hopeful that performance testing will ease my worries. </p>
<p>I&#8217;ve include the LimitedStack logic below.  You will see it is using the LinkedList&lt;T&gt; as its base.</p>
<p>I also found the copying of the state (which was a collections of nested objec references) to be an interesting problem which needed solving.  I hope to comment about deep copying soon.</p>
<pre class="code">[<span style="color: #008080;">Serializable</span>()]
<span style="color: #0000ff;">public</span> <span style="color: #0000ff;">class</span> <span style="color: #008080;">LimitedStack</span>&lt;T&gt; : <span style="color: #008080;">LinkedList</span>&lt;T&gt;
{
    <span style="color: #0000ff;">private</span> <span style="color: #0000ff;">int</span> _maxItems;

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">int</span> MaxItems
    {
        <span style="color: #0000ff;">get</span> { <span style="color: #0000ff;">return</span> _maxItems; }
        <span style="color: #0000ff;">set
</span>        {
            <span style="color: #0000ff;">while</span> (<span style="color: #0000ff;">this</span>.Count &gt; <span style="color: #0000ff;">value</span>)
            {
                <span style="color: #0000ff;">this</span>.RemoveFirst();
            }
            _maxItems = <span style="color: #0000ff;">value</span>;
        }
    }

    <span style="color: #0000ff;">public</span> LimitedStack(<span style="color: #0000ff;">int</span> num)
    {
        _maxItems = num;
    }

    <span style="color: #0000ff;">public</span> T Peek()
    {
        <span style="color: #0000ff;">return</span> <span style="color: #0000ff;">this</span>.Last.Value;
    }

    <span style="color: #0000ff;">public</span> T Pop()
    {
        <span style="color: #008080;">LinkedListNode</span>&lt;T&gt; node = <span style="color: #0000ff;">this</span>.Last;
        <span style="color: #0000ff;">this</span>.RemoveLast();
        <span style="color: #0000ff;">return</span> node.Value;
    }

    <span style="color: #0000ff;">public</span> <span style="color: #0000ff;">void</span> Push(T value)
    {
        <span style="color: #008080;">LinkedListNode</span>&lt;T&gt; node = <span style="color: #0000ff;">new</span> <span style="color: #008080;">LinkedListNode</span>&lt;T&gt;(value);
        <span style="color: #0000ff;">this</span>.AddLast(node);

        <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">this</span>.Count &gt; _maxItems)
        {
            <span style="color: #0000ff;">this</span>.RemoveFirst();
        }
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/01/07/undo-functionality-with-a-limited-stack/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>C# Brain Scratcher of the Day</title>
		<link>http://johnnycoder.com/blog/2007/09/07/brain-scratcher-of-the-day/</link>
		<comments>http://johnnycoder.com/blog/2007/09/07/brain-scratcher-of-the-day/#comments</comments>
		<pubDate>Fri, 07 Sep 2007 17:06:56 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[Brain Scratcher]]></category>
		<category><![CDATA[C#]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2007/09/07/brain-scratcher-of-the-day/</guid>
		<description><![CDATA[We ran into the following issue two days ago.  In a nutshell, the &#8220;initialCategory&#8221; was not being selected in the Categories dropdown by default.  Yes, I recognize that the code itself may be written in fewer lines, but please only focus on the differences between the two code snippets below.  I haven&#8217;t had the time to [...]]]></description>
			<content:encoded><![CDATA[<p>We ran into the following issue two days ago.  In a nutshell, the &#8220;initialCategory&#8221; was not being selected in the Categories dropdown by default.  Yes, I recognize that the code itself may be written in fewer lines, but please only focus on the differences between the two code snippets below.  I haven&#8217;t had the time to research, but this code has been rolling around in my head ever since a developer presented the &#8220;fix&#8221; to me yesterday morning.  As far as I can tell, only syntax has changed.  I would expected the code to work in both case, to be honest, but the &#8220;before&#8221; code didn&#8217;t function correctly with our last release.</p>
<p>Any thoughts?</p>
<p> </p>
<p><span style="text-decoration: underline;">Before</span></p>
<pre class="code"><span style="color: #0000ff;">for</span>(<span style="color: #0000ff;">int</span> i=0;i&lt;cboCategories.Items.Count;i++)
{
    <span style="color: #0000ff;">if</span>(initialCategory != <span style="color: #0000ff;">string</span>.Empty)
    {
        <span style="color: #0000ff;">if</span>(cboCategories.Items[i].Value.ToLower()==initialCategory.ToLower())
        {
            cboCategories.Items[i].Selected=<span style="color: #0000ff;">true</span>;
            <span style="color: #0000ff;">break</span>;
        }
    }
    <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span>(cboCategories.Items[i].Value==all)
    {
        cboCategories.Items[i].Selected=<span style="color: #0000ff;">true</span>;
        <span style="color: #0000ff;">break</span>;
    }
}</pre>
<p><span style="text-decoration: underline;">After</span></p>
<p><span style="color: #0000ff;">for</span>(<span style="color: #0000ff;">int</span> i=0;i&lt;cboCategories.Items.Count;i++)<br />
{<br />
    <span style="color: #0000ff;">if</span>(initialCategory != <span style="color: #0000ff;">string</span>.Empty)<br />
    {<br />
        <span style="color: #0000ff;">if</span>(cboCategories.Items[i].Value.ToLower()==initialCategory.ToLower())<br />
        {<br />
            <span style="color: #008000;">//cboCategories.Items[i].Selected=true;<br />
</span>            cboCategories.SelectedIndex = i;<br />
            <span style="color: #0000ff;">break</span>;<br />
        }<br />
    }<br />
    <span style="color: #0000ff;">else</span> <span style="color: #0000ff;">if</span>(cboCategories.Items[i].Value==all)<br />
    {<br />
        <span style="color: #008000;">//cboCategories.Items[i].Selected=true;<br />
</span>        cboCategories.SelectedIndex = i;<br />
        <span style="color: #0000ff;">break</span>;<br />
    }<br />
}</p>
<p><a href="http://11011.net/software/vspaste"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2007/09/07/brain-scratcher-of-the-day/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
	</channel>
</rss>

