<?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; Samples</title>
	<atom:link href="http://johnnycoder.com/blog/category/samples/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>Render MVCContrib Grid with No Header Row</title>
		<link>http://johnnycoder.com/blog/2010/06/12/render-mvccontrib-grid-with-no-header-row/</link>
		<comments>http://johnnycoder.com/blog/2010/06/12/render-mvccontrib-grid-with-no-header-row/#comments</comments>
		<pubDate>Sat, 12 Jun 2010 22:33:39 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[ASP.NET MVC]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2010/06/12/render-mvccontrib-grid-with-no-header-row/</guid>
		<description><![CDATA[The MVCContrib Grid allows for the easy construction of HTML tables for displaying data from a collection of Model objects. I add this component to all of my ASP.NET MVC projects.&#160; If you aren’t familiar with what the grid has to offer, it’s worth the looking into. What you may notice in the busy example [...]]]></description>
			<content:encoded><![CDATA[<p>The <a href="http://mvccontrib.codeplex.com/wikipage?title=Grid">MVCContrib Grid</a> allows for the easy construction of HTML tables for displaying data from a collection of Model objects. I add this component to all of my ASP.NET MVC projects.&#160; If you aren’t familiar with what the grid has to offer, it’s worth the looking into.</p>
<p>What you may notice in the busy example below is the fact that I render my column headers independent of the grid contents.&#160; This allows me to keep my headers fixed while the user searches through the table content which is displayed in a scrollable div*.&#160; Thus, I needed a way to render my grid without headers. That’s where <a href="http://www.jeremyskinner.co.uk/2009/02/23/rewriting-the-mvccontrib-grid-part-3-gridmodels-and-gridrenderers">Grid Renderers</a> come into play.&#160; </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:712c4c20-0671-40cb-a3e8-1e5a1e0c5dc0" 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">&lt;</span><span style="color:#800000">table</span> <span style="color:#ff0000">border</span><span style="color:#0000ff">=&quot;0&quot;</span> <span style="color:#ff0000">cellspacing</span><span style="color:#0000ff">=&quot;0&quot;</span> <span style="color:#ff0000">cellpadding</span><span style="color:#0000ff">=&quot;0&quot;</span> <span style="color:#ff0000">class</span><span style="color:#0000ff">=&quot;projectHeaderTable&quot;&gt;</span></li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#0000ff">&lt;</span><span style="color:#800000">tr</span><span style="color:#0000ff">&gt;</span></li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">&lt;</span><span style="color:#800000">td</span> <span style="color:#ff0000">class</span><span style="color:#0000ff">=&quot;memberTableMemberHeader&quot;&gt;</span></li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="background:#ffff00">&lt;%</span><span style="color:#0000ff">=</span> Html.GridColumnHeader(<span style="color:#a31515">&quot;Member&quot;</span>, <span style="color:#a31515">&quot;Index&quot;</span>, <span style="color:#a31515">&quot;MemberFullName&quot;</span>)<span style="background:#ffff00">%&gt;</span>&#160;&#160;&#160;&#160;&#160;</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">&lt;/</span><span style="color:#800000">td</span><span style="color:#0000ff">&gt;</span></li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">&lt;</span><span style="color:#800000">td</span> <span style="color:#ff0000">class</span><span style="color:#0000ff">=&quot;memberTableRoleHeader&quot;&gt;</span></li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="background:#ffff00">&lt;%</span><span style="color:#0000ff">=</span> Html.GridColumnHeader(<span style="color:#a31515">&quot;Role&quot;</span>, <span style="color:#a31515">&quot;Index&quot;</span>, <span style="color:#a31515">&quot;ProjectRoleTypeName&quot;</span>)<span style="background:#ffff00">%&gt;</span>&#160;&#160;&#160;&#160;&#160;</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">&lt;/</span><span style="color:#800000">td</span><span style="color:#0000ff">&gt;</span>&#160;&#160;&#160;&#160;&#160;&#160;&#160;</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">&lt;</span><span style="color:#800000">td</span> <span style="color:#ff0000">class</span><span style="color:#0000ff">=&quot;memberTableActionHeader&quot;&gt;</span></li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Action</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">&lt;/</span><span style="color:#800000">td</span><span style="color:#0000ff">&gt;</span></li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#0000ff">&lt;/</span><span style="color:#800000">tr</span><span style="color:#0000ff">&gt;</span></li>
<li><span style="color:#0000ff">&lt;/</span><span style="color:#800000">table</span><span style="color:#0000ff">&gt;</span></li>
<li style="background: #f3f3f3"><span style="color:#0000ff">&lt;</span><span style="color:#800000">div</span> <span style="color:#ff0000">class</span><span style="color:#0000ff">=&quot;scrollContentWrapper&quot;&gt;</span></li>
<li><span style="background:#ffff00">&lt;%</span> Html.Grid(Model)</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;.Columns(column =&gt;</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;{</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;column.For(c =&gt; c.MemberFullName).Attributes(@class =&gt; <span style="color:#a31515">&quot;memberTableMemberCol&quot;</span>);</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;column.For(c =&gt; c.ProjectRoleTypeName).Attributes(@class =&gt; <span style="color:#a31515">&quot;memberTableRoleCol&quot;</span>);</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;column.For(x =&gt; Html.ActionLink(<span style="color:#a31515">&quot;View&quot;</span>, <span style="color:#a31515">&quot;Details&quot;</span>, <span style="color:#0000ff">new</span> { Id = x.ProjectMemberId }) + <span style="color:#a31515">&quot; | &quot;</span> +</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Html.ActionLink(<span style="color:#a31515">&quot;Edit&quot;</span>, <span style="color:#a31515">&quot;Edit&quot;</span>, <span style="color:#0000ff">new</span> { Id = x.ProjectMemberId }) + <span style="color:#a31515">&quot; | &quot;</span> +</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;Html.ActionLink(<span style="color:#a31515">&quot;Remove&quot;</span>, <span style="color:#a31515">&quot;Delete&quot;</span>, <span style="color:#0000ff">new</span> { Id = x.ProjectMemberId }))</li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;.Attributes(@class =&gt; <span style="color:#a31515">&quot;memberTableActionCol&quot;</span>).DoNotEncode();</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;})</li>
<li>&#160;&#160;&#160;&#160;.Empty(<span style="color:#a31515">&quot;There are no members associated with this project.&quot;</span>)</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;.Attributes(@class =&gt; <span style="color:#a31515">&quot;lbContent&quot;</span>)</li>
<li>&#160;&#160;&#160;&#160;.RenderUsing(<span style="color:#0000ff">new</span> <span style="color:#2b91af">GridNoHeaderRenderer</span>&lt;<span style="color:#2b91af">ProjectMemberDetailsViewModel</span>&gt;())</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;.Render();</li>
<li><span style="background:#ffff00">%&gt;</span></li>
<li style="background: #f3f3f3"><span style="color:#0000ff">&lt;/</span><span style="color:#800000">div</span><span style="color:#0000ff">&gt;</span></li>
<li><span style="color:#0000ff">&lt;</span><span style="color:#800000">div</span> <span style="color:#ff0000">class</span><span style="color:#0000ff">=&quot;scrollContentBottom&quot;&gt;</span></li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#006400">&lt;!&#8211; &#8211;&gt;</span></li>
<li><span style="color:#0000ff">&lt;/</span><span style="color:#800000">div</span><span style="color:#0000ff">&gt;</span></li>
<li style="background: #f3f3f3"><span style="background:#ffff00">&lt;%</span><span style="color:#0000ff">=</span>Html.Pager(Model) <span style="background:#ffff00">%&gt;</span></li>
</ol></div>
</p></div>
</p></div>
<p>Maybe you noticed the reference to the GridNoHeaderRenderer class above?&#160; Yep, rendering the grid with no header is straightforward.&#160;&#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:668ec790-d5ef-42f7-ba69-b25460f917e5" 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">public</span> <span style="color:#0000ff">class</span> <span style="color:#2b91af">GridNoHeaderRenderer</span>&lt;T&gt; : </li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#2b91af">HtmlTableGridRenderer</span>&lt;T&gt; <span style="color:#0000ff">where</span> T: <span style="color:#0000ff">class</span></li>
<li>{</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;<span style="color:#0000ff">protected</span> <span style="color:#0000ff">override</span> <span style="color:#0000ff">bool</span> RenderHeader()</li>
<li>&#160;&#160;&#160;&#160;{</li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#008000">// Explicitly returning true would suppress the header</span></li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#008000">// just fine, however, Render() will always assume that</span></li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#008000">// items exist in collection and RenderEmpty() will </span></li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#008000">// never be called.&#160;&#160;</span></li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#008000">// In other words, return ShouldRenderHeader() if you </span></li>
<li>&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#008000">// want to maintain the Empty text when no items exist.</span></li>
<li style="background: #f3f3f3">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;<span style="color:#0000ff">return</span> ShouldRenderHeader();</li>
<li>&#160;&#160;&#160;&#160;}</li>
<li style="background: #f3f3f3">}</li>
</ol></div>
</p></div>
</p></div>
<p>Well, if you read through the comments, there is one catch.&#160; <a href="http://groups.google.com/group/mvccontrib-discuss/browse_thread/thread/84942c21354820c0">You might be tempted to have the RenderHeader method always return true</a>.&#160; This would work just fine but you should return the result of ShouldRenderHeader() instead so the Empty text will continue to display if there are no items in the collection.</p>
<p>The GridRenderer feature found in the MVCContrib Grid is so well put together, I just had to share.&#160; </p>
<p>* <em>Though you can find countless alternatives to the fixed headers problem online, this is the only solution that I’ve ever found to reliably work across browsers. If you know something I don’t, please share.</em></p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2010/06/12/render-mvccontrib-grid-with-no-header-row/feed/</wfw:commentRss>
		<slash:comments>4</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>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>ClickOnce Getting Started Sample</title>
		<link>http://johnnycoder.com/blog/2009/02/18/clickonce-getting-started-sample/</link>
		<comments>http://johnnycoder.com/blog/2009/02/18/clickonce-getting-started-sample/#comments</comments>
		<pubDate>Wed, 18 Feb 2009 23:35:56 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[ClickOnce]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[Visual Studio]]></category>
		<category><![CDATA[WPF]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2009/02/18/clickonce-getting-started-sample/</guid>
		<description><![CDATA[ClickOnce is pretty simple to get going once you know where to click (no pun intended.)&#160; Here&#8217;s a down and dirty, quick start guide on how to implement ClickOnce in your application: First, create a sample application in Visual Studio.&#160; The attached sample is a WPF application using VS 2008.&#160; ClickOnce configuration is managed through [...]]]></description>
			<content:encoded><![CDATA[</p>
<p><a href="http://msdn.microsoft.com/en-us/netframework/aa497348.aspx">ClickOnce</a> is pretty simple to get going once you know where to click (no pun intended.)&#160; Here&#8217;s a down and dirty, quick start guide on how to implement ClickOnce in your application:</p>
<p>First, create a sample application in Visual Studio.&#160; The attached sample is a WPF application using VS 2008.&#160; ClickOnce configuration is managed through the project property pages so right-click on the project and click properties (or type ALT+ENTER) to access the properties pages.</p>
<p> <a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image2.png">
<p><em></em></p>
<p> </a><a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image4.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; margin: 10px 10px 10px 0px; border-right-width: 0px" height="195" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image-thumb1.png" width="244" align="left" border="0" /></a></a></a>
<p>Under the <strong>Signing Tab</strong>, Select <em>Sign the ClickOnce manifest.</em><em>&#160; </em>When you first publish, a temporary key (named [APPNAME]_TemporyKey.pfk) will be created and added to your the project.&#160; Additionally, the temporary certificate information will be generated and displayed in the Certificate textarea.<a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image5.png"><img title="image" style="border-top-width: 0px; display: inline; border-left-width: 0px; border-bottom-width: 0px; margin: 10px 0px 10px 10px; border-right-width: 0px" height="195" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image-thumb2.png" width="244" align="right" border="0" /></a>     </p>
<p>Under the <strong>Security Tab</strong>, Select <em>Enable ClickOnce Security Settings.&#160; </em>Also select <em>This is a full trust application.</em>&#160; If you wish to go with the partial trust option, I would recommend configuring your permissions per the <em>Calculate Permissions</em> option.&#160; </p>
<p>Note, an empty WPF application (single XML windows with no logic) must be run as a full trust application according to the <em>Calculate </em><a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image6.png"><em><img title="image" style="border-right: 0px; border-top: 0px; display: inline; margin: 10px 10px 10px 0px; border-left: 0px; border-bottom: 0px" height="164" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image-thumb3.png" width="244" align="left" border="0" /></em></a><em>Permissions</em> analyzer.&#160; A similar Windows Application (single form with no logic,) in comparison, can be run with partial trust.&#160; <br />&#160; <br />Under the <strong>Publish Tab</strong>, enter a <em>Publish Location</em>.&#160; You may, for example, provide a locally hosted website.&#160; If the website doesn’t exist, it will be created – assuming appropriate permissions are granted to the logged in user.&#160; Be sure to select <em><strong><em><a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image18.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; margin: 10px 0px 10px 10px; border-left: 0px; border-bottom: 0px" height="206" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image18-thumb.png" width="244" align="right" border="0" /></a></em></strong></em><em>The application is available offline</em> as well.&#160; </p>
<p>Open the <em><strong>Updates…</strong></em> dialogue. Check <em>The application should check for updates</em>.&#160; Keep the default which states the application will check for updates before it starts.&#160; Click OK. </p>
<p>Open the <em><strong>Options…</strong></em> dialogue. Under <strong>Description</strong>, provide a Publisher and Product name.&#160; Under <strong>Deployment</strong>, provide a <a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image21.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; margin: 10px 10px 10px 0px; border-left: 0px; border-bottom: 0px" height="142" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image21-thumb.png" width="244" align="left" border="0" /></a>Deployment web page.&#160; I recommend “Publish.htm” and check Automatically generate deployment web page after publish.&#160; Under <strong>Manifests</strong>, you may wish to select Create desktop shortcut. Click OK. </p>
<p>Your basic ClickOnce configuration is now in place and it is time to test.&#160; Compile and publish the application.&#160; Publishing many be done through the Publishing Tab’s <em>Publishing Wizard</em>, or via the <em>Publishing </em><a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image61.png"><em><img title="image" style="border-right: 0px; border-top: 0px; display: inline; margin: 10px 10px 10px 0px; border-left: 0px; border-bottom: 0px" height="218" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image6-thumb.png" width="244" align="left" border="0" /></em></a><em>Now</em> option.&#160; Alternatively, you may use the Publish option under the Build Menu.&#160; </p>
<p>The Publish action will copy your compiled application to the publish location and render publish.htm page in your default browser.&#160; Notice the application name, version and publisher is displayed along with an Install link.&#160; <a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image31.png"><img title="image" style="border-right: 0px; border-top: 0px; display: inline; margin: 10px 0px 5px 10px; border-left: 0px; border-bottom: 0px" height="133" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2009/02/image3-thumb1.png" width="244" align="right" border="0" /></a>Click on the Install link to kick off the download and installation of the application. You will be potentially be prompted with a security warning along with the request to install.&#160; Continue with the installation.&#160; Once complete, the application will launch automatically.&#160; The application may be launched via the application shortcuts going forward.&#160; </p>
<p>That’s it. The downloadable sample application doesn&#8217;t do much of anything. It merely demonstrates the installation of a WPF application using ClickOnce technology.&#160; You may uninstall as you would any traditional application.&#160; </p>
<div class="wlWriterEditableSmartContent" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:a7e34ae0-07d1-486b-a3c9-606f82927f3f" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div>Download Sample ClickOnce WPF Project:<a href="http://johnnycoder.com/blog/wp-content/uploads/2009/02/clickoncesample.zip" target="_blank">ClickOnceSample.zip</a></div>
</p>
</div>
<p>References:</p>
<ul>
<li>&#160;<a href="http://www.dnrtv.com/default.aspx?showNum=8">Brian Noyes on publishing Smart Client Applications with ClickOnce Technology</a> </li>
</ul>
<p>See ClickOnce In Action:</p>
<ul>
<li><a href="http://code.google.com/p/wittytwitter/">Witty Twitter Project</a> </li>
<li><a href="http://www.hanselman.com/babysmash/download.htm">BabySmash</a> </li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2009/02/18/clickonce-getting-started-sample/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Caching with C#, AOP and PostSharp</title>
		<link>http://johnnycoder.com/blog/2009/01/16/caching-with-c-aop-and-postsharp/</link>
		<comments>http://johnnycoder.com/blog/2009/01/16/caching-with-c-aop-and-postsharp/#comments</comments>
		<pubDate>Sat, 17 Jan 2009 01:53:57 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[AOP]]></category>
		<category><![CDATA[ASP.NET]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[Tools]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2009/01/16/caching-with-c-aop-and-postsharp/</guid>
		<description><![CDATA[I&#8217;ve been spending lots of time getting my head around Aspect-Oriented Programming (AOP). At its foundation, AOP separates crosscutting concerns (concerns which are not localizable and cannot be implemented successfully using pure imperative or object-oriented programming) into loosely coupled, modularized units called aspects and injects them into the otherwise one-dimensional base program.&#160; Without AOP, we [...]]]></description>
			<content:encoded><![CDATA[<p>I&#8217;ve been spending lots of time getting my head around <a href="http://en.wikipedia.org/wiki/Aspect-oriented_software_development">Aspect-Oriented Programming (AOP)</a>. At its foundation, AOP separates crosscutting concerns (concerns which are not localizable and cannot be implemented successfully using pure imperative or object-oriented programming) into loosely coupled, modularized units called aspects and injects them into the otherwise one-dimensional base program.&nbsp; Without AOP, we end up with a system with tangled and scattered code which is harder to design, understand, implement, and evolve primarily due to poor traceability, lower productively, less code reuse and testing difficulties. With AOP, well, my head started to hurt&#8230;until I put an ended to my research and put AOP to practice.<a href="http://johnnycoder.com/blog/wp-content/uploads/2009/01/image4.png"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; margin: 0px 0px 0px 20px; border-right-width: 0px" height="59" alt="image" src="http://johnnycoder.com/blog/wp-content/uploads/2009/01/image-thumb4.png" width="244" align="right" border="0"></a></p>
<p>I know it&#8217;s a bit of a tease, but I&#8217;m going to save my &#8220;What is OAP&#8221; post for another day.&nbsp; Right now, I&#8217;m going to show you some code.</p>
<p><a href="http://www.postsharp.org/">Postsharp</a> is an open source library which encapsulate aspects as custom attributes and adds new behaviors to your code through policy injection (which is just another name for AOP.)&nbsp; </p>
<h3>Smelly, Old Code</h3>
<p>The follow code serves as an example of a crosscutting concern (Cache) which needs to be separated from the base program and modularized into an aspect.&nbsp; Notice the offending code checks the cache and queries the database.&nbsp; It laughs in the face of the <a href="http://en.wikipedia.org/wiki/Single_responsibility_principle">Single Responsibility Principle</a>. </p>
<p><a href="http://11011.net/software/vspaste"></a>
<pre class="code"><span style="color: blue">private const string </span>KeyNumber = <span style="color: #a31515">"RandomNumber"</span>;</pre>
<p><a href="http://11011.net/software/vspaste"></a>
<pre class="code"><span style="color: blue">private int </span>GetNumber()
{
    <span style="color: blue">int </span>value;
    <span style="color: blue">if </span>(!<span style="color: #2b91af">CacheHelper</span>.Get(KeyNumber, <span style="color: blue">out </span>value))
    {
        value = <span style="color: #2b91af">DataAccess</span>.GetNumberRandom();
        <span style="color: #2b91af">CacheHelper</span>.Add(value, KeyNumber);
    }

    <span style="color: blue">return </span>value;
}
</pre>
<h3>Shiny, Happy Code</h3>
<p>Using PostSharp, GetNumber() is left to do one thing (query the database) and all the caching checks are handled by the aspect, the custom CacheAttribute.&nbsp; Notice this is all hooked up by decorating GetNumber() with the CacheAttribute tag which accepts the key in the constructor.</p>
<pre class="code"><span style="color: blue">private const string </span>KeyNumber = <span style="color: #a31515">"RandomNumber"</span>;</pre>
<p><a href="http://11011.net/software/vspaste"></a>
<pre class="code"><span style="color: green">// Pass the key associated with the cached item in the constructor
</span>[<span style="color: #2b91af">Cache</span>(KeyNumber)]
<span style="color: blue">private int </span>GetNumber()
{
    <span style="color: green">// This logic is only executed if the CacheAttribute calls upon it.
    </span><span style="color: blue">return </span><span style="color: #2b91af">DataAccess</span>.GetNumberRandom();
}
</pre>
<p>The attribute&#8217;s logic is basic but very powerful.&nbsp; When the GetNumber (or any other method which is decorated with the CacheAttribute)&nbsp; is invoked, CacheAttribute checks to see if the data is in cache using the provided key.&nbsp; If so, the data is extracted and returned. Period. The GetNumber method is completely bypassed and never executed.&nbsp; In the sample application, I added some logging to help clarify this point.&nbsp; However, if the data is not found in cache, the custom attribute invokes the caller, the GetNumber() method, stores the result in cache and then returns the value.&nbsp; In this case, GetNumber&#8217;s logic is executed but it is invoke via the CacheAttribute.&nbsp; </p>
<pre class="code"><span style="color: blue">using </span>System;
<span style="color: blue">using </span>PostSharp.Laos;

<span style="color: blue">namespace </span>PostSharpWebApplicationCache
{
    [<span style="color: #2b91af">Serializable</span>]
    <span style="color: blue">public sealed class </span><span style="color: #2b91af">CacheAttribute </span>: <span style="color: #2b91af">OnMethodInvocationAspect
    </span>{
        <span style="color: blue">private readonly string </span>key;

        <span style="color: blue">public </span>CacheAttribute(<span style="color: blue">string </span>key)
        {
            <span style="color: blue">this</span>.key = key;
        }

        <span style="color: blue">public override void </span>OnInvocation(<span style="color: #2b91af">MethodInvocationEventArgs </span>context)
        {
            <span style="color: blue">object </span>value;

            <span style="color: blue">if </span>(!<span style="color: #2b91af">CacheHelper</span>.Get(key, <span style="color: blue">out </span>value))
            {
                <span style="color: green">// Do lookup based on caller's logic.
                </span>value = context.Delegate.DynamicInvoke();
                <span style="color: #2b91af">CacheHelper</span>.Add(value, key);
            }

            context.ReturnValue = value;
        }
    }
}</pre>
<p>As you can see, both the smelly, old code and the shiny, happy code achieve the same effect, but the latter option is a lot cleaner and more elegant if you ask me. </p>
<p>As noted, I&#8217;ve included some downloaded code if you want to play around with Postsharp and AOP on your own.&nbsp; To get the code to work, you&#8217;ll need to visit the Postsharp site and install the latest bits.&nbsp; In my case, I&#8217;m using <a href="http://www.postsharp.org/all-downloads">PostSharp 1.0</a>.&nbsp; Please don&#8217;t be fooled.&nbsp; You&#8217;ll need to use an ASP.NET Web Application Project rather than ASP.NET Web Site in order for PostSharp to work.&nbsp; This is because <a href="http://www.postsharp.org/aop-net/compiletime-weaving">Postsharp does compile-time weaving and cleverly mucks with your IL</a>. Details.&nbsp; Don&#8217;t worry. we&#8217;ll get into all of it.&nbsp; For now, just trust me and know the sample project is a Web Application Project.&nbsp; Enjoy.</p>
<p>&nbsp;</p>
<p><div class="wlWriterSmartContent" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:cfd03151-35d3-43e7-8514-5b92457308e1" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div>Download Sample PostSharp Web Project: <a href="http://johnnycoder.com/blog/wp-content/uploads/2009/01/postsharpwebapplicationcache.zip" target="_blank">PostSharpWebApplicationCache.zip</a></div>
</p>
</div>
<div class="wlWriterSmartContent" id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:00b2eb1d-aa20-416d-b5d8-48d6d0b7a945" 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/16/caching-with-c-aop-and-postsharp/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2009/01/16/caching-with-c-aop-and-postsharp/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2009/01/16/caching-with-c-aop-and-postsharp/feed/</wfw:commentRss>
		<slash:comments>14</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>Insert File Plugin</title>
		<link>http://johnnycoder.com/blog/2008/12/11/insert-file-plugin/</link>
		<comments>http://johnnycoder.com/blog/2008/12/11/insert-file-plugin/#comments</comments>
		<pubDate>Thu, 11 Dec 2008 16:45:54 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[Plugins]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[Tools]]></category>
		<category><![CDATA[WordPress]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/12/11/insert-file-plugin/</guid>
		<description><![CDATA[I&#8217;m thinking it&#8217;s about time I start providing downloadable sample code along with my posts.&#160; Rather than copying and pasting code snippets into your own solution, it might be nice to alternatively download a compressed sample project.&#160; The Insert File Plugin for Windows Live Writer has been around for a while.&#160; Here&#8217;s my attempt at [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://gallery.live.com/liveItemDetail.aspx?li=6c4619fa-6865-4632-9b48-0f4390a512b8&amp;bt=9&amp;pl=8"><img style="margin: 10px" alt="Insert File Plugin" src="http://download.gallery.start.com/d.dll/1~14~573~32202/LARGE.jpg" align="right"></a>I&#8217;m thinking it&#8217;s about time I start providing downloadable sample code along with my posts.&nbsp; Rather than copying and pasting code snippets into your own solution, it might be nice to alternatively download a compressed sample project.&nbsp; </p>
<p>The <a href="http://gallery.live.com/liveItemDetail.aspx?li=6c4619fa-6865-4632-9b48-0f4390a512b8&amp;bt=9&amp;pl=8">Insert File Plugin</a> for Windows Live Writer has been around for a while.&nbsp; Here&#8217;s my attempt at trying it out.&nbsp; It&#8217;s documented to be tested with WordPress.&nbsp; Wish me luck&#8230;&nbsp; </p>
<div class="wlWriterSmartContent" id="scid:8eb9d37f-1541-4f29-b6f4-1eea890d4876:c36a1284-9068-40f7-a9f2-c8da0bd77a18" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div>Download Compressed Insert File Plugin Sample Project: <a href="http://johnnycoder.com/blog/wp-content/uploads/2008/12/insertfileplugintest2.zip" target="_blank">InsertFilePluginTest.zip</a></div>
</p>
</div>
<p>Update: It worked like a charm.&nbsp; I wonder if it will still work with a post update from WLW?</p>
<p>Update: Yes, it does.&nbsp; <img src='http://johnnycoder.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/12/11/insert-file-plugin/feed/</wfw:commentRss>
		<slash:comments>0</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>TSQL &#8211; Self Update</title>
		<link>http://johnnycoder.com/blog/2008/07/25/tsql-self-update/</link>
		<comments>http://johnnycoder.com/blog/2008/07/25/tsql-self-update/#comments</comments>
		<pubDate>Fri, 25 Jul 2008 15:55:10 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[Samples]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2008/07/25/tsql-self-update/</guid>
		<description><![CDATA[This morning I needed to compose a very simple SQL routine and it took me around five compiles until I got the syntax right.  All I needed to do was transfer an active status from one entity (in my case a computer) to another.  I decided to implement this by updating the same table in [...]]]></description>
			<content:encoded><![CDATA[<p>This morning I needed to compose a very simple SQL routine and it took me around five compiles until I got the syntax right.  All I needed to do was transfer an active status from one entity (in my case a computer) to another.  I decided to implement this by updating the same table in which I was selecting.  I think the syntax associated with &#8220;self update&#8221; type queries is tricky so this post is so I personally don&#8217;t lose this code snippet and future cycles.  I hope it might help you as well.</p>
<p>This example transfers the status of the source computer to the destination computer.  Nothing fancy&#8230;</p>
<pre class="code"><span style="color: #0000ff;">DECLARE </span>@SourceID <span style="color: #0000ff;">INT</span><span style="color: #808080;">; </span><span style="color: #0000ff;">SET </span>@SourceID <span style="color: #808080;">= </span>2
<span style="color: #0000ff;">DECLARE </span>@DestinationID <span style="color: #0000ff;">INT</span><span style="color: #808080;">; </span><span style="color: #0000ff;">SET </span>@DestinationID <span style="color: #808080;">= </span>1

<span style="color: #0000ff;">DECLARE </span>@Computer <span style="color: #0000ff;">TABLE </span><span style="color: #808080;">(</span>ComputerID <span style="color: #0000ff;">INT</span><span style="color: #808080;">, </span>StatusID <span style="color: #0000ff;">INT</span><span style="color: #808080;">)

</span><span style="color: #0000ff;">INSERT INTO </span>@Computer<span style="color: #808080;">(</span>ComputerID<span style="color: #808080;">, </span>StatusID<span style="color: #808080;">)
</span><span style="color: #0000ff;">SELECT </span>@DestinationID<span style="color: #808080;">, </span>1 <span style="color: #0000ff;">UNION SELECT </span>@SourceID<span style="color: #808080;">, </span>2

<span style="color: #0000ff;">SELECT </span><span style="color: #808080;">* </span><span style="color: #0000ff;">FROM </span>@Computer

<span style="color: #0000ff;">UPDATE </span>A
<span style="color: #0000ff;">SET </span>A<span style="color: #808080;">.</span>StatusID <span style="color: #808080;">= </span>B<span style="color: #808080;">.</span>StatusID
<span style="color: #0000ff;">FROM </span>@Computer A<span style="color: #808080;">, </span>@Computer B
<span style="color: #0000ff;">WHERE </span>B<span style="color: #808080;">.</span>ComputerID <span style="color: #808080;">= </span>@SourceID
<span style="color: #808080;">AND </span>A<span style="color: #808080;">.</span>ComputerID <span style="color: #808080;">= </span>@DestinationID

<span style="color: #0000ff;">SELECT </span><span style="color: #808080;">* </span><span style="color: #0000ff;">FROM </span>@Computer</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code">(2 row(s) affected)
ComputerID  StatusID
----------- -----------
1           1
2           2

(2 row(s) affected)

(1 row(s) affected)

ComputerID  StatusID
----------- -----------
1           2
2           2

(2 row(s) affected)</pre>
<p> </p>
<div id="scid:C16BAC14-9A3D-4c50-9394-FBFEF7A93539:c9b74d3c-3b98-49e0-b2c5-9a9102aa744a" 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/tsql-self-update/"><img src="http://www.dotnetkicks.com/Services/Images/KickItImageGenerator.ashx?url=http://johnnycoder.com/blog/2008/07/25/tsql-self-update/" border="0" alt="kick it on DotNetKicks.com" /></a></div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2008/07/25/tsql-self-update/feed/</wfw:commentRss>
		<slash:comments>4</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>Doing Your Dirty Work</title>
		<link>http://johnnycoder.com/blog/2007/08/27/doing-your-dirty-work/</link>
		<comments>http://johnnycoder.com/blog/2007/08/27/doing-your-dirty-work/#comments</comments>
		<pubDate>Mon, 27 Aug 2007 15:45:20 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Humor]]></category>
		<category><![CDATA[Samples]]></category>
		<category><![CDATA[Team]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2007/08/27/doing-your-dirty-work/</guid>
		<description><![CDATA[My current focus is on stabilizing about a dozen applications which I recently inherited.  By &#8220;stabilizing&#8221; I mean I am in the process of cleaning up, documenting and fixing somebody else&#8217;s code. These applications have been in existence for years. They were first coded in Classic ASP, then rewritten in .NET 1.1 and finally ported over to [...]]]></description>
			<content:encoded><![CDATA[<p>My current focus is on stabilizing about a dozen applications which I recently inherited.  By &#8220;stabilizing&#8221; I mean I am in the process of cleaning up, documenting and fixing somebody else&#8217;s code.</p>
<p>These applications have been in existence for years. They were first coded in Classic ASP, then rewritten in .NET 1.1 and finally ported over to 2.0.  A review of source control history shows these applications were designed, written, loved, patched, hacked, semi-maintained, rewritten, loathed and abandoned (repeat) by dozens of developers with various coding styles and, I suspect, varying levels of sanity. </p>
<p>If you are the typically developer, you want to work on the latest and greatest new development and you don&#8217;t want someone else&#8217;s crumby code thrown onto your plate.  You, frankly, believe you have better things to do and you squirm at the mere thought of &#8220;production support.&#8221; </p>
<p>But if you <em>are </em>me, you first squirm and then you get over it knowing it can&#8217;t be that bad&#8230;and then you crack open the code and quickly consider stabbing yourself in both eyes just to lessen the pain.  If you <em>are</em> me, you are relieved in the fact that the application merely fails to connect to SQL rather than seeing what the code would do if it had a chance to execute.  If you <em>are </em>me, you resolve one defect just to uncover two more and you seriously wonder why you are being punished as thoughts of <a href="http://en.wikipedia.org/wiki/Sisyphus">Sisyphus</a> run through your head.</p>
<p>But sometimes we have to suck it up and we have to do this unpleasant work.  When you find yourself in my shoes, try to find the good in it.  Acknowledge the fact that this is about as close to instant gratification with little risk as one can get in software development.  Appreciate the fact that the damage has already been done (the code is already broken or really ugly) and you can only make things better (most likely very quickly too.)  Know that there is a lot to be learned in observing what earlier developers did right, but also realize there is so much to learn from what other have done wrong.  Finally, by all means, do everything you can to make things easier for the poor schmuck who will be cleaning up after you someday&#8230;</p>
<p>In the spirit of this post, here&#8217;s my most recent fix.  What&#8217;s wrong with the following code?  Please assume the AppActiveFlag column is a tinyint with a value of 0,1 or null:</p>
<pre class="code"><span style="color: #0000ff;">bool</span> isAppActive = <span style="color: #0000ff;">false</span>;   

System.Data.SqlClient.<span style="color: #008080;">SqlDataReader</span> dbReader = dbCommand.ExecuteReader();
<span style="color: #0000ff;">if</span> (dbReader.Read())
{
    <span style="color: #0000ff;">object</span> o = dbReader[<span style="color: #800000;">"AppActiveFlag"</span>];
    <span style="color: #0000ff;">if</span> (<span style="color: #0000ff;">null</span> == o)
    {
        isAppActive = <span style="color: #0000ff;">false</span>;
    }
    <span style="color: #0000ff;">else
</span>    {
        isAppActive = <span style="color: #008080;">Convert</span>.ToBoolean(<span style="color: #008080;">Convert</span>.ToInt32(o.ToString()));
    }
}</pre>
<pre class="code"> </pre>
<p>If it helps, here&#8217;s the refactored logic:</p>
<p><a href="http://11011.net/software/vspaste"></a></p>
<pre class="code"><span style="color: #0000ff;">bool</span> isAppActive = <span style="color: #0000ff;">false</span>;   

System.Data.SqlClient.<span style="color: #008080;">SqlDataReader</span> dbReader = dbCommand.ExecuteReader();
<span style="color: #0000ff;">if</span> (dbReader.Read())
{
    <span style="color: #0000ff;">if</span> (!dbReader.IsDBNull(dbReader.GetOrdinal(<span style="color: #800000;">"AppActiveFlag"</span>)))
    {
        isAppActive =
<span style="color: #008080;">Convert</span>.ToBoolean(dbReader.GetByte(dbReader.GetOrdinal(<span style="color: #800000;">"AppActiveFlag"</span>)));
    }
}</pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2007/08/27/doing-your-dirty-work/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>DBTalk &#8211; Stuff vs Replace</title>
		<link>http://johnnycoder.com/blog/2007/08/08/dbtalk-stuff-vs-replace/</link>
		<comments>http://johnnycoder.com/blog/2007/08/08/dbtalk-stuff-vs-replace/#comments</comments>
		<pubDate>Wed, 08 Aug 2007 09:10:22 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[Samples]]></category>
		<category><![CDATA[TSQL]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2007/08/08/dbtalk-stuff-vs-replace/</guid>
		<description><![CDATA[Why would you use &#8220;Stuff&#8221; instead of &#8220;Replace?&#8221; Good question.  Both perform a similar function &#8211; replace a string with another string (or no string at all), but Replace has a simpler syntax. The Replace function looks like this: select replace('abcdef','bc','xx') result: axxdef No locations to find, just replace the string.  However, what if we had [...]]]></description>
			<content:encoded><![CDATA[<p>Why would you use &#8220;Stuff&#8221; instead of &#8220;Replace?&#8221;</p>
<p>Good question.  Both perform a similar function &#8211; replace a string with another string (or no string at all), but Replace has a simpler syntax.</p>
<p>The Replace function looks like this:</p>
<pre class="code"><span style="color: #0000ff;">select</span> <span style="color: #ff00ff;">replace</span><span style="color: #808080;">(</span><span style="color: #ff0000;">'abcdef'</span><span style="color: #808080;">,</span><span style="color: #ff0000;">'bc'</span><span style="color: #808080;">,</span><span style="color: #ff0000;">'xx'</span><span style="color: #808080;">)</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>result: axxdef</p>
<p>No locations to find, just replace the string.  However, what if we had a string with two occurrences of the string, like:</p>
<pre class="code"><span style="color: #0000ff;">select</span> <span style="color: #ff00ff;">replace</span><span style="color: #808080;">(</span><span style="color: #ff0000;">'abcabcabc'</span><span style="color: #808080;">,</span><span style="color: #ff0000;">'abc'</span><span style="color: #808080;">,</span><span style="color: #ff0000;">'123'</span><span style="color: #808080;">)</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>result: 123123123</p>
<p>If we only wanted to replace the first one, Replace wouldn&#8217;t work, since it always replaces ALL occurrences of the string. But Stuff would, since it only replaces the string it finds at the starting location we tell it for the number of chars we want it to replace. </p>
<pre class="code"><span style="color: #0000ff;">select</span> <span style="color: #ff00ff;">stuff</span><span style="color: #808080;">(</span><span style="color: #ff0000;">'abcabcabc'</span><span style="color: #808080;">,</span>4<span style="color: #808080;">,</span> 3<span style="color: #808080;">,</span><span style="color: #ff0000;">'123'</span><span style="color: #808080;">)</span></pre>
<p><a href="http://11011.net/software/vspaste"></a></p>
<p>result: abc123abc</p>
<p>Since I tend to prefer explicit control of strings (to reduce the possibility of unintended substitutions), I will usually grab Stuff rather than Replace.  The overhead is probably slightly less for Stuff since the function already knows where to look for the value, but I don&#8217;t consider that a deal breaker.</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2007/08/08/dbtalk-stuff-vs-replace/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

