<?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; Code Library</title>
	<atom:link href="http://johnnycoder.com/blog/category/code-library/feed/" rel="self" type="application/rss+xml" />
	<link>http://johnnycoder.com/blog</link>
	<description></description>
	<lastBuildDate>Tue, 10 Apr 2012 00:14:39 +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>.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>53</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>3</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>28</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>19</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>What&#8217;s the Best Way to Manage a Database Queue?</title>
		<link>http://johnnycoder.com/blog/2007/06/20/whats-the-best-way-to-manage-a-database-queue/</link>
		<comments>http://johnnycoder.com/blog/2007/06/20/whats-the-best-way-to-manage-a-database-queue/#comments</comments>
		<pubDate>Thu, 21 Jun 2007 03:09:17 +0000</pubDate>
		<dc:creator>Ben Griswold</dc:creator>
				<category><![CDATA[C#]]></category>
		<category><![CDATA[Code Library]]></category>
		<category><![CDATA[SQL Server]]></category>
		<category><![CDATA[Samples]]></category>

		<guid isPermaLink="false">http://johnnycoder.com/blog/2007/06/20/whats-the-best-way-to-manage-a-database-queue/</guid>
		<description><![CDATA[This question circulates through the office about once a year.  &#8220;Um, I have Windows service which processes requests which are queued in a database table.  Everything is working great, but I would like to add a second instance of the service and I need to know the best way to ensure the services don&#8217;t step [...]]]></description>
			<content:encoded><![CDATA[<p>This question circulates through the office about once a year.  &#8220;Um, I have Windows service which processes requests which are queued in a database table.  Everything is working great, but I would like to add a second instance of the service and I need to know the best way to ensure the services don&#8217;t step on each other.  In other words, how do I mark each row as it is being processed so it won&#8217;t be picked up again?&#8221; </p>
<p>Here are the ingredients in my current ideal solution:</p>
<ol>
<li>The table must include the following columns: a Unique Identifier such as RequestID, Status, LockedBy, and LockedTime.  I also like to include RequestedTime and CompletionTime columns as I&#8217;ve found that capturing these values help when/if system stats are required.</li>
<li>The key is to lock the current request at the time of processing.  To do so, you should use a transaction and an update lock.</li>
<li>I think it is important to pull requests off the queue in an intelligent order.  FIFO is the best bet under most circumstances.  In this case, the RequestedTime column becomes imperative (unless your RequestID is an auto-incrementing identity column and you are comfortable ordering on it.)</li>
<li>Finally, I like to make sure no request is left behind.  Let&#8217;s say Service A locks a request for processing and then the application server crashes.  I want the lock to eventually expire so Service B can pick up the row and save the day.</li>
</ol>
<p>Assuming new requests are added to the queue as &#8216;Pending&#8217; , one may use a routine similar to the one below to safely pull the next request off the queue:</p>
<pre class="code"><span style="color: #0000ff;">create</span> <span style="color: #0000ff;">procedure</span> [GetNextItemInQueue]
<span style="color: #808080;">(
</span>    @LockedBy varchar<span style="color: #808080;">(</span>75<span style="color: #808080;">)
)
</span><span style="color: #0000ff;">as 

set</span> nocount <span style="color: #0000ff;">on 

declare</span>
    @Error                     <span style="color: #0000ff;">int</span><span style="color: #808080;">,
</span>    @ExitCode                  <span style="color: #0000ff;">int</span><span style="color: #808080;">,
</span>    @RowCount                  <span style="color: #0000ff;">int</span><span style="color: #808080;">,
</span>    @PendingStatus               <span style="color: #0000ff;">int</span><span style="color: #808080;">,
</span>    @MinutesBeforeBreakLock       <span style="color: #0000ff;">int</span><span style="color: #808080;">,
</span>    @RequestId                   <span style="color: #0000ff;">int
</span>
<span style="color: #0000ff;">select</span>
    @Error                      <span style="color: #808080;">=</span> 0<span style="color: #808080;">,
</span>    @ExitCode                   <span style="color: #808080;">=</span> 0<span style="color: #808080;">,
</span>    @RowCount                   <span style="color: #808080;">=</span> 0<span style="color: #808080;">,
</span>    @PendingStatus                <span style="color: #808080;">=</span> 1<span style="color: #808080;">,
</span>    @MinutesBeforeBreakLock        <span style="color: #808080;">=</span> 30 

<span style="color: #0000ff;">begin</span> <span style="color: #0000ff;">tran</span> ProcessQueue 

<span style="color: #0000ff;">select</span> <span style="color: #0000ff;">top</span> 1 @RequestId <span style="color: #808080;">=</span> RequestId
<span style="color: #0000ff;">from</span> Queue <span style="color: #0000ff;">with</span> <span style="color: #808080;">(</span>updlock<span style="color: #808080;">)
</span><span style="color: #0000ff;">where</span> Status <span style="color: #808080;">=</span> @PendingStatus
<span style="color: #808080;">and</span> <span style="color: #808080;">(</span>LockedTime <span style="color: #808080;">IS</span> <span style="color: #808080;">NULL</span> <span style="color: #808080;">OR</span>
<span style="color: #ff00ff;">DateDiff</span><span style="color: #808080;">(</span>mi<span style="color: #808080;">,</span> LockedTime<span style="color: #808080;">,</span> <span style="color: #ff00ff;">GetDate</span><span style="color: #808080;">())</span> <span style="color: #808080;">&gt;=</span> @MinutesBeforeBreakLock<span style="color: #808080;">)
</span><span style="color: #0000ff;">order</span> <span style="color: #0000ff;">by</span> RequestedTime <span style="color: #0000ff;">Asc 

select</span> @RowCount <span style="color: #808080;">=</span> <span style="color: #ff00ff;">@@RowCount</span><span style="color: #808080;">,</span> @Error <span style="color: #808080;">=</span> <span style="color: #ff00ff;">@@Error 

</span><span style="color: #0000ff;">if</span> <span style="color: #808080;">(</span>@RowCount <span style="color: #808080;">=</span> 0<span style="color: #808080;">)
</span>    <span style="color: #0000ff;">goto</span> ExitProc 

<span style="color: #0000ff;">if</span> <span style="color: #808080;">(</span>@Error <span style="color: #808080;">&lt;&gt;</span> 0<span style="color: #808080;">)
</span>    <span style="color: #0000ff;">goto</span> ErrorHandler 

<span style="color: #0000ff;">update</span> Queue
<span style="color: #0000ff;">set</span>    LockedBy <span style="color: #808080;">=</span> @LockedBy<span style="color: #808080;">,</span>
    LockedTime <span style="color: #808080;">=</span> <span style="color: #ff00ff;">GetDate</span><span style="color: #808080;">()
</span><span style="color: #0000ff;">where</span> RequestId <span style="color: #808080;">=</span> @RequestId 

<span style="color: #0000ff;">select</span> @Error <span style="color: #808080;">=</span> <span style="color: #ff00ff;">@@Error
</span><span style="color: #0000ff;">if</span> <span style="color: #808080;">(</span>@Error <span style="color: #808080;">&lt;&gt;</span> 0<span style="color: #808080;">)
</span>    <span style="color: #0000ff;">goto</span> ErrorHandler 

<span style="color: #0000ff;">select</span> @RequestId <span style="color: #0000ff;">as</span> RequestId 

<span style="color: #0000ff;">select</span> @Error <span style="color: #808080;">=</span> <span style="color: #ff00ff;">@@Error
</span><span style="color: #0000ff;">if</span> <span style="color: #808080;">(</span>@Error <span style="color: #808080;">&lt;&gt;</span> 0<span style="color: #808080;">)
</span>    <span style="color: #0000ff;">goto</span> ErrorHandler 

<span style="color: #0000ff;">goto</span> ExitProc 

ErrorHandler<span style="color: #808080;">:
</span>    <span style="color: #0000ff;">raiserror</span>   <span style="color: #808080;">(</span>@Error<span style="color: #808080;">,</span> 16<span style="color: #808080;">,</span> 1<span style="color: #808080;">)
</span>    <span style="color: #0000ff;">if</span> <span style="color: #ff00ff;">@@trancount</span> <span style="color: #808080;">&gt;</span> 0
        <span style="color: #0000ff;">rollback</span> <span style="color: #0000ff;">tran</span> ProcessQueue
    <span style="color: #0000ff;">select</span>      @ExitCode <span style="color: #808080;">=</span>  <span style="color: #808080;">-</span>100 

ExitProc<span style="color: #808080;">:
</span>    <span style="color: #0000ff;">commit</span> <span style="color: #0000ff;">tran</span> ProcessQueue
    <span style="color: #0000ff;">return</span>      <span style="color: #808080;">(</span>@ExitCode<span style="color: #808080;">)</span></pre>
<p>Once the request is processed, a database call will be made to update the row&#8217;s Status to &#8216;Complete&#8217; and CompletionTime. </p>
<p>Note, you may choose to change the status of each row from &#8216;Pending&#8217; to &#8216;Processing&#8217; when you do the initial lock.  This is perfectly fine, but I&#8217;ve found that is unnecessary as the Processing status can be determined based on the value of other columns.</p>
<p>Again, that&#8217;s my current preferred implementation.  Perhaps there are better solutions out there?</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2007/06/20/whats-the-best-way-to-manage-a-database-queue/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>DataView.RowFilter Top Rows</title>
		<link>http://johnnycoder.com/blog/2007/02/07/dataviewrowfilter-top-rows/</link>
		<comments>http://johnnycoder.com/blog/2007/02/07/dataviewrowfilter-top-rows/#comments</comments>
		<pubDate>Wed, 07 Feb 2007 21:25:35 +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/2007/02/07/dataviewrowfilter-top-rows/</guid>
		<description><![CDATA[Out of the box, you can do a lot with the DataView.RowFilter property, but you can&#8217;t make use of the top clause. However, if the view contains a column with unique values, you can obtain the same results by setting the Sort property and then generating a RowFilter which uses the in condition. Here&#8217;s a [...]]]></description>
			<content:encoded><![CDATA[<p>Out of the box, you can do a lot with the DataView.RowFilter property, but you can&#8217;t make use of the <em>top</em> clause. However, if the view contains a column with unique values, you can obtain the same results by setting the Sort property and then generating a RowFilter which uses the <em>in</em> condition.</p>
<p>Here&#8217;s a sample:</p>
<div id="57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:a03c9230-f22a-4bd3-9800-0a14fd1b865b" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div><!--  Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/  --><span style="color: #0000ff;">public</span><span style="color: #000000;"> </span><span style="color: #0000ff;">static</span><span style="color: #000000;"> DataView GetLatestComments(</span><span style="color: #0000ff;">int</span><span style="color: #000000;"> numComments) { DataView Comments </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000ff;">new</span><span style="color: #000000;"> DataView(GetComments()); Comments.Sort </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #000000;">&#8220;</span><span style="color: #000000;">DateCreated Desc</span><span style="color: #000000;">&#8220;</span><span style="color: #000000;">; </span><span style="color: #0000ff;">string</span><span style="color: #000000;"> filter </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000ff;">string</span><span style="color: #000000;">.Empty; </span><span style="color: #0000ff;">string</span><span style="color: #000000;"> delimiter </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000ff;">string</span><span style="color: #000000;">.Empty; numComments </span><span style="color: #000000;">=</span><span style="color: #000000;"> Math.Min(numComments, Comments.Count); </span><span style="color: #0000ff;">for</span><span style="color: #000000;"> (</span><span style="color: #0000ff;">int</span><span style="color: #000000;"> i </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #000000;">0</span><span style="color: #000000;">; i </span><span style="color: #000000;">&lt;</span><span style="color: #000000;"> numComments; i</span><span style="color: #000000;">++</span><span style="color: #000000;">) { filter </span><span style="color: #000000;">+=</span><span style="color: #000000;"> delimiter </span><span style="color: #000000;">+</span><span style="color: #000000;"> Comments[i][</span><span style="color: #000000;">"</span><span style="color: #000000;">Id</span><span style="color: #000000;">"</span><span style="color: #000000;">].ToString(); delimiter </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #000000;">&#8220;</span><span style="color: #000000;">,</span><span style="color: #000000;">&#8220;</span><span style="color: #000000;">; } </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (filter.Length </span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> </span><span style="color: #000000;">0</span><span style="color: #000000;">) { Comments.RowFilter </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #000000;">&#8220;</span><span style="color: #000000;">Id in (</span><span style="color: #000000;">&#8220;</span><span style="color: #000000;"> </span><span style="color: #000000;">+</span><span style="color: #000000;"> filter </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #000000;">&#8220;</span><span style="color: #000000;">)</span><span style="color: #000000;">&#8220;</span><span style="color: #000000;">; } </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> Comments; }</span></div>
</div>
<p>Note how the delimited string is built.  Phil Haack provided an interesting tip on <a href="http://haacked.com/archive/2006/11/21/Tip_Jar_Concatenating_A_Delimited_String.aspx">concatenating a delimited string</a> last year.  Undoubtedly, we&#8217;ve all built delimited strings using our preferred method.  If you sift through the post comments, you will see what I mean.  Anyhow, I took a liking to the method <a href="http://jcheng.wordpress.com/">Joe Cheng</a> uses when he says he&#8217;s &#8220;feeling lazy and performance is not critical (which is the <em>vast</em> majority of the time).&#8221;</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2007/02/07/dataviewrowfilter-top-rows/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
		</item>
		<item>
		<title>C# RoundToInterval()</title>
		<link>http://johnnycoder.com/blog/2007/01/22/roundtointerval/</link>
		<comments>http://johnnycoder.com/blog/2007/01/22/roundtointerval/#comments</comments>
		<pubDate>Tue, 23 Jan 2007 01:28:58 +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/2007/01/22/roundtointerval/</guid>
		<description><![CDATA[Disclaimer: If I were a betting man, I would bet there&#8217;s some code which does the following kicking around a forum, blog or two already.  Simply, I wasn&#8217;t lucky enough to find it.  Hence, the IF in &#8220;if I were a betting man.&#8221; I ran into a case today where I wanted to reduce unused [...]]]></description>
			<content:encoded><![CDATA[<p>Disclaimer: If I were a betting man, I would bet there&#8217;s some code which does the following kicking around a forum, blog or two already.  Simply, I wasn&#8217;t lucky enough to find it.  Hence, the IF in &#8220;if I were a betting man.&#8221;</p>
<p>I ran into a case today where I wanted to reduce unused space in a generated chart.  I figured I could tighten up the chart if the minimum and maximum Y values were slightly beyond the min and max data point values.  For example, if the largest value in my dataset is 14, I would make the maximum value, and the corresponding Y axis label, 16. </p>
<p>This fixed the real estate issue, but I didn&#8217;t like the my labels were now somewhat random and no longer looked clean.  For example, 14.64 + 2 = ugly. To get around this, I opted to pad the values to the nearest interval of 5 and helps with perceived consistency.</p>
<p><strong>Original Chart</strong></p>
<p><a href="http://johnnycoder.com/blog/wp-content/uploads/2007/01/WindowsLiveWriter/Math.Round_99F2/before_thumb7%5B2%5D.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" src="http://johnnycoder.com/blog/wp-content/uploads/2007/01/WindowsLiveWriter/Math.Round_99F2/before_thumb7%5B1%5D.png" border="0" alt="" width="300" height="145" /></a></p>
<p><strong><br />
RoundToInterval() Function</strong></p>
<p>Note the IntervalRounding enum below.  I consider it similar to Math.Round&#8217;s MidpointRounding enumeration where you can use MidPointRounding.ToEven to round a positive value to the nearest even number and MidPointRounding.AwayFromZero to round a value to the nearest number away from zero.  </p>
<div id="57F11A72-B0E5-49c7-9094-E3A15BD5B5E6:1d07782e-eb1a-4e5d-992a-41e60a806b07" class="wlWriterSmartContent" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">
<div><!--  Code highlighting produced by Actipro CodeHighlighter (freeware) http://www.CodeHighlighter.com/  --><span style="color: #008000;">//</span><span style="color: #008000;"> Sample call: Rounds 17 to 20.</span><span style="color: #008000;"> </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;"> d </span><span style="color: #000000;">=</span><span style="color: #000000;"> RoundToInterval(17M, 5M, IntervalRounding.Up); </span><span style="color: #0000ff;">private</span><span style="color: #000000;"> </span><span style="color: #0000ff;">static</span><span style="color: #000000;"> </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;"> RoundToInterval(</span><span style="color: #0000ff;">decimal</span><span style="color: #000000;"> value, </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;"> interval, IntervalRounding rounding) { </span><span style="color: #008000;">//</span><span style="color: #008000;"> Guard against the divide by zero exception</span><span style="color: #008000;"> </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (interval </span><span style="color: #000000;">==</span><span style="color: #000000;"> </span><span style="color: #000000;">0</span><span style="color: #000000;">) </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;">.MinValue; </span><span style="color: #008000;">//</span><span style="color: #008000;"> For example, round 18 to the nearest interval of 5 </span><span style="color: #008000;">//</span><span style="color: #008000;"> Quotient = 3.6, Remainder = 0.6, Whole = 3</span><span style="color: #008000;"> </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;"> quotient </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;">.Divide(value, interval); </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;"> remainder </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;">.Subtract(quotient, </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;">.Floor(quotient)); </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;"> whole </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #0000ff;">decimal</span><span style="color: #000000;">.Subtract(quotient, remainder); </span><span style="color: #008000;">//</span><span style="color: #008000;"> Rounding to the nearest interval and remainder </span><span style="color: #008000;">//</span><span style="color: #008000;"> is over half way to the next interval value</span><span style="color: #008000;"> </span><span style="color: #0000ff;">if</span><span style="color: #000000;"> (rounding </span><span style="color: #000000;">==</span><span style="color: #000000;"> IntervalRounding.Nearest </span><span style="color: #000000;">&amp;&amp;</span><span style="color: #000000;"> remainder </span><span style="color: #000000;">&gt;=</span><span style="color: #000000;"> .5M </span><span style="color: #000000;">||</span><span style="color: #000000;"> </span><span style="color: #008000;">//</span><span style="color: #008000;"> Or we force rounding to the next highest interval </span><span style="color: #008000;">//</span><span style="color: #008000;"> and we have a remainder. In otherwords, our value </span><span style="color: #008000;">//</span><span style="color: #008000;"> isn&#8217;t on an interval already</span><span style="color: #008000;"> </span><span style="color: #000000;">rounding </span><span style="color: #000000;">==</span><span style="color: #000000;"> IntervalRounding.Up </span><span style="color: #000000;">&amp;&amp;</span><span style="color: #000000;"> remainder </span><span style="color: #000000;">&gt;</span><span style="color: #000000;"> 0M) { </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> interval </span><span style="color: #000000;">*</span><span style="color: #000000;"> (whole </span><span style="color: #000000;">+</span><span style="color: #000000;"> </span><span style="color: #000000;">1</span><span style="color: #000000;">); } </span><span style="color: #0000ff;">else</span><span style="color: #000000;"> { </span><span style="color: #0000ff;">return</span><span style="color: #000000;"> interval </span><span style="color: #000000;">*</span><span style="color: #000000;"> whole; } } </span><span style="color: #0000ff;">public</span><span style="color: #000000;"> </span><span style="color: #0000ff;">enum</span><span style="color: #000000;"> IntervalRounding { Nearest </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #000000;">0</span><span style="color: #000000;">, Up </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #000000;">1</span><span style="color: #000000;">, Down </span><span style="color: #000000;">=</span><span style="color: #000000;"> </span><span style="color: #000000;">2</span><span style="color: #000000;"> }</span></div>
</div>
<p><strong>Final Chart:</strong></p>
<p>The chart is now using more available space and the Y axis labels are rounded to the provided interval.  </p>
<p><a href="http://johnnycoder.com/blog/wp-content/uploads/2007/01/WindowsLiveWriter/Math.Round_99F2/after_thumb4%5B2%5D.png"><img style="border-right: 0px; border-top: 0px; border-left: 0px; border-bottom: 0px" src="http://johnnycoder.com/blog/wp-content/uploads/2007/01/WindowsLiveWriter/Math.Round_99F2/after_thumb4%5B1%5D.png" border="0" alt="" width="300" height="142" /></a></p>
<p>Sorry for the blurry image.  If you really squint you can read it.  Maybe&#8230;</p>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2007/01/22/roundtointerval/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Secure PDF Display &#8211; A Second Chance</title>
		<link>http://johnnycoder.com/blog/2006/11/13/secure-pdf-display-a-second-chance/</link>
		<comments>http://johnnycoder.com/blog/2006/11/13/secure-pdf-display-a-second-chance/#comments</comments>
		<pubDate>Mon, 13 Nov 2006 09:36: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/2006/11/13/secure-pdf-display-a-second-chance/</guid>
		<description><![CDATA[Recently, we had the opportunity to do some clean up work on a legacy web app.  At the top of our list was to refactor PDF report rendering to the browser.  The typical application use case was as follows: User enters data.   User submits data.  User requests PDF report.   Application queues report.   Application processes report.   Application stores the [...]]]></description>
			<content:encoded><![CDATA[<p>Recently, we had the opportunity to do some clean up work on a legacy web app.  At the top of our list was to refactor PDF report rendering to the browser.  The typical application use case was as follows:</p>
<ol>
<li>User enters data.  </li>
<li>User submits data. </li>
<li>User requests PDF report.  </li>
<li>Application queues report.  </li>
<li>Application processes report.  </li>
<li>Application stores the report on the fileshare.</li>
<li>Application notifies user that report is ready.  </li>
<li>User requests report. </li>
</ol>
<p>There&#8217;s nothing too tricky here, yet we still managed to really botch it up since there were no less than three security issues associated with the process.  First, we saved the PDF using an auto-incremented identifier for a filename.  For example, the 123rd file would be named 123.pdf.  Second, the PDFs were requested directly.  In the case of a request for the 123rd report, https://www.site.com/reports/123.pdf would be displayed in the address bar.  Finally, we didn&#8217;t have any authorization in place so any user could access any report if they were nosy enough and smart enough (and you didn&#8217;t have to be too smart) to crack the code. </p>
<p>We remedied the issue by first encrypting the querystring parameters.  ID 123, in the example above, was being passed around all over the place and we put an end to it.  We also put a layer of abstraction between the PDF request and the PDF display.  This included a single ASPX page and a FileHandler class.  The ASPX validated that the requestor had rights to view the report and then used the FileHandler class to check for the PDF&#8217;s existence and return a binary stream of the URL.  This binary stream, in turn, was written out by the ASPX page for the user.</p>
<p>Here&#8217;s a block of the code from the ASPX page&#8230;</p>
<div class="csharpcode">
<pre><span class="lnum">   1:  </span><span class="kwrd">bool</span> fileFound = FileHandler.FileExists(url);</pre>
<pre><span class="lnum">   2:  </span> </pre>
<pre><span class="lnum">   3:  </span><span class="kwrd">if</span> (fileFound)</pre>
<pre><span class="lnum">   4:  </span>{</pre>
<pre><span class="lnum">   5:  </span>    Response.Clear();</pre>
<pre><span class="lnum">   6:  </span>    Response.ContentType = <span class="str">"application/pdf"</span>;</pre>
<pre><span class="lnum">   7:  </span>    Response.AddHeader(<span class="str">"Content-Disposition"</span>,</pre>
<pre><span class="str">"inline;filename=report.pdf"</span>);</pre>
<pre><span class="lnum">   8:  </span>    Response.BinaryWrite(</pre>
<pre>FileHandler.GetBinaryFileStream(url));</pre>
<pre><span class="lnum">   9:  </span>}</pre>
</div>
<p><!-- .csharpcode, .csharpcode pre { 	font-size: small; 	color: black; 	font-family: consolas, "Courier New", courier, monospace; 	background-color: #ffffff; 	/*white-space: pre;*/ } .csharpcode pre { margin: 0em; } .csharpcode .rem { color: #008000; } .csharpcode .kwrd { color: #0000ff; } .csharpcode .str { color: #006080; } .csharpcode .op { color: #0000c0; } .csharpcode .preproc { color: #cc6633; } .csharpcode .asp { background-color: #ffff00; } .csharpcode .html { color: #800000; } .csharpcode .attr { color: #ff0000; } .csharpcode .alt  { 	background-color: #f4f4f4; 	width: 100%; 	margin: 0em; } .csharpcode .lnum { color: #606060; } --></p>
<p> </p>
<p>As for the FileHandler class, this code worked great, but still have a look at the bold green comment in the FileExists() function above.  This one threw us for a loop when testing.  As you can see, the function leverages the HttpWebRequest and HttpWebResponse objects to evaluate if a page URL exists.  Here&#8217;s the gotcha.  If 123.pdf didn&#8217;t exist, for example, and IIS gracefully handled this by redirecting to a custom 404 error page, the webrequest would be created for the <span style="text-decoration: underline;">existing</span> 404 error page and it would provide a response.  In this case, the FileExists() would return true even though 123.pdf doesn&#8217;t exist!  Basically, custom error handling of PDF files had to be turned off in order for the FileExists() function to operate correctly.</p>
<p>Here&#8217;s the majority of the FileHandler class.  And, man, were we lucky to get a second change to get it in place.</p>
<div class="csharpcode">
<pre><span class="lnum"></span><span class="lnum">   1:  </span><span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="rem">   </span><span class="rem"><span class="lnum">2:  </span><span class="rem">/// The class checks for the existence of files</span></span></pre>
<pre><span class="lnum">   3:  </span><span class="rem">/// and streams them back to the caller</span></pre>
<pre><span class="lnum">   4:  </span><span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">   5:  </span><span class="kwrd">public</span> <span class="kwrd">class</span> FileHandler</pre>
<pre><span class="lnum">   6:  </span>{</pre>
<pre><span class="lnum">   7:  </span>    <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">   8:  </span>    <span class="rem">/// Validates the existence of a file/page by URL</span></pre>
<pre><span class="lnum">   9:  </span>    <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">  10:  </span>    <span class="rem">/// &lt;param name="url"&gt;File or page by URL&lt;/param&gt;</span></pre>
<pre><span class="lnum">  11:  </span>    <span class="rem">/// &lt;returns&gt;True if exists else false&lt;/returns&gt;</span></pre>
<pre><span class="lnum">  12:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">bool</span> FileExists(<span class="kwrd">string</span> url)</pre>
<pre><span class="lnum">  13:  </span>    {</pre>
<pre><span class="lnum">  14:  </span>        <span class="kwrd">bool</span> pageExists = <span class="kwrd">true</span>;</pre>
<pre><span class="lnum">  15:  </span> </pre>
<pre><span class="lnum">  16:  </span>        <span class="kwrd">try</span></pre>
<pre><span class="lnum">  17:  </span>        {</pre>
<pre><span class="lnum">  18:  </span>            <span class="rem">// <strong>Beware - if the site gracefully handles </strong></span></pre>
<pre><span class="rem"><strong>the </strong></span><span class="rem"><strong>missing page through a redirection of a generic 404 error </strong></span></pre>
<pre><span class="rem"><strong>page, </strong></span><span class="rem"><strong>the page is still considered to be found.</strong></span></pre>
<pre><span class="lnum">  20:  </span> </pre>
<pre><span class="lnum">  21:  </span>            <span class="rem">// Request the page or PDF</span></pre>
<pre><span class="lnum">  22:  </span>            System.Net.HttpWebRequest myHttpWebRequest</pre>
<pre>=(System.Net.HttpWebRequest)System.Net.WebRequest.Create(url);</pre>
<pre><span class="lnum">  23:  </span> </pre>
<pre><span class="lnum">  24:  </span>            <span class="rem">// Get the associated response for the </span></pre>
<pre><span class="rem">above request.</span></pre>
<pre><span class="lnum">  25:  </span>            System.Net.HttpWebResponse myHttpWebResponse</pre>
<pre>= (System.Net.HttpWebResponse)myHttpWebRequest.GetResponse();</pre>
<pre><span class="lnum">  26:  </span> </pre>
<pre><span class="lnum">  27:  </span>            <span class="kwrd">if</span> (myHttpWebResponse.StatusCode !=</pre>
<pre>System.Net.HttpStatusCode.OK)</pre>
<pre><span class="lnum">  28:  </span>            {</pre>
<pre><span class="lnum">  29:  </span>                pageExists = <span class="kwrd">false</span>;</pre>
<pre><span class="lnum">  30:  </span>            }</pre>
<pre><span class="lnum">  31:  </span> </pre>
<pre><span class="lnum">  32:  </span>            myHttpWebResponse.Close();</pre>
<pre><span class="lnum">  33:  </span>        }</pre>
<pre><span class="lnum">  34:  </span>        <span class="kwrd">catch</span> (System.Net.WebException e)</pre>
<pre><span class="lnum">  35:  </span>        {</pre>
<pre><span class="lnum">  36:  </span>            <span class="kwrd">if</span> (e.Status ==</pre>
<pre>System.Net.WebExceptionStatus.ProtocolError)</pre>
<pre><span class="lnum">  37:  </span>            {</pre>
<pre><span class="lnum">  39:  </span>                pageExists = <span class="kwrd">false</span>;</pre>
<pre><span class="lnum">  40:  </span>            }</pre>
<pre><span class="lnum">  41:  </span>        }</pre>
<pre><span class="lnum">  42:  </span></pre>
<pre><span class="lnum">  43:  </span>        <span class="kwrd">return</span> pageExists;</pre>
<pre><span class="lnum">  44:  </span>    }</pre>
<pre><span class="lnum">  47:  </span> </pre>
<pre><span class="lnum">  48:  </span>    <span class="rem">/// &lt;summary&gt;</span></pre>
<pre><span class="lnum">  49:  </span>    <span class="rem">/// Streams binary representation of the web </span></pre>
<pre><span class="rem">page / file</span></pre>
<pre><span class="lnum">  50:  </span>    <span class="rem">/// &lt;/summary&gt;</span></pre>
<pre><span class="lnum">  51:  </span>    <span class="rem">/// &lt;param name="url"&gt;File or page by URL&lt;/param&gt;</span></pre>
<pre><span class="lnum">  52:  </span>    <span class="rem">/// &lt;returns&gt;Page binary stream&lt;/returns&gt;</span></pre>
<pre><span class="lnum">  53:  </span>    <span class="kwrd">public</span> <span class="kwrd">static</span> <span class="kwrd">byte</span>[] GetBinaryFileStream(</pre>
<pre><span class="kwrd">string</span> url)</pre>
<pre><span class="lnum">  54:  </span>    {</pre>
<pre><span class="lnum">  55:  </span>        <span class="rem">//string result = string.Empty;</span></pre>
<pre><span class="lnum">  56:  </span>        <span class="kwrd">byte</span>[] data = <span class="kwrd">null</span>;</pre>
<pre><span class="lnum">  57:  </span> </pre>
<pre><span class="lnum">  58:  </span>        <span class="kwrd">try</span></pre>
<pre><span class="lnum">  59:  </span>        {</pre>
<pre><span class="lnum">  60:  </span>            <span class="kwrd">if</span> (FileExists(url))</pre>
<pre><span class="lnum">  61:  </span>            {</pre>
<pre><span class="lnum">  62:  </span>                <span class="rem">// Request the page or PDF</span></pre>
<pre><span class="lnum">  63:  </span>                System.Net.HttpWebRequest</pre>
<pre>myHttpWebRequest = (System.Net.HttpWebRequest)</pre>
<pre>System.Net.WebRequest.Create(url);</pre>
<pre><span class="lnum">  64:  </span> </pre>
<pre><span class="lnum">  65:  </span>                <span class="rem">// Get the associated response for </span></pre>
<pre><span class="rem">the above request.</span></pre>
<pre><span class="lnum">  66:  </span>                System.Net.HttpWebResponse</pre>
<pre>myHttpWebResponse = (System.Net.HttpWebResponse)</pre>
<pre>myHttpWebRequest.GetResponse();</pre>
<pre><span class="lnum">  67:  </span> </pre>
<pre><span class="lnum">  68:  </span>                <span class="rem">// Fill the binary reader</span></pre>
<pre><span class="lnum">  69:  </span>                System.IO.BinaryReader oStream = <span class="kwrd">new</span></pre>
<pre>System.IO.BinaryReader(myHttpWebResponse.GetResponseStream(),</pre>
<pre>System.Text.Encoding.ASCII);</pre>
<pre><span class="lnum">  70:  </span> </pre>
<pre><span class="lnum">  71:  </span>                <span class="rem">// Read the byte array. hack below?</span></pre>
<pre><span class="lnum">  72:  </span>                data = oStream.ReadBytes(100000000);</pre>
<pre><span class="lnum">  73:  </span></pre>
<pre><span class="lnum">  74:  </span>                oStream.Close();</pre>
<pre><span class="lnum">  75:  </span> </pre>
<pre><span class="lnum">  76:  </span>                myHttpWebResponse.Close();</pre>
<pre><span class="lnum">  77:  </span>            }</pre>
<pre><span class="lnum">  78:  </span>        }</pre>
<pre><span class="lnum">  79:  </span>        <span class="kwrd">catch</span></pre>
<pre><span class="lnum">  80:  </span>        {</pre>
<pre><span class="lnum">  81:  </span>            <span class="kwrd">throw</span>;</pre>
<pre><span class="lnum">  82:  </span>        }</pre>
<pre><span class="lnum">  83:  </span> </pre>
<pre><span class="lnum">  84:  </span>        <span class="kwrd">return</span> data;</pre>
<pre><span class="lnum">  85:  </span>    }</pre>
<pre><span class="lnum">  86:  </span>}</pre>
<pre> </pre>
</div>
]]></content:encoded>
			<wfw:commentRss>http://johnnycoder.com/blog/2006/11/13/secure-pdf-display-a-second-chance/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>

