<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom">
    <title>Logos Bible Software Code Blog</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/" />
    
   <id>tag:code.logos.com,2009:/blog/12</id>
    <link rel="service.post" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12" title="Logos Bible Software Code Blog" />
    <updated>2009-11-05T18:24:18Z</updated>
    
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type 4.24-en</generator>
 

<link rel="self" href="http://feeds.feedburner.com/LogosBibleSoftwareCodeBlog" type="application/atom+xml" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><entry>
    <title>How to Crash every WPF application</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/11/how_to_crash_every_wpf_application.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1638" title="How to Crash every WPF application" />
    <id>tag:code.logos.com,2009:/blog//12.1638</id>
    
    <published>2009-11-05T18:24:18Z</published>
    <updated>2009-11-05T18:24:18Z</updated>
    
    <summary>Now that we’ve released Logos 4, our users are really helping us stress-test WPF. (It’s still a little remarkable that after three years, ours is the first (and only!) WPF application installed on many of our users’ systems.) On one...</summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="Debugging" />
    
        <category term="WPF" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>Now that we’ve <a href="http://code.logos.com/blog/2009/11/hiatus.html">released Logos 4</a>, our users are really helping us stress-test WPF. (It’s still a little remarkable that <a href="http://msdn.microsoft.com/en-us/library/aa663364.aspx">after three years</a>, ours is the first (and only!) WPF application installed on many of our users’ systems.)</p>  <p>On one system, the application was crashing at startup, with the following exception:</p>  <pre>System.TypeInitializationException: The type initializer for
  'System.Windows.Media.FontFamily' threw an exception. ---&gt;
  System.ArgumentException: Illegal characters in path. 
    at System.IO.Path.CheckInvalidPathChars(String path) 
    at System.IO.Path.GetFileName(String path) 
    at MS.Internal.FontCache.FontSourceCollection.SetFontSources() 
    at MS.Internal.FontCache.FontSourceCollection.GetEnumerator() 
    at MS.Internal.FontCache.FamilyCollection.BuildFamilyList(List`1&amp; familyList,
      SortedDictionary`2&amp; familyNameList, SortedList`2&amp; frequentStrings) 
    at MS.Internal.FontCache.FamilyCollection.MS.Internal.FontCache.
      IFontCacheElement.AddToCache(CheckedPointer newPointer, ElementCacher cacher) 
    at MS.Internal.FontCache.HashTable.Lookup(IFontCacheElement e, Boolean add) 
    at MS.Internal.FontCache.CacheManager.Lookup(IFontCacheElement e) 
    at System.Windows.Media.FontFamily.PreCreateDefaultFamilyCollection() 
    at System.Windows.Media.FontFamily..cctor()</pre>

<p>We traced this to having an illegal path char in one of the fonts listed in the <tt>HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts</tt> registry key. To reproduce the problem, you can simply edit one of those values on your own machine and add a colon, pipe, or any other illegal path character to one of the values. Now, any WPF application on your system will crash as soon as it attempts to display its first UI.</p>

<p>If the user of your application discovers this issue, the only thing to do is to examine each of the <tt>Fonts</tt> registry values and correct/delete any that contain invalid characters. (Or write a program to do this for you.)</p>

<p>I’ve filed this as <a href="https://connect.microsoft.com/WPF/feedback/ViewFeedback.aspx?FeedbackID=508419&amp;wa=wsignin1.0#details">Connect issue 508419</a>; we’ve also noted that <a title="When WPF applications don&#39;t start (Discipline is Freedom)" href="http://alissonsol.blogspot.com/2009/02/when-wpf-applications-dont-start.html">others have encountered</a> the same problem (and fixed it in a similar way).</p>]]>
        
    </content>
</entry>

<entry>
    <title>Hiatus</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/11/hiatus.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1635" title="Hiatus" />
    <id>tag:code.logos.com,2009:/blog//12.1635</id>
    
    <published>2009-11-03T05:59:28Z</published>
    <updated>2009-11-05T20:44:06Z</updated>
    
    <summary>If you’ve been following the company blog, you’ve probably guessed why this  blog has been quiet for so long. Today (after four years of development, and two months of intense private beta testing) we released Logos Bible Software 4, the...</summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>If you’ve been following the <a title="Logos Bible Software blog" href="http://blog.logos.com">company blog</a>, you’ve probably guessed why this&#160; blog has been quiet for so long. Today (after four years of development, and two months of intense private beta testing) we <a title="Introducing Logos Bible Software 4" href="http://blog.logos.com/archives/2009/11/introducing_logos_bible_software_4.html">released Logos Bible Software 4</a>, the major upgrade to our flagship product. This was a ground-up rewrite in C#, WPF, and .NET 3.5 (as you can probably tell from the topics previously covered here), with a dash of C++/CLI and legacy code.</p>  <p>We got to play with a lot of cool new technology as we developed it (we started developing with VS2008 Beta 2, and upgraded to pre-release versions of WPF along the way) and learnt a lot, which I hope we can turn into some interesting blog topics in the next few months. And now that we’re “done”, we’re looking forward to upgrading to .NET 4.0 and targeting the new features introduced in Windows 7. (And I hope our growing Mac team might chime in with some OS X-specific posts, too.)</p>  <p>Meanwhile, our web team delivered major improvements to the infrastructure behind logos.com (which supports Logos 4), as well as developing the back-end for our <a title="Logos Bible Software for iPhone" href="http://www.logos.com/iphone">iPhone app</a>.</p>  <p>I think this is the part where I mention that <a href="http://www.logos.com/jobs">we’re hiring</a>… if you’re interested in Bible software, iPhone, WPF, web, Mac, or slaving away on a 15-year-old legacy codebase (just kidding!), we’ve got a spot on our growing teams.</p>]]>
        
    </content>
</entry>

<entry>
    <title>"File not found" CryptographicException</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/09/file_not_found_cryptographicexception.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1602" title="&quot;File not found&quot; CryptographicException" />
    <id>tag:code.logos.com,2009:/blog//12.1602</id>
    
    <published>2009-09-12T20:56:17Z</published>
    <updated>2009-09-13T05:17:48Z</updated>
    
    <summary>The Data Protection API (in Windows 2000 or later) provides methods to securely store secret information (e.g., a cached password) on a local computer. Only the logged-in user can decrypt the protected data (if they also have the key that...</summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="C#" />
    
        <category term="Debugging" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>The <a href="http://msdn.microsoft.com/en-us/library/ms995355.aspx">Data Protection API</a> (in Windows 2000 or later) provides methods to securely store secret information (e.g., a cached password) on a local computer. Only the logged-in user can decrypt the protected data (if they also have the key that was used to protect it). In .NET, these APIs are exposed through the <a title="ProtectedData class (MSDN)" href="http://msdn.microsoft.com/en-us/library/system.security.cryptography.protecteddata.aspx">ProtectedData class</a>.</p>  <p>On one of our XP test systems, a call to ProtectedData.Protect unexpectedly failed with a CryptographicException that had a very puzzling exception message:</p>  <pre>System.Security.Cryptography.CryptographicException: The system cannot
    find the file specified. 
  at System.Security.Cryptography.ProtectedData.Protect(Byte[] userData,
    Byte[] optionalEntropy, DataProtectionScope scope)</pre>

<p>There is no information provided on which file is required or why it's missing, or even why protecting data (in memory) requires file system access in the first place. Searching the internet for the error message turned up just a few other programmers who were also experiencing, but no solutions.</p>

<p>Since the ProtectedData class is just a thin wrapper around the Win32 <a href="http://msdn.microsoft.com/en-us/library/aa380261(VS.85).aspx">CryptProtectData</a> function, I searched for the underlying Win32 error code, and found <a href="http://blogs.msdn.com/spatdsg/archive/2006/01/04/509452.aspx">the answer</a>: the crypto methods read the <tt>HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders</tt> registry key; if there are missing values, the methods will fail. (This makes me think that the methods are incorrectly reading the "User Shell Folders" key, instead of calling SHGetFolderPath, as <a title="The long and sad story of the Shell Folders key (The Old New Thing)" href="http://blogs.msdn.com/oldnewthing/archive/2003/11/03/55532.aspx">Raymond recommends</a>, but I haven't been able to test that yet.)</p>]]>
        
    </content>
</entry>

<entry>
    <title>Entity Framework Performance Tip - Be a Minimalist</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/08/entity_framework_performance_tips_-_part_1.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1581" title="Entity Framework Performance Tip - Be a Minimalist" />
    <id>tag:code.logos.com,2009:/blog//12.1581</id>
    
    <published>2009-08-20T03:11:01Z</published>
    <updated>2009-08-20T04:09:40Z</updated>
    
    <summary>Only get the data you need! This not only applies to Entity Framework query performance, but just about every situation were code interacts with data. It is a simple rule to follow, but yet I see it broken all the time. Breaking this rule is one of the top three reasons I've seen for slow Entity Framework query performance.</summary>
    <author>
        <name>Bill Simpkins</name>
        <uri>http://www.logos.com</uri>
    </author>
    
        <category term="C#" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>Only get the data you need! This not only applies to Entity Framework query performance, but just about every situation were code interacts with data. It is a simple rule to follow, but yet I see it broken all the time. Breaking this rule is one of the top three reasons I've seen for slow Entity Framework query performance. I may discuss the other two in later posts ...</p>

<p><strong>Bad</strong></p>

<div style="font-family: Courier New; font-size: 10pt; color: black; background: #eaeaea;">
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;116</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: blue;">string</span>&gt; GetNames()</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;117</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;118</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> dc = <span style="color: blue;">new</span> <span style="color: #2b91af;">MyDataContext</span>())</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;119</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;120</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// This is bad news!</span></p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;121</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// This will return alot of columns</span></p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;122</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">//&nbsp; that won't even be used.</span></p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;123</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> userNames = <span style="color: blue;">from</span> u <span style="color: blue;">in</span> dc.UserSet</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;124</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">select</span> u;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;125</span>&nbsp;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;126</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// SQL Server Profiler will show you that all the</span></p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;127</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">//&nbsp; columns are fetched when you call &quot;ToList()&quot;.</span></p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;128</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> userNames.ToList().Select(u =&gt; u.Name);</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;129</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;130</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>

<p><br />
<strong>Good</strong></p>

<div style="font-family: Courier New; font-size: 10pt; color: black; background: #eaeaea;">
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;116</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">private</span> <span style="color: blue;">static</span> <span style="color: #2b91af;">IEnumerable</span>&lt;<span style="color: blue;">string</span>&gt; GetNames()</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;117</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;118</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">using</span> (<span style="color: blue;">var</span> dc = <span style="color: blue;">new</span> <span style="color: #2b91af;"> MyDataContext </span>())</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;119</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; {</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;120</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// Just get the Name.</span></p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;121</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: green;">// Don't waste database and network resources!</span></p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;122</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">var</span> userNames = <span style="color: blue;">from</span> u <span style="color: blue;">in</span> dc.UserSet</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;123</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">select</span> u.Name;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;124</span>&nbsp;</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;125</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; <span style="color: blue;">return</span> userNames.ToList();</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;126</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
<p style="margin: 0px;"><span style="color: #2b91af;">&nbsp;&nbsp;127</span>&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp; }</p>
</div>]]>
        
    </content>
</entry>

<entry>
    <title>A Few Tips For Taking a SQL Server Database Offline</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/07/taking_a_sql_server_database_offline.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1569" title="A Few Tips For Taking a SQL Server Database Offline" />
    <id>tag:code.logos.com,2009:/blog//12.1569</id>
    
    <published>2009-07-31T00:29:12Z</published>
    <updated>2009-07-31T00:47:10Z</updated>
    
    <summary>In SQL Server Management Studio (SSMS), you can right-click on a database, select "Tasks" and take the database offline. If the database seems to "hang" in the transition for more than a minute after you do this (you may be...</summary>
    <author>
        <name>Bill Simpkins</name>
        <uri>http://www.logos.com</uri>
    </author>
    
        <category term="SQL" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>In SQL Server Management Studio (SSMS), you can right-click on a database, select "Tasks" and take the database offline.</p>

<p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="sqloffline.jpg" src="http://code.logos.com/blog/2009/07/30/sqloffline.jpg" width="274" height="238" class="mt-image-none" style="" /></span></p>

<p>If the database seems to "hang" in the transition for more than a minute after you do this (you may be sweating bullets by this point), try the following two things:</p>

<ol>
	<li>Make sure you are not profiling the database.</li>
        <li>Restart SSMS.</li>
</ol>

<p>These simple things may save you a lot of stress!</p>]]>
        
    </content>
</entry>

<entry>
    <title>Patching a Crash in Kensington MouseWorks</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/06/patching_a_crash_in_kensington_mouseworks.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1550" title="Patching a Crash in Kensington MouseWorks" />
    <id>tag:code.logos.com,2009:/blog//12.1550</id>
    
    <published>2009-06-26T02:45:14Z</published>
    <updated>2009-06-26T02:52:45Z</updated>
    
    <summary>A co-worker had trouble installing the latest version of an application I've been working on. The log file showed that the problem was an access violation when our setup program called MsiInstallProduct. This seemed very unusual, since Windows APIs return...</summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="Debugging" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>A co-worker had trouble installing the latest version of an application I've been working on. The log file showed that the problem was an access violation when our setup program called <a title="MsiInstallProduct Function (MSDN)" href="http://msdn.microsoft.com/en-us/library/aa370315(VS.85).aspx">MsiInstallProduct</a>. This seemed very unusual, since Windows APIs return error codes instead of crashing. I decided to see where the crash was happening by running the installer under <a title="Debugging Tools for Windows" href="http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx">WinDbg</a>.</p>  <p>I set WinDbg to immediately break on exceptions and launched the app. It stopped almost immediately with the following callstack. The crash location is in <tt>kwm_dll.dll</tt>, which is a hook DLL installed by <a href="http://us.kensington.com/html/1466.html#mw622">Kensington MouseWorks</a>.</p>  <pre>kmw_dll!CallWndProcFunc+0xa8
USER32!DispatchHookA+0x101
USER32!fnHkINLPCWPSTRUCTA+0x4f
USER32!__fnDWORD+0x24
ntdll!KiUserCallbackDispatcher+0x13
USER32!NtUserSetFocus+0xc
USER32!CreateDialogIndirectParamAorW+0x33
USER32!CreateDialogParamW+0x49
msi!CBasicUI::CreateProgressDialog+0x35
msi!CBasicUI::CheckDialog+0x47
msi!CBasicUI::SetProgressData+0x58
msi!CBasicUI::Initialize+0x11c
msi!MsiUIMessageContext::Initialize+0x230
msi!MsiUIMessageContext::RunInstall+0x22
msi!RunEngine+0xe0
msi!MsiInstallProductW+0xa1
BatchUpd!Application::RunCommandInstall+0x1f5
BatchUpd!Application::Run+0x11e3
BatchUpd!wWinMain+0x102</pre>

<p>Disassembling the crash location showed the following (crashing code in bold; <code>ebp</code> does not contain a valid address).</p>

<pre>mov     eax,dword ptr [ebp-4]
mov     ecx,dword ptr [eax]
push    ecx
mov     edx,dword ptr [ebp-4]
mov     eax,dword ptr [edx+4]
push    eax
mov     ecx,dword ptr [ebp-4]
mov     edx,dword ptr [ecx+0Ch]
push    edx
call    kmw_dll!CallWndProcFunc+0x12f0 (10004210)
add     esp,0Ch
<b>mov     eax,dword ptr [ebp+10h]</b>
push    eax
mov     ecx,dword ptr [ebp+0Ch]
push    ecx
mov     edx,dword ptr [ebp+8]
push    edx
mov     eax,dword ptr [kmw_dll!ShowOptsProc+0x6b94 (1000e0a4)]
push    eax
call    dword ptr [kmw_dll!ShowOptsProc+0x7c80 (1000f190)]
mov     esp,ebp
pop     ebp
ret     0Ch</pre>

<p>One interesting thing about the code is that it looks like a Debug build (or a Release build with no optimizations): the disassembly is straightforward and seems like it has a one-to-one correspondence with the putative source code. The other thing of note (not shown above) is that the base address of the DLL is set to the default <tt>0x10000000</tt>, which is a poor choice for a hook DLL that will be loaded into every process on the system.</p>

<p><code>ebp</code> should be preserved across the function call, so I looked at the function that was just called (at address 0x10004210). I've added a few explanatory comments based on my understanding of what it's doing. </p>

<pre>push    ebp				; save caller's value of ebp
mov     ebp,esp				; standard function prologue
sub     esp,offset <unloaded_32.dll>+0x87 (00000088)	; BOOL bLocal0; char szLocal1[132];
cmp     dword ptr [ebp+0Ch],0		; if (param2 == 0)
je      kmw_dll!CallWndProcFunc+0x130b (1000422b) ; goto label0;
mov     dword ptr [ebp-88h],0		; bLocal0 = FALSE;
jmp     kmw_dll!CallWndProcFunc+0x1315 (10004235) ; goto label1;
label0:
mov     dword ptr [ebp-88h],offset <unloaded_32.dll> (00000001) ; bLocal0 = TRUE;
label1:
mov     eax,dword ptr [ebp-88h]		; push bLocal0
push    eax
lea     ecx,[ebp-84h]			; push &amp;szLocal1[0]
push    ecx
mov     edx,dword ptr [ebp+10h]		; push param3
push    edx
mov     eax,dword ptr [ebp+8]		; push param1
push    eax
call    kmw_dll!ShowOptsProc+0x16e0 (10008bf0)	; fn(param1, param3, szLocal1, bLocal0)
add     esp,10h				; clean up parameters (C calling convention)
mov     esp,ebp				; &quot;free&quot; locals
pop     ebp				; restore caller's value of ebp
ret                                                                                                  </pre>

<p>This function is allocating 0x88 (i.e., 136) bytes for local variable storage: enough for an int (or BOOL) and a 132 byte buffer. If this buffer were overflowed, the stack would be overwritten and <tt>ebp</tt> would be corrupted upon return. Some internet searching turns up <a title="Click-once application doesn&#39;t start (MSDN Forums)" href="http://social.msdn.microsoft.com/forums/en-US/winformssetup/thread/3ab4fc8f-1212-424f-ac35-ba41be66e1ba/#53032cb5-961a-44d0-8817-18b844b6e0f8">posts</a> that <a title="Conflict Between ClickOnce and Kensington Mouseworks Causes ClickOnce Applications to Crash" href="http://blogs.msdn.com/winformsue/archive/2006/05/22/604103.aspx">discuss</a> a similar issue, stating that "Kensington MouseWorks ... crashes ... if the executable path is longer than 128 characters"; this seems to match our situation. Indeed, dumping the bytes at the old value of <tt>ebp-84h</tt> shows the full path of our setup application, which is too long for the buffer.</p>

<p>Since the buffer is stack allocated, it would be trivial to change its size by editing the instructions that create and reference the local variables. At a minimum, the buffer should be capable of storing <a title="File Names, Paths, and Namespaces -- Maximum Path Length (MSDN)" href="http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx#maximum_path_length"><tt>MAX_PATH</tt></a> characters. Because this function doesn't supply the actual buffer length to the function it calls, we can make it as long as we (reasonably) want. I decided to increase the size for storage of locals in this function to 300 bytes. In version 6.3.2.4 of kmw_dll.dll (which seems like it may be newer than the <a title="Kensington MouseWorks download" href="http://us.kensington.com/html/1466.html#mw622">latest available version</a>, published in February 2006), this can be accomplished by editing the following bytes in the file. These changes simply change the numbers 136, -136, and -132 (which are the three offsets used in the code above) to 300, -300, and -296.</p>

<table>
<tr><td style="padding-right: 32px"><b>Offset</b></td><td><b>New Bytes</b></td></tr>
<tr><td>0x4215</td><td>2C 01</td></tr>
<tr><td>0x4221</td><td>D4 FE</td></tr>
<tr><td>0x422D</td><td>D4 FE</td></tr>
<tr><td>0x4237</td><td>D4 FE</td></tr>
<tr><td>0x423E</td><td>D8 FE</td></tr>
</table>

<p>The buffer should now be large enough to hold a file name up to <tt>MAX_PATH</tt> bytes long. With this new DLL installed in the <tt>C:\Windows\System32</tt> folder, the setup program is able to launch the MSI and installation completes successfully.</p>
<!-- <p>A patched version of kmw_dll.dll that fixes this problem is available <a title="Patched kmw_dll.dll, version 6.3.2.4" href="http://code.logos.com/images/kmw_dll.dll">here</a>. This patch has been applied to version 6.3.2.4. You should not overwrite any other version of the DLL with this patched version, use at your own risk, this could corrupt your system, etc., etc. (Kensington: if you would like me to discontinue distributing this patch, please leave a comment and I will take it down.)</p> -->]]>
        
    </content>
</entry>

<entry>
    <title>Using If-Modified-Since in HTTP Requests</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/06/using_if-modified-since_in_http_requests.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1534" title="Using If-Modified-Since in HTTP Requests" />
    <id>tag:code.logos.com,2009:/blog//12.1534</id>
    
    <published>2009-06-05T18:36:21Z</published>
    <updated>2009-06-05T18:36:21Z</updated>
    
    <summary><![CDATA[Conditionally requesting the download of a web page only if it has been modified after a given time seems like it should be as simple as setting the IfModifiedSince property and making the request: HttpWebRequest request = (HttpWebRequest) WebRequest.Create(@&quot;http://code.logos.com/blog/&quot;); request.IfModifiedSince...]]></summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="C#" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>Conditionally requesting the download of a web page only if it has been modified after a given time seems like it should be as simple as setting the <a title="HttpWebRequest.IfModifiedSince Property (MSDN)" href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.ifmodifiedsince.aspx">IfModifiedSince</a> property and making the request:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <div style="font-family: verdana; background: white; color: black; font-size: 8pt">     <p style="margin: 0px"><span style="color: #2b91af">HttpWebRequest</span> request = (<span style="color: #2b91af">HttpWebRequest</span>) <span style="color: #2b91af">WebRequest</span>.Create(<span style="color: #a31515">@&quot;http://code.logos.com/blog/&quot;</span>);</p>      <p style="margin: 0px">request.IfModifiedSince = <span style="color: blue">new</span> <span style="color: #2b91af">DateTime</span>(2009, 6, 3);</p>      <p style="margin: 0px"><span style="color: blue">using</span> (<span style="color: #2b91af">HttpWebResponse</span> response = (<span style="color: #2b91af">HttpWebResponse</span>) request.GetResponse())</p>      <p style="margin: 0px">{</p>      <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">if</span> (response.StatusCode == <span style="color: #2b91af">HttpStatusCode</span>.NotModified)</p>      <p style="margin: 0px">&#160;&#160;&#160; {</p>      <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// page wasn't modified; use cached version</span></p>      <p style="margin: 0px">&#160;&#160;&#160; }</p>      <p style="margin: 0px">}</p>   </div> </div>  <p>But of course it’s not that simple (as <a title="Setting HTTP headers in .NET: This header must be modified using the appropriate property" href="http://www.clariusconsulting.net/blogs/kzu/archive/2007/07/30/29105.aspx">some</a> <a href="http://www.codeguru.com/csharp/.net/net_general/internet/print.php/c16073">others</a> <a title=".NET: Getting HTTP Headers" href="http://adventuresdotnet.blogspot.com/2009_04_01_archive.html">have</a> noticed).</p>  <p>The designers of HttpWebRequest decided that some particular HTTP status codes would cause a WebException to be thrown. (As far as I can tell, this list is undocumented, but 304 “Not Modified” is one of them.) This is a <a title="Vexing exceptions (Fabulous Adventures In Coding)" href="http://blogs.msdn.com/ericlippert/archive/2008/09/10/vexing-exceptions.aspx">vexing exception</a>, because the situation is hardly exceptional. In fact, because it can only happen if IfModifiedSince is explicitly set (or if request.Headers were modified), one could argue that it’s quite expected and intentional. To avoid duplicating logic in the try block (for handling 200 “OK”) and in the catch block (for handling “304” Not Modified), I wrote a utility method that swallows any WebException thrown due to a ProtocolError (e.g., an “invalid” HTTP status code):</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">class</span> <span style="color: #2b91af">HttpWebRequestUtility</span></p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Gets the </span><span style="color: gray">&lt;see cref=&quot;HttpWebResponse&quot;/&gt;</span><span style="color: green"> from an Internet resource.</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;param name=&quot;request&quot;&gt;</span><span style="color: green">The request.</span><span style="color: gray">&lt;/param&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;returns&gt;</span><span style="color: green">A </span><span style="color: gray">&lt;see cref=&quot;HttpWebResponse&quot;/&gt;</span><span style="color: green"> that contains the response from the Internet resource.</span><span style="color: gray">&lt;/returns&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;remarks&gt;</span><span style="color: green">This method does not throw a </span><span style="color: gray">&lt;see cref=&quot;WebException&quot;/&gt;</span><span style="color: green"> for &quot;error&quot; HTTP status codes; the caller should</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> check the </span><span style="color: gray">&lt;see cref=&quot;HttpWebResponse.StatusCode&quot;/&gt;</span><span style="color: green"> property to determine how to handle the response.</span><span style="color: gray">&lt;/remarks&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: #2b91af">HttpWebResponse</span> GetHttpResponse(<span style="color: blue">this</span> <span style="color: #2b91af">HttpWebRequest</span> request)</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">try</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> (<span style="color: #2b91af">HttpWebResponse</span>) request.GetResponse();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">catch</span> (<span style="color: #2b91af">WebException</span> ex)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// only handle protocol errors that have valid responses</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (ex.Response == <span style="color: blue">null</span> || ex.Status != <span style="color: #2b91af">WebExceptionStatus</span>.ProtocolError)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">throw</span>;</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> (<span style="color: #2b91af">HttpWebResponse</span>) ex.Response;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">}</p> </div>  <p>The code to consume this reads very similarly to the first snippet in this post; you just have to remember that normal errors (e.g., 404 “Not Found”) are reported through a valid HttpWebResponse, so its <a title="HttpWebResponse.StatusCode Property (MSDN)" href="http://msdn.microsoft.com/en-us/library/system.net.httpwebresponse.statuscode.aspx">StatusCode</a> property must be checked before acting on the response.</p>]]>
        
    </content>
</entry>

<entry>
    <title>Enumerable.Sum never returns null</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/06/enumerablesum_never_returns_null.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1530" title="Enumerable.Sum never returns null" />
    <id>tag:code.logos.com,2009:/blog//12.1530</id>
    
    <published>2009-06-01T23:55:07Z</published>
    <updated>2009-06-02T00:48:37Z</updated>
    
    <summary><![CDATA[I wrote the following code recently, and was surprised when ReSharper warned me that the condition is always true: IEnumerable&lt;int?&gt; values = // get some values int? sum = values.Sum(); if (sum.HasValue) { /* this code is always executed */...]]></summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="C#" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>I wrote the following code recently, and was surprised when ReSharper warned me that the condition is always true:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">int</span>?&gt; values = <span style="color: green">// get some values</span></p>    <p style="margin: 0px"><span style="color: blue">int</span>? sum = values.Sum();</p>    <div style="font-family: verdana; background: white; color: black; font-size: 8pt">     <p style="margin: 0px"><span style="color: blue">if</span> (sum.HasValue) { <span style="color: green">/* this code is always executed */</span> }</p>   </div> </div>  <p>It’s even more surprising when you consider the following difference:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: blue">int</span>?[] values = <span style="color: blue">new</span> <span style="color: blue">int</span>?[] { 1, <span style="color: blue">null</span> };</p>    <p style="margin: 0px"><span style="color: blue">int</span>? sum1 = values.Sum(); <span style="color: green">// returns 1</span></p>    <p style="margin: 0px"><span style="color: blue">int</span>? sum2 = values[0] + values[1]; <span style="color: green">// returns null</span></p> </div>  <p>Here, <code>sum1</code> is <code>1</code>, but <code>sum2</code> is <code>null</code>.</p>  <p>Since Sum&lt;int?&gt; never returns <code>null</code> (not even for any empty sequence, or a sequence containing all nulls), it’s odd that its return type is int?, implying that <code>null</code> is a possible return value. Anders <a href="http://social.msdn.microsoft.com/Forums/en-US/linqprojectgeneral/thread/b7ff1857-1b42-4b48-a4c9-850a8219f37b#a760c930-ef30-4d4e-b1c3-c560032a5349">explains</a> that this return type is to keep the pattern of <code>T Sum&lt;T&gt;(IEnumerable&lt;T&gt;)</code> for nullable types.</p>  <p>But what if you want Sum to return <code>null</code> if the sequence contains a <code>null</code>? This is easy to simulate using <code>Aggregate</code>, as C# already propagates nulls properly when using the addition operator:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">class</span> <span style="color: #2b91af">EnumerableUtility</span></p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">int</span>? NullableSum(<span style="color: blue">this</span> <span style="color: #2b91af">IEnumerable</span>&lt;<span style="color: blue">int</span>?&gt; values)</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> values.Aggregate((<span style="color: blue">int</span>?) 0, (sum, value) =&gt; sum + value);</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">}</p> </div>  <p>The initial value of 0 is specified to force the sum of an empty list to be zero<strike>; you could change it to <code>default(int?)</code> to make an empty list sum to <code>null</code></strike>. A possible optimisation would be to rewrite it with a <code>foreach</code> loop that returns <code>null</code> as soon as the first <code>null</code> in the sequence is found.</p>  <p><strong>Update</strong>: My <a href="http://www.fallingcanbedeadly.com/">very smart coworker</a> points out that changing the initial aggregate value to <code>default(int?)</code> makes the function return <code>null</code> for any input. (This is probably a good reason to include a full unit test suite with every blog post…) A custom enumerator (or test of <code>values.Any()</code> first) could be used if returning <code>null</code> as the sum of an empty sequence is desired.</p>]]>
        
    </content>
</entry>

<entry>
    <title>WrappingStream Implementation</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/05/wrappingstream_implementation.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1489" title="WrappingStream Implementation" />
    <id>tag:code.logos.com,2009:/blog//12.1489</id>
    
    <published>2009-05-06T17:12:05Z</published>
    <updated>2009-05-06T17:12:05Z</updated>
    
    <summary>In a previous post, I mentioned that a certain problem could be solved by creating “an implementation of Stream that wraps another stream”. “Anonymous” asked recently, “Can you send me the code of your straightforward solution that is wrapper the...</summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="C#" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>In a <a title="“Memory leak” with BitmapImage and MemoryStream" href="http://code.logos.com/blog/2008/04/memory_leak_with_bitmapimage_and_memorystream.html">previous post</a>, I mentioned that a certain problem could be solved by creating “an implementation of Stream that wraps another stream”. “Anonymous” asked recently, “Can you send me the code of your straightforward solution that is wrapper the class MemoryStream?”. Yes, but first I want to give another example of where such a class is useful.</p>  <p>The first time I used <a title="BinaryReader Class (MSDN)" href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.aspx">BinaryReader</a>, I wrote code similar to the following:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">void</span> DoSomething(<span style="color: #2b91af">Stream</span> stream)</p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// read a simple byte</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">int</span> value = stream.ReadByte();</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// simplify more complex reading by using a BinaryReader</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">using</span> (<span style="color: #2b91af">BinaryReader</span> reader = <span style="color: blue">new</span> <span style="color: #2b91af">BinaryReader</span>(stream))</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; value = reader.ReadInt32();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; value = reader.ReadInt32();</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// back to simple reading</span></p>    <p style="margin: 0px">&#160;&#160;&#160; value = stream.ReadByte();</p>    <p style="margin: 0px">}</p> </div>  <p>Experienced users of BinaryReader will see the problem here: the BinaryReader class takes ownership of the Stream with which it’s constructed, and disposes it in Dispose. (This somewhat-important detail is only briefly mentioned in the documentation for the <a title="BinaryReader.Close (MSDN)" href="http://msdn.microsoft.com/en-us/library/system.io.binaryreader.close.aspx">Close</a> method.) Thus the last call to ReadByte fails; we have also closed the Stream even though our caller probably expects it to still be open.</p>  <p>While the easy answer is to simply not Close/Dispose the BinaryReader (it holds no unmanaged resources, and so nothing “bad” happens if it’s not disposed), I feel guilty every time I don’t dispose an IDisposable object. Moreover, tools like the <a href="http://memprofiler.com/">.NET Memory Profiler</a> have a profiling mode that lists all non-disposed IDisposable objects (to help find resource leaks); leaving this BinaryReader undisposed generates a false positive and makes it harder to find the real leaks.</p>  <p>The WrappingStream class can be of use in this scenario by providing an implementation of Stream that the BinaryReader can own and Dispose without affecting the real stream:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: blue">using</span> (<span style="color: #2b91af">WrappingStream</span> wrapper = <span style="color: blue">new</span> <span style="color: #2b91af">WrappingStream</span>(stream))</p>    <p style="margin: 0px"><span style="color: blue">using</span> (<span style="color: #2b91af">BinaryReader</span> reader = <span style="color: blue">new</span> <span style="color: #2b91af">BinaryReader</span>(wrapper))</p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; value = reader.ReadInt32();</p>    <p style="margin: 0px">&#160;&#160;&#160; value = reader.ReadInt32();</p>    <p style="margin: 0px">}</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px"><span style="color: green">// 'stream' is still valid here</span></p> </div>  <p>Here, at long last, is the code for WrappingStream:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> A </span><span style="color: gray">&lt;see cref=&quot;Stream&quot;/&gt;</span><span style="color: green"> that wraps another stream. The major feature of </span><span style="color: gray">&lt;see cref=&quot;WrappingStream&quot;/&gt;</span><span style="color: green"> is that it does not dispose the</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> underlying stream when it is disposed; this is useful when using classes such as </span><span style="color: gray">&lt;see cref=&quot;BinaryReader&quot;/&gt;</span><span style="color: green"> and</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;see cref=&quot;System.Security.Cryptography.CryptoStream&quot;/&gt;</span><span style="color: green"> that take ownership of the stream passed to their constructors.</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">WrappingStream</span> : <span style="color: #2b91af">Stream</span></p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Initializes a new instance of the </span><span style="color: gray">&lt;see cref=&quot;WrappingStream&quot;/&gt;</span><span style="color: green"> class.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;param name=&quot;streamBase&quot;&gt;</span><span style="color: green">The wrapped stream.</span><span style="color: gray">&lt;/param&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> WrappingStream(<span style="color: #2b91af">Stream</span> streamBase)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// check parameters</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (streamBase == <span style="color: blue">null</span>)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">ArgumentNullException</span>(<span style="color: #a31515">&quot;streamBase&quot;</span>);</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_streamBase = streamBase;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Gets a value indicating whether the current stream supports reading.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;returns&gt;&lt;c&gt;</span><span style="color: green">true</span><span style="color: gray">&lt;/c&gt;</span><span style="color: green"> if the stream supports reading; otherwise, </span><span style="color: gray">&lt;c&gt;</span><span style="color: green">false</span><span style="color: gray">&lt;/c&gt;</span><span style="color: green">.</span><span style="color: gray">&lt;/returns&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">bool</span> CanRead</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span> { <span style="color: blue">return</span> m_streamBase == <span style="color: blue">null</span> ? <span style="color: blue">false</span> : m_streamBase.CanRead; }</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Gets a value indicating whether the current stream supports seeking.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;returns&gt;&lt;c&gt;</span><span style="color: green">true</span><span style="color: gray">&lt;/c&gt;</span><span style="color: green"> if the stream supports seeking; otherwise, </span><span style="color: gray">&lt;c&gt;</span><span style="color: green">false</span><span style="color: gray">&lt;/c&gt;</span><span style="color: green">.</span><span style="color: gray">&lt;/returns&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">bool</span> CanSeek</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span> { <span style="color: blue">return</span> m_streamBase == <span style="color: blue">null</span> ? <span style="color: blue">false</span> : m_streamBase.CanSeek; }</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Gets a value indicating whether the current stream supports writing.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;returns&gt;&lt;c&gt;</span><span style="color: green">true</span><span style="color: gray">&lt;/c&gt;</span><span style="color: green"> if the stream supports writing; otherwise, </span><span style="color: gray">&lt;c&gt;</span><span style="color: green">false</span><span style="color: gray">&lt;/c&gt;</span><span style="color: green">.</span><span style="color: gray">&lt;/returns&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">bool</span> CanWrite</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span> { <span style="color: blue">return</span> m_streamBase == <span style="color: blue">null</span> ? <span style="color: blue">false</span> : m_streamBase.CanWrite; }</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Gets the length in bytes of the stream.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">long</span> Length</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span> { ThrowIfDisposed();&#160; <span style="color: blue">return</span> m_streamBase.Length; }</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Gets or sets the position within the current stream.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">long</span> Position</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span> { ThrowIfDisposed(); <span style="color: blue">return</span> m_streamBase.Position; }</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">set</span> { ThrowIfDisposed(); m_streamBase.Position = <span style="color: blue">value</span>; }</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Begins an asynchronous read operation.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">IAsyncResult</span> BeginRead(<span style="color: blue">byte</span>[] buffer, <span style="color: blue">int</span> offset, <span style="color: blue">int</span> count, <span style="color: #2b91af">AsyncCallback</span> callback, <span style="color: blue">object</span> state)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> m_streamBase.BeginRead(buffer, offset, count, callback, state);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Begins an asynchronous write operation.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: #2b91af">IAsyncResult</span> BeginWrite(<span style="color: blue">byte</span>[] buffer, <span style="color: blue">int</span> offset, <span style="color: blue">int</span> count, <span style="color: #2b91af">AsyncCallback</span> callback, <span style="color: blue">object</span> state)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> m_streamBase.BeginWrite(buffer, offset, count, callback, state);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Waits for the pending asynchronous read to complete.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">int</span> EndRead(<span style="color: #2b91af">IAsyncResult</span> asyncResult)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> m_streamBase.EndRead(asyncResult);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Ends an asynchronous write operation.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">void</span> EndWrite(<span style="color: #2b91af">IAsyncResult</span> asyncResult)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_streamBase.EndWrite(asyncResult);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Clears all buffers for this stream and causes any buffered data to be written to the underlying device.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">void</span> Flush()</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_streamBase.Flush();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Reads a sequence of bytes from the current stream and advances the position</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> within the stream by the number of bytes read.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">int</span> Read(<span style="color: blue">byte</span>[] buffer, <span style="color: blue">int</span> offset, <span style="color: blue">int</span> count)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> m_streamBase.Read(buffer, offset, count);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Reads a byte from the stream and advances the position within the stream by one byte, or returns -1 if at the end of the stream.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">int</span> ReadByte()</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> m_streamBase.ReadByte();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Sets the position within the current stream.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;param name=&quot;offset&quot;&gt;</span><span style="color: green">A byte offset relative to the </span><span style="color: gray">&lt;paramref name=&quot;origin&quot;/&gt;</span><span style="color: green"> parameter.</span><span style="color: gray">&lt;/param&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;param name=&quot;origin&quot;&gt;</span><span style="color: green">A value of type </span><span style="color: gray">&lt;see cref=&quot;T:System.IO.SeekOrigin&quot;/&gt;</span><span style="color: green"> indicating the reference point used to obtain the new position.</span><span style="color: gray">&lt;/param&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;returns&gt;</span><span style="color: green">The new position within the current stream.</span><span style="color: gray">&lt;/returns&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">long</span> Seek(<span style="color: blue">long</span> offset, <span style="color: #2b91af">SeekOrigin</span> origin)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> m_streamBase.Seek(offset, origin);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Sets the length of the current stream.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;param name=&quot;value&quot;&gt;</span><span style="color: green">The desired length of the current stream in bytes.</span><span style="color: gray">&lt;/param&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">void</span> SetLength(<span style="color: blue">long</span> value)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_streamBase.SetLength(value);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Writes a sequence of bytes to the current stream and advances the current position</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> within this stream by the number of bytes written.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">void</span> Write(<span style="color: blue">byte</span>[] buffer, <span style="color: blue">int</span> offset, <span style="color: blue">int</span> count)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_streamBase.Write(buffer, offset, count);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Writes a byte to the current position in the stream and advances the position within the stream by one byte.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">void</span> WriteByte(<span style="color: blue">byte</span> value)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; ThrowIfDisposed();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_streamBase.WriteByte(value);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Gets the wrapped stream.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;value&gt;</span><span style="color: green">The wrapped stream.</span><span style="color: gray">&lt;/value&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: #2b91af">Stream</span> WrappedStream</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span> { <span style="color: blue">return</span> m_streamBase; }</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Releases the unmanaged resources used by the </span><span style="color: gray">&lt;see cref=&quot;WrappingStream&quot;/&gt;</span><span style="color: green"> and optionally releases the managed resources.</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;param name=&quot;disposing&quot;&gt;</span><span style="color: green">true to release both managed and unmanaged resources; false to release only unmanaged resources.</span><span style="color: gray">&lt;/param&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">protected</span> <span style="color: blue">override</span> <span style="color: blue">void</span> Dispose(<span style="color: blue">bool</span> disposing)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// doesn't close the base stream, but just prevents access to it through this WrappingStream</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (disposing)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_streamBase = <span style="color: blue">null</span>;</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">base</span>.Dispose(disposing);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">private</span> <span style="color: blue">void</span> ThrowIfDisposed()</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// throws an ObjectDisposedException if this object has been disposed</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">if</span> (m_streamBase == <span style="color: blue">null</span>)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">throw</span> <span style="color: blue">new</span> <span style="color: #2b91af">ObjectDisposedException</span>(GetType().Name);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">Stream</span> m_streamBase;</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p> </div>  <p>You’ll note that this class isn’t sealed; that’s because it can be a useful base class for more specialised wrappers, some of which I hope to cover in future posts.</p>]]>
        
    </content>
</entry>

<entry>
    <title>How to use UMDH to find native memory leaks</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/04/how_to_use_umdh_to_find_native_memory_leaks.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1477" title="How to use UMDH to find native memory leaks" />
    <id>tag:code.logos.com,2009:/blog//12.1477</id>
    
    <published>2009-04-28T23:05:39Z</published>
    <updated>2009-04-28T23:05:39Z</updated>
    
    <summary>The Debugging Tools for Windows packages come with a tool—UMDH.exe—that makes finding memory leaks in native code really pretty easy. There’s a Microsoft Knowledgebase Article that gives an overview of how to use the tool but it’s a little out...</summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="Debugging" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>The <a href="http://www.microsoft.com/whdc/devtools/debugging/default.mspx">Debugging Tools for Windows</a> packages come with a tool—UMDH.exe—that makes finding memory leaks in native code really pretty easy. There’s a <a href="http://support.microsoft.com/kb/268343">Microsoft Knowledgebase Article</a> that gives an overview of how to use the tool but it’s a little out of date. (It’s also very detailed, and I usually just want a summary.)</p>  <p>All these steps assume you have the latest Debugging Tools package installed and in your path. (Note that you need to run the tools for the same platform (x86 vs x64) as the target executable.)</p>  <h3>Start Collecting Data</h3>  <p>At an Administrator command prompt, run gflags.exe to start collecting stack traces for user-mode allocations:</p>  <blockquote><tt>gflags –i Program.exe +ust</tt></blockquote>  <h3>Collect Snapshots</h3>  <p>Start Program.exe running, and collect a baseline snapshot (this can be done from a regular command prompt):</p>  <blockquote><tt>umdh –pn:Program.exe –f:Dump1.txt</tt></blockquote>  <p>Perform the action that leaks memory, and collect a second snapshot:</p>  <blockquote><tt>umdh –pn:Program.exe –f:Dump2.txt</tt></blockquote>  <p>(If “Program.exe” is not a unique process name, the “-p:” command line argument can select a process by ID.)</p>  <h3>Compare Snapshots</h3>  <blockquote><tt>umdh –d Dump1.txt Dump2.txt &gt; Diff.txt</tt></blockquote>  <p>Open <em>Diff.txt</em> in your favourite text editor (that can handle large files!). The memory leaks are listed in descending order of bytes leaked; each should be followed by the complete stack trace of the allocation call. Depending on the cause, this may either pinpoint the bug, or at least show a good place to set a breakpoint for debugging.</p>  <h3>Stop Data Collection</h3>  <p>The most important step in the whole process is to turn off the data collection for your application (once the memory leak is fixed), or else your program will run slowly while the OS kernel logs every memory allocation:</p>  <blockquote><tt>gflags –i Program.exe -ust</tt></blockquote>]]>
        
    </content>
</entry>

<entry>
    <title>DateTime and ISO8601</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/04/datetime_and_iso8601.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1465" title="DateTime and ISO8601" />
    <id>tag:code.logos.com,2009:/blog//12.1465</id>
    
    <published>2009-04-14T16:24:22Z</published>
    <updated>2009-04-14T16:25:15Z</updated>
    
    <summary>The ISO 8601 standard for representing dates and times defines a (large) number of string formats for serializing dates. One of the more common formats in use (certainly here at Logos) uses the “extended format”, specifies the full date and...</summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="C#" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>The <a title="ISO 8601 (Wikipedia)" href="http://en.wikipedia.org/wiki/ISO_8601">ISO 8601 standard</a> for representing dates and times defines a (large) number of string formats for serializing dates. One of the more common formats in use (certainly here at Logos) uses the “extended format”, specifies the full date and time (but only in whole, not fractional, seconds) and always uses UTC. A string in this format looks like “2009-04-14T16:19:58Z”.</p>  <p>The <a href="http://msdn.microsoft.com/en-us/library/az4se3k1.aspx">standard date and time format strings</a> for .NET don’t include a pattern that uses this precise format. The round-trip date/time pattern (specified by “o”) includes fractional seconds (e.g., “2009-04-14T16:19:58.0785018Z”), whereas the universal sortable date/time pattern (specified by “u”) has a space instead of a ‘T’ between the date and the time (e.g., “2009-04-14 16:19:58Z”).</p>  <p>We wrote the following utility methods to parse and render DateTimes in our preferred format:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px"><span style="color: gray">///</span><span style="color: green"> Provides methods for manipulating dates.</span></p>    <p style="margin: 0px"><span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">class</span> <span style="color: #2b91af">DateTimeUtility</span></p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Converts the specified ISO 8601 representation of a date and time</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> to its DateTime equivalent. </span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;param name=&quot;value&quot;&gt;</span><span style="color: green">The ISO 8601 string representation to parse.</span><span style="color: gray">&lt;/param&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;returns&gt;</span><span style="color: green">The DateTime equivalent.</span><span style="color: gray">&lt;/returns&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: #2b91af">DateTime</span> ParseIso8601(<span style="color: blue">string</span> value)</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: #2b91af">DateTime</span>.ParseExact(value,</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; Iso8601Format, <span style="color: #2b91af">CultureInfo</span>.InvariantCulture,</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: #2b91af">DateTimeStyles</span>.AssumeUniversal | <span style="color: #2b91af">DateTimeStyles</span>.AdjustToUniversal);</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> Formats the date in the standard ISO 8601 format.</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;param name=&quot;value&quot;&gt;</span><span style="color: green">The date to format.</span><span style="color: gray">&lt;/param&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;returns&gt;</span><span style="color: green">The formatted date.</span><span style="color: gray">&lt;/returns&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">static</span> <span style="color: blue">string</span> ToIso8601(<span style="color: blue">this</span> <span style="color: #2b91af">DateTime</span> value)</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> value.ToUniversalTime().ToString(Iso8601Format, <span style="color: #2b91af">CultureInfo</span>.InvariantCulture);</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> The ISO 8601 format string.</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: gray">///</span><span style="color: green"> </span><span style="color: gray">&lt;/summary&gt;</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">const</span> <span style="color: blue">string</span> Iso8601Format = <span style="color: #a31515">&quot;yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'&quot;</span>;</p>    <p style="margin: 0px">}</p> </div>]]>
        
    </content>
</entry>

<entry>
    <title>Creating Mixins with T4 in Visual Studio</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/04/creating_mixins_with_t4_in_visual_studio.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1461" title="Creating Mixins with T4 in Visual Studio" />
    <id>tag:code.logos.com,2009:/blog//12.1461</id>
    
    <published>2009-04-08T15:51:23Z</published>
    <updated>2009-04-08T15:51:23Z</updated>
    
    <summary>One of the (few) features I really miss from C++ is the ability to use multiple inheritance to create mixins, particularly with the Curiously Recurring Template Pattern. Scott Hanselman blogged about T4 (Text Template Transformation Toolkit) a few months back,...</summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="C#" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>One of the (few) features I really miss from C++ is the ability to use multiple inheritance to create <a href="http://en.wikipedia.org/wiki/Mixin">mixins</a>, particularly with the <a href="http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern">Curiously Recurring Template Pattern</a>.</p>  <p>Scott Hanselman <a title="T4 (Text Template Transformation Toolkit) Code Generation - Best Kept Visual Studio Secret" href="http://www.hanselman.com/blog/T4TextTemplateTransformationToolkitCodeGenerationBestKeptVisualStudioSecret.aspx">blogged about T4</a> (Text Template Transformation Toolkit) a few months back, but only recently it hit me that T4 could be combined with <a href="http://msdn.microsoft.com/en-us/library/wa80x488.aspx">partial classes</a> to create a poor man's mixin system in C# 3.0.</p>  <p>For a simple example, let's consider a class that supports <code>IEquatable&lt;T&gt;</code>. The logic that’s specific to computing equality for this class will be in the <code>Equals</code> and <code>GetHashCode</code> methods:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">TestObject</span> : <span style="color: #2b91af">IEquatable</span>&lt;<span style="color: #2b91af">TestObject</span>&gt;</p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> TestObject(<span style="color: blue">int</span> value)</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; Value = value;</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">bool</span> Equals(<span style="color: #2b91af">TestObject</span> other)</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> other != <span style="color: blue">null</span> &amp;&amp; Value == other.Value;</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">override</span> <span style="color: blue">int</span> GetHashCode()</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> Value;</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: blue">int</span> Value { <span style="color: blue">get</span>; <span style="color: blue">set</span>; }</p>    <p style="margin: 0px">}</p> </div>  <p>To round out this class, we really should implement <code>Equals(object)</code> and overload the equality operators. This is exactly where a mixin would be useful, because that code is exactly the same in every implementation of an equatable object.</p>  <p>Firstly, prepare <code>TestObject</code> to support mixins by making it a partial class:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">partial</span> <span style="color: blue">class</span> <span style="color: #2b91af">TestObject</span> : <span style="color: #2b91af">IEquatable</span>&lt;<span style="color: #2b91af">TestObject</span>&gt;</p> </div>  <p>Secondly, create the mixin source: the templated methods of the equatable implementations. Add a new item to the project, and set the name to “EquatableClass.tt”. (This implementation will be for classes only; a separate mixin would need to be created for structs since they can’t ever be null.)</p>  <p>Open the Properties window for this new file, and clear the <em>Custom Tool</em> property. This prevents an output file being generated for this template.</p>  <p>Fill in the EquatableClass.tt file with this code, a templated version of standard equality methods.</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px">namespace &lt;#= NamespaceName #&gt;</p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; partial class &lt;#= ClassName #&gt;</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; public override bool Equals(object other)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return Equals(other as &lt;#= ClassName #&gt;);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; public static bool operator==(&lt;#= ClassName #&gt; left, &lt;#= ClassName #&gt; right)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (ReferenceEquals(left, right))</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return true;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else if (ReferenceEquals(left, null) || ReferenceEquals(right, null))</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return false;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return left.Equals(right);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; public static bool operator!=(&lt;#= ClassName #&gt; left, &lt;#= ClassName #&gt; right)</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; if (ReferenceEquals(left, right))</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return false;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else if (ReferenceEquals(left, null) || ReferenceEquals(right, null))</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return true;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; else</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; return !left.Equals(right);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">}</p>    <p style="margin: 0px">&lt;#+</p>    <p style="margin: 0px">&#160;&#160;&#160; public void SetClassName(string namespaceName, string className)</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; NamespaceName = namespaceName;</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; ClassName = className;</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; string NamespaceName;</p>    <p style="margin: 0px">&#160;&#160;&#160; string ClassName;</p>    <p style="margin: 0px">#&gt;</p> </div>  <p>This template (when included in another template) outputs the standard equality methods and also provides a way for the including template to customize the output.</p>  <p>Lastly, write the including template. Add another file to the project, this time named “TestObjectEquatable.tt”. Paste the following code into that file:</p>  <div style="font-family: verdana; background: white; color: black; font-size: 8pt">   <p style="margin: 0px">&lt;#@template language=&quot;C#&quot;#&gt;</p>    <p style="margin: 0px">&lt;#@output extension=&quot;g.cs&quot; #&gt;</p>    <p style="margin: 0px">&lt;# SetClassName(&quot;Mixins&quot;, &quot;TestObject&quot;); #&gt;</p>    <p style="margin: 0px">&lt;#@include file=&quot;EquatableClass.tt&quot;#&gt;</p> </div>  <p>These four lines have the following effects:</p>  <ol>   <li>Instructs the T4 engine that code in this template is written in C#. </li>    <li>Sets the extension of the file to “.g.cs”; this clearly identifies the output as generated code. </li>    <li>Calls the <code>SetClassName</code> method defined in the first template so that the right namespace and class name are used in the generated code. </li>    <li>Includes the first template, causing all the code it defines to be generated. </li> </ol>  <p>When the project is built, the TestObjectEquatable.tt template will be processed to generate a partial class containing the supporting equality methods. The C# compiler will compile this with the primary partial class, giving a complete implementation of the standard equality methods. </p>  <p>Now that the template is defined, only the four lines in the second template need to be copied to add equatable methods to a new class, instead of the 25 lines of boilerplate code that the template generates.</p>  <p>One significant drawback with this approach is that a template is only reprocessed when it changes; the template engine isn't aware that TestObjectEquatable.tt depends on EquatableClass.tt, and that it should be reprocessed if the latter changes. For this reason, it’s probably best to keep the included template rather simple; it would be better to have the generated methods delegate to composed objects or static methods on utility classes rather than including a lot of complicated logic in the template itself.</p>  <p>To learn more about T4, I highly recommend <a href="http://www.olegsych.com/">Oleg Sych’s blog</a>, which contains many tutorials, examples, and information about his <a href="http://www.codeplex.com/t4toolbox">T4 Toolbox</a> project.</p>]]>
        
    </content>
</entry>

<entry>
    <title>ReadOnlyObservableCollection anti-pattern</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/03/readonlyobservablecollection_anti-pattern.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1438" title="ReadOnlyObservableCollection anti-pattern" />
    <id>tag:code.logos.com,2009:/blog//12.1438</id>
    
    <published>2009-03-17T16:02:49Z</published>
    <updated>2009-03-17T16:12:57Z</updated>
    
    <summary><![CDATA[I recently fixed a bug that was a result of a subtle misuse of the ReadOnlyObservableCollection&lt;T&gt; class. The code in question was structured as follows: The Source class has a collection of Items. Clients should be able to observe but...]]></summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
        <category term="C#" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>I recently fixed a bug that was a result of a subtle misuse of the <a title="ReadOnlyObservableCollection(T) Class (MSDN)" href="http://msdn.microsoft.com/en-us/library/ms668620.aspx">ReadOnlyObservableCollection&lt;T&gt;</a> class. The code in question was structured as follows: The <code>Source</code> class has a collection of <code>Items</code>. Clients should be able to observe but not modify the collection, so it’s exposed as a ReadOnlyObservableCollection. The <code>Client</code> class adds an event handler to this collection, and removes it at the appropriate time (to prevent a possible memory leak).</p>  <div style="font-size: 8pt; background: white; color: black; font-family: verdana">   <p style="margin: 0px"><span style="color: blue">class</span> <span style="color: #2b91af">Source</span></p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; Source()</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_collection = <span style="color: blue">new</span> <span style="color: #2b91af">ObservableCollection</span>&lt;<span style="color: blue">int</span>&gt;();</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ReadOnlyObservableCollection</span>&lt;<span style="color: blue">int</span>&gt; Items</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: green">// this is the bug</span></p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">return</span> <span style="color: blue">new</span> <span style="color: #2b91af">ReadOnlyObservableCollection</span>&lt;<span style="color: blue">int</span>&gt;(m_collection);</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">readonly</span> <span style="color: #2b91af">ObservableCollection</span>&lt;<span style="color: blue">int</span>&gt; m_collection;</p>    <p style="margin: 0px">}</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px"><span style="color: blue">class</span> <span style="color: #2b91af">Client</span></p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: green">// obtain Source instance from somewhere</span></p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: #2b91af">Source</span> m_source;</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">void</span> Subscribe()</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; ((<span style="color: #2b91af">INotifyCollectionChanged</span>) m_source.Items).CollectionChanged += SourceItems_CollectionChanged;</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">void</span> Unsubscribe()</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; ((<span style="color: #2b91af">INotifyCollectionChanged</span>) m_source.Items).CollectionChanged += SourceItems_CollectionChanged;</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">void</span> SourceItems_CollectionChanged(<span style="color: blue">object</span> sender, <span style="color: #2b91af">NotifyCollectionChangedEventArgs</span> e) { }</p>    <p style="margin: 0px">}</p> </div>  <p>The bug is that the <code>Source.Items</code> property creates a new ReadOnlyObservableCollection instance each time it’s accessed, which means that the calls to add and remove the event handler happen on two different objects; the event handler is never actually removed.</p>  <p>One solution is for the <code>Client</code> class to cache the exact INotifyCollectionChanged object it subscribed to, so it can be sure to unsubscribe from the same object. The other (and better) solution is for the <code>Source</code> class to create and hold a ReadOnlyObservableCollection, and return the same object each time the <code>Items</code> property is accessed:</p>  <div style="font-size: 8pt; background: white; color: black; font-family: verdana">   <p style="margin: 0px"><span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Source</span></p>    <p style="margin: 0px">{</p>    <p style="margin: 0px">&#160;&#160;&#160; Source()</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_collection = <span style="color: blue">new</span> <span style="color: #2b91af">ObservableCollection</span>&lt;<span style="color: blue">int</span>&gt;();</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; m_collectionReadOnly = <span style="color: blue">new</span> <span style="color: #2b91af">ReadOnlyObservableCollection</span>&lt;<span style="color: blue">int</span>&gt;(m_collection);</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">public</span> <span style="color: #2b91af">ReadOnlyObservableCollection</span>&lt;<span style="color: blue">int</span>&gt; Items</p>    <p style="margin: 0px">&#160;&#160;&#160; {</p>    <p style="margin: 0px">&#160;&#160;&#160;&#160;&#160;&#160;&#160; <span style="color: blue">get</span> { <span style="color: blue">return</span> m_collectionReadOnly; }</p>    <p style="margin: 0px">&#160;&#160;&#160; }</p>    <p style="margin: 0px">&#160;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">readonly</span> <span style="color: #2b91af">ObservableCollection</span>&lt;<span style="color: blue">int</span>&gt; m_collection;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">readonly</span> <span style="color: #2b91af">ReadOnlyObservableCollection</span>&lt;<span style="color: blue">int</span>&gt; m_collectionReadOnly;</p>    <p style="margin: 0px">}</p> </div>  <p>This solves the initial bug and also has the benefit of allowing all clients to share the same ReadOnlyObservableCollection instance (instead of creating one per client).</p>]]>
        
    </content>
</entry>

<entry>
    <title>Subtle Differences</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/03/subtle_differences.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1428" title="Subtle Differences" />
    <id>tag:code.logos.com,2009:/blog//12.1428</id>
    
    <published>2009-03-09T15:25:35Z</published>
    <updated>2009-03-09T15:25:35Z</updated>
    
    <summary>What’s the difference between the values generated by the following statements?     long ticks1 = stopwatch.ElapsedTicks;     long ticks2 = stopwatch.Elapsed.Ticks; While the latter uses the standard 100-nanosecond intervals (used by FILETIME, DateTime, etc.) as its units, the former reports...</summary>
    <author>
        <name>Bradley Grainger</name>
        <uri>http://code.logos.com/blog/2008/04/author_introduction_bradley_grainger.html</uri>
    </author>
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>What’s the difference between the values generated by the following statements?</p>  <div style="font-size: 8pt; background: white; color: black; font-family: verdana">   <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">long</span> ticks1 = stopwatch.ElapsedTicks;</p>    <p style="margin: 0px">&#160;&#160;&#160; <span style="color: blue">long</span> ticks2 = stopwatch.Elapsed.Ticks;</p> </div>  <p>While the latter uses the standard 100-nanosecond intervals (used by <a title="FILETIME Structure (MSDN)" href="http://msdn.microsoft.com/en-us/library/ms724284(VS.85).aspx">FILETIME</a>, <a title="DateTime Structure (MSDN)" href="http://msdn.microsoft.com/en-us/library/z2xf7zzk.aspx">DateTime</a>, etc.) as its units, the former reports the number of ticks as measured by the system’s high-resolution performance counter, and is not very meaningful until divided by <code><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.frequency.aspx">Stopwatch.Frequency</a></code>. The use of the noun ‘ticks’ to describe both is unfortunate.</p>  <p>Here’s another difference, which turns out to not be so significant after all:</p>  <div style="font-size: 8pt; background: white; color: black; font-family: verdana">   <p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; using</span> System.Linq;</p>    <p style="margin: 0px">&#160;<span style="color: green">&#160;&#160; // ...</span></p>    <p style="margin: 0px">&#160;<span style="color: blue">&#160;&#160; bool</span> contains1 = dictionary.ContainsKey(value);</p>    <p style="margin: 0px"><span style="color: blue">&#160;&#160;&#160; bool</span> contains2 = dictionary.Keys.Contains(value);</p> </div>  <p></p>  <p>I initially assumed that the second statement—which invokes the <code>Enumerable.Contains</code> extension method—would perform a linear search over a copy of all the keys in the Dictionary. However, some exploration with Reflector showed that <code>Enumerable.Contains</code> first checks if its parameter implements <code>ICollection&lt;T&gt;</code>. The <code>KeyCollection</code> returned by <code>Dictionary&lt;K, V&gt;.Keys</code> does implement this interface, and its implementation of <code>Contains</code> simply delegates to <code>ContainsKey</code>. Experimentation showed that the latter statement only takes twice as long as the first—not the O(1) vs O(<em>n</em>) difference I was expecting. While API duplication should be avoided, some overlap is inevitable when retrofitting extension methods to an existing codebase; it’s very nice that the LINQ to Objects design allows for an efficient implementation to be chosen when it’s available.</p>]]>
        
    </content>
</entry>

<entry>
    <title>CHARINDEX ?</title>
    <link rel="alternate" type="text/html" href="http://code.logos.com/blog/2009/01/charindex.html" />
    <link rel="service.edit" type="application/atom+xml" href="http://blog.logos.com/mt-cgi/mt-atom.cgi/weblog/blog_id=12/entry_id=1371" title="CHARINDEX ?" />
    <id>tag:code.logos.com,2009:/blog//12.1371</id>
    
    <published>2009-01-15T01:32:44Z</published>
    <updated>2009-01-15T02:06:15Z</updated>
    
    <summary>CHARINDEX returns the index of a successful string match.</summary>
    <author>
        <name>Bill Simpkins</name>
        <uri>http://www.logos.com</uri>
    </author>
    
        <category term="SQL" />
    
    <content type="html" xml:lang="en" xml:base="http://code.logos.com/blog/">
        <![CDATA[<p>CHARINDEX. Yeah. That's right. It is <em>one</em> of my favorite SQL functions. I rarely see it used and most people I know don't even know about it. Consequently, I must blab about it a little.</p>

<p>CHARINDEX returns the index of a successful string match.</p>

<p>For example:<br />
<!--<br />
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red163\green21\blue21;}??\fs20 \cf1 print charindex\cf0 (\cf4 'cat'\cf0 ,\cf4 'my cat is king'\cf0 )}<br />
--><br />
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;"><p style="margin: 0px;"><span style="color: blue;">print charindex</span>(<span style="color: #a31515;">'cat'</span>,<span style="color: #a31515;">'my cat is king'</span>)</p></div></p>

<p>Returns: 4</p>

<p><br />
The searches can also be case sensitive:<br />
<!--<br />
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red163\green21\blue21;}??\fs20 \cf1 print charindex\cf0 (\cf4 'king'\cf0 ,\cf4 'my cat is KING!' \cf1 COLLATE \cf0 Latin1_General_CS_AS)}<br />
--><br />
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;"><p style="margin: 0px;"><span style="color: blue;">print charindex</span>(<span style="color: #a31515;">'king'</span>,<span style="color: #a31515;">'my cat is KING!' </span><span style="color: blue;">COLLATE </span>Latin1_General_CS_AS)</p></div></p>

<p>returns: 0</p>

<p><br />
Here is a little function I use from time to time. It grabs the text in between two characters:<br />
<!--<br />
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;}??\fs20 \cf1 Create Function \cf0 [dbo].[fnBetweenCharacters](@text \cf1 ntext\cf0 , @startChar \cf1 nchar\cf0 (1), @endChar \cf1 nchar\cf0 (1)) \par ??\par ??\cf1 RETURNS nvarchar\cf0 (4000)\par ??\par ??\cf1 AS\par ??\par ??BEGIN\par ??\par ??declare \cf0 @startIndex \cf1 int\par ??declare \cf0 @endIndex \cf1 int\par ??\par ??set \cf0 @startIndex = \cf1 charindex\cf0 (@startChar, @text, 1)\par ??\cf1 set \cf0 @endIndex = \cf1 charindex\cf0 (@endChar, @text, @startIndex+1)\par ??\par ??\cf1 return substring\cf0 (@text,@startIndex+1, @endIndex - @startIndex-1)\par ??\par ??\cf1 END}<br />
--><br />
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;"><p style="margin: 0px;"><span style="color: blue;">Create Function </span>[dbo].[fnBetweenCharacters](@text <span style="color: blue;">ntext</span>, @startChar <span style="color: blue;">nchar</span>(1), @endChar <span style="color: blue;">nchar</span>(1)) </p><p style="margin: 0px;">&nbsp;</p><p style="margin: 0px;"><span style="color: blue;">RETURNS nvarchar</span>(4000)</p><p style="margin: 0px;">&nbsp;</p><p style="margin: 0px;"><span style="color: blue;">AS</span></p><p style="margin: 0px;">&nbsp;</p><p style="margin: 0px;"><span style="color: blue;">BEGIN</span></p><p style="margin: 0px;">&nbsp;</p><p style="margin: 0px;"><span style="color: blue;">declare </span>@startIndex <span style="color: blue;">int</span></p><p style="margin: 0px;"><span style="color: blue;">declare </span>@endIndex <span style="color: blue;">int</span></p><p style="margin: 0px;">&nbsp;</p><p style="margin: 0px;"><span style="color: blue;">set </span>@startIndex = <span style="color: blue;">charindex</span>(@startChar, @text, 1)</p><p style="margin: 0px;"><span style="color: blue;">set </span>@endIndex = <span style="color: blue;">charindex</span>(@endChar, @text, @startIndex+1)</p><p style="margin: 0px;">&nbsp;</p><p style="margin: 0px;"><span style="color: blue;">return substring</span>(@text,@startIndex+1, @endIndex - @startIndex-1)</p><p style="margin: 0px;">&nbsp;</p><p style="margin: 0px;"><span style="color: blue;">END</span></p></div></p>

<p><br />
It can be used like this:<br />
<!--<br />
{\rtf1\ansi\ansicpg\lang1024\noproof65001\uc1 \deff0{\fonttbl{\f0\fnil\fcharset0\fprq1 Courier New;}}{\colortbl;??\red0\green0\blue255;\red255\green255\blue255;\red0\green0\blue0;\red163\green21\blue21;}??\fs20 \cf1 print \cf0 [dbo].[fnBetweenCharacters](N\cf4 'asdkljasd@I need this text*k;lk'\cf0 , \cf4 '@'\cf0 , \cf4 '*'\cf0 ) }<br />
--><br />
<div style="font-family: Courier New; font-size: 10pt; color: black; background: white;"><p style="margin: 0px;"><span style="color: blue;">print </span>[dbo].[fnBetweenCharacters](N<span style="color: #a31515;">'asdkljasd@I need this text*k;lk'</span>, <span style="color: #a31515;">'@'</span>, <span style="color: #a31515;">'*'</span>) </p></div></p>

<p>returns: I need this text</p>

<p><br />
Pass it on!</p>]]>
        
    </content>
</entry>

</feed>
