tag:blogger.com,1999:blog-192120772024-03-05T08:36:58.711-08:00Code never written......never needs maintenance.Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.comBlogger30125tag:blogger.com,1999:blog-19212077.post-13279793927669521462020-01-23T17:50:00.000-08:002020-01-23T17:50:05.057-08:00Visual Studio doesn't discover my unit tests!I added a unit test class to a project today, and Visual Studio couldn't find my new unit tests. Quick hack: modify your output window to "Show output from:" "Tests." This may help you find the reason why. In my case, it told me pretty directly what the issue was:<br />
<br />
<div style="text-align: center;">
<span style="font-family: Courier New, Courier, monospace;">UTA001: TestClass attribute defined on non-public class MyTests</span></div>
<br />
My test class wasn't <span style="font-family: Courier New, Courier, monospace;">public</span>, which it appears is a requirement for discovery.Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.comtag:blogger.com,1999:blog-19212077.post-53452773425836235312019-04-03T20:03:00.000-07:002019-04-03T20:03:11.724-07:00Updating include directories after updating VivadoSo, after updating Vivado, I ended up with a number of warnings during compile in the SDK IDE, referring to an old, now missing path. As the paths didn't appear to be modifiable within the project settings, I searched for a way to update them.<br />
<br />
That brought me to <a href="https://forums.xilinx.com/t5/Embedded-Development-Tools/Include-PATH-not-found-SDK/m-p/737514/highlight/true#M40630">this post</a>, which has approximately the right stuff:<br />
<br />
<br />
<ol>
<li>Close the SDK.</li>
<li>Delete the .metadata folder in your xyz.sdk folder.</li>
<li>Restart the SDK.</li>
<li>Import the existing projects. You'll see that only the design folder was automatically imported.
</li>
</ol>
<br />
<br />Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-1737569382380144112017-12-14T17:43:00.000-08:002017-12-14T17:44:17.128-08:00No matching key exchange method foundRan into this again while trying to <span style="font-family: Courier New, Courier, monospace;">ssh</span> into the old battleship:<br />
<br />
<div style="text-align: center;">
no matching key exchange method found. Their offer: diffie-hellman-group1-sha1</div>
<br />
A solution is to specify the key exchange algorithm on the command line:<br />
<br />
<div style="text-align: center;">
<span style="font-family: Courier New, Courier, monospace;">ssh -o KexAlgorithms=+diffie-hellman-group1-sha1 root@169.254.8.70</span></div>
<br />
More information can be found on <a href="https://www.openssh.com/legacy.html" target="_blank">OpenSSH's Legacy Options page</a>.Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-37418317111220161042017-10-31T19:56:00.000-07:002017-10-31T20:01:03.658-07:00Vivado does not launch with Windows 10 Fall Creators UpdateThere's a work-around available from Xilinx <a href="https://www.xilinx.com/support/answers/69908.html" target="_blank">AR 69908</a>. Windows 10 Fall Creators Update is not officially supported for Vivado 17.3 or 17.3.1.<br />
<br />
<br />Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-10131962129782534772017-03-12T10:24:00.000-07:002017-03-12T10:24:10.145-07:00Downloading an ISO for Visual Studio 2017<b>Note to Self</b><br />
<u><br /></u>
There isn't an ISO image download for VS 2017, you download the web installer, then pass it the commands to construct a disk layout for you. Here's the location of instructions to do so:<br />
<br />
<a href="https://docs.microsoft.com/en-us/visualstudio/install/create-an-offline-installation-of-visual-studio" target="_blank">Create an offline installer for Visual Studio 2017</a><br />
<br />
That page includes instructions for:<br />
<br />
<ul>
<li>Creating an offline installation layout.</li>
<li>Installing from an offline installation layout (may not be necessary, see the comments on this instruction).</li>
<li>Customizing the offline installer.</li>
<li>Updating the offline installer.</li>
<li>Troubleshooting.</li>
</ul>
<br />
And here's the command line I use:<br />
<br />
<span style="background-color: #fff2cc; font-family: "consolas" , "courier new" , "courier" , monospace;">vs_Community.exe --layout c:\vs2017-community-en-US-offline --lang en-US</span><br />
<br />
<br />Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-8001256868738991142016-04-29T07:00:00.000-07:002016-04-29T08:23:36.078-07:00MMU section translation faultWhile working on a ZedBoard (perhaps also MicroZed and others) you may find yourself facing a message referring to <b><i>MMU section translation fault</i></b>. This has happened to me a couple times. In my experience it's because I'm attempting to launch a bare metal application to the PS while the board has already booted to Linux--so the MMU is likely already in use.
My solution:
<ul>
<li>Remove the Linux SD card (from which the board is booting) from the slot and reset the board</li>
<li>Program the PL (FPGA) again</li>
<li>Launch your bare metal application again.</li>
</ul>
Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-24197057438725730502016-01-10T15:49:00.000-08:002016-01-10T15:50:34.616-08:00Atmel Studio 7 incompatibility with Visual Studio 2015 Update 1<p>I spent a bit of time baffled after installing Atmel Studio 7.0.634 as I couldn't even create a new project successfully. This appears to be an incompatibility with Visual Studio 2015 Update 1. I found an apparent solution to the issue <a href="http://www.mikrocontroller.net/topic/385112#4418999" target="_blank">here</a>, which manages to get me past my issues with creating a project. I'm not exactly sure why Atmel Studio has so many binding redirects, but there it is.</p>
<p>
<em>Sample error message: The 'ErrorListPackage' package did not load correctly.</em>
</p>
<script src="https://gist.github.com/curtnichols/2d76c33b9dcc65704e53.js"></script>
Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-13013104449058405922015-06-09T22:08:00.000-07:002015-06-10T16:00:33.852-07:00ZedBoard button bit assignmentsFuture self,<br />
<br />
Here are the bit assignments for the five momentary switches on the ZedBoard, as found by experimentation, for your future reference should you ever wish to use them w/GPIO again:<br />
<br />
<span style="font-family: Courier New, Courier, monospace;">#define BUTTON_CENTER 0x01</span><br />
<span style="font-family: Courier New, Courier, monospace;">#define BUTTON_DOWN 0x02</span><br />
<span style="font-family: Courier New, Courier, monospace;">#define BUTTON_LEFT 0x04</span><br />
<span style="font-family: Courier New, Courier, monospace;">#define BUTTON_RIGHT 0x08</span><br />
<span style="font-family: Courier New, Courier, monospace;">#define BUTTON_UP 0x10</span><br />
<div>
<br /></div>
Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-34066397874930284832015-06-09T08:30:00.000-07:002015-06-10T16:01:54.566-07:00How to undo (almost) anything with Gitvia GitHub.com:<br />
<br />
https://github.com/blog/2019-how-to-undo-almost-anything-with-git<br />
<br />Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-22043256770687651182015-05-31T21:17:00.001-07:002015-05-31T21:17:39.486-07:00DetoursThis evening I put together an app using an Adafruit <a href="http://www.adafruit.com/products/189">PIR (motion) sensor</a> on Win10 for IoT on Raspberry Pi 2. It <i>almost</i> worked the first time, but edge detection in the ValueChanged event on GpioPin gets its value inverted at times. Turns out it's a known issue. My workaround: in the event handler use sender.Read() to get the pin value.<br />
<br />
I'll be glad to see this fixed.<br />
<br />
Oh, also--the motion sensor prefers 5V over 3.3V. Just sayin'.Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-7008329548720573142015-05-03T14:45:00.000-07:002015-05-03T14:45:00.570-07:00Enable "Developer Mode" on Windows 10 build 10074Here's the trick as currently documented <a href="https://msdn.microsoft.com/library/windows/apps/xaml/dn706236.aspx?f=255&MSPPError=-2147217396#GroupPolicy">here</a>, as the method to do so through the settings window do not work (for me, Settings, For Developers crashes the settings application):<br />
<br />
<br />
<blockquote class="tr_bq">
<strong>For Windows 10 desktop</strong><br />
Use gpedit.msc to set the group policies to enable your device, unless you have Windows 10 Insider Preview Home Edition. If you do have Home Edition, you need to use regedit or PowerShell commands to set the registry keys directly to enable your device.<br />
<div class="proch">
<img alt="Dn706236.wedge(en-us,WIN.10).gif" class="cl_IC153696" id="wedge" src="https://i-msdn.sec.s-msft.com/areas/global/content/clear.gif" title="Dn706236.wedge(en-us,WIN.10).gif" xmlns="" /><strong>Use gpedit to enable your device</strong></div>
<ol>
<li>Open a cmd prompt with administrator privileges.</li>
<li>Run <strong>Gpedit.msc</strong>.</li>
<li>Go to <strong>Local Computer Policy > Computer Configuration > Administrative Templates > Windows Components > App Package Deployment</strong></li>
<li>Edit the policies to enable the following:<ul>
<li><strong>Allow all trusted apps to install </strong>(Enables your device for <a href="http://go.microsoft.com/fwlink/p/?linkid=253132">sideloading</a> apps)</li>
<li><strong>Allows development of Windows Store apps and installing them from an integrated development environment (IDE)</strong> (Enables your device for development from Visual Studio) </li>
</ul>
</li>
<li> Reboot your machine.</li>
</ol>
</blockquote>
<br />
<br />
Other methods to do so using regedit and PowerShell are found at the same link.Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-50655898957867356562015-04-06T12:10:00.000-07:002015-04-06T12:10:00.064-07:00Upping Raspberry Pi 2's power to the USB portsInteresting post on upping the Raspberry Pi 2's power to the USB ports. Out of the box the USB peripherals are limited to 600mA.<br />
<br />
http://hackaday.com/2015/04/06/more-power-for-raspberry-pi-usb-ports/<br />
<br />Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-51342529387184109292015-04-03T19:00:00.000-07:002015-04-03T19:00:02.339-07:00Raspberry Pi, Quite ExcitingAs I write this i am installing an operating system image on the microSD card of a Raspberry Pi that just arrived. I'm rather surprised at the level of excitement that I feel waiting for it to complete.<br />
<br />
Unpacking the Pi reminds me of days long ago when our Atari 800 arrived and shortly thereafter came BASIC, PEEK, POKE, and some 6502 assembler. Yes, 8 KB of RAM, that was living high on the hog. I later parlayed my meager 6502 experience into building a graphical supply-side economics demonstration on the Apple II in high school. Those were the days. (Today, my work machine has 16 GB of RAM--2 million times as much--mostly taken up by web browser programs....)<br />
<br />
I expect in coming weeks, as I find time, I'll perform amazing feats such as making an LED light up (no code!) and making an LED flash (a little Python code!) and then doing the same in C++ (okay, where is the right header file?!).<br />
<br />
How far will this go? Multiple LEDs of different colors? Multiple concurrent LEDs flash patterns? Wait, can I use the Boost libraries? I bet I can. :) Only time will tell.<br />
<br />Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-12788971099546923742014-07-08T11:11:00.000-07:002014-07-08T11:11:00.805-07:00WPF Binding DiagnosticsNote to self: when trying to diagnose WPF binding issues, and you want more debug spew, here's that attached property you can't remember:<br />
<br />
<a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.presentationtracesources.tracelevel.aspx">PresentationTraceSources.TraceLevel</a><br />
<br />
Good luck!Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-27628409975913358862014-07-05T18:20:00.000-07:002014-07-05T18:20:00.795-07:00Check yourselfI am humored occasionally at (what I assume is) the rush to get things deployed and the bugs that inevitably appear. Here's a portion of Garmin's "modern" interface for http://connect.garmin.com/ :<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghB6yhjqzP3vBA76vmdMCe8CyZVLFXina2KqE67snGLLHz3Un3NfwOp6xcUU64ChQYHzFeQWIPCr6Kostluwc6z_RvTBNOl3AgVs8BbQcRMis4VXC1Mfn0NdQ6V9exYUUdceUM9Q/s1600/garming+calendar+null.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEghB6yhjqzP3vBA76vmdMCe8CyZVLFXina2KqE67snGLLHz3Un3NfwOp6xcUU64ChQYHzFeQWIPCr6Kostluwc6z_RvTBNOl3AgVs8BbQcRMis4VXC1Mfn0NdQ6V9exYUUdceUM9Q/s1600/garming+calendar+null.png" /></a></div>
<div>
<br /></div>
<div>
"Null" indeed. I suppose I can't complain too much, as I can't really tell what "items" are supposed to appear in this pane. Plenty of options in the contextual menu, but no obvious guidance as to putting things there. :)</div>
<div>
<br /></div>
<div class="separator" style="clear: both; text-align: center;">
<a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUCwAI-Lk_-PBxbi97C5MKhTHFmUPkwjQY4ygoAAy3hyzcWxX4aJjqb38dNtYPNkhPhn3oM8C3DeZtd7rO_csEOsunxJHj0KlV6YsgNGWperrsKG_70iHGz4p7zlB4tx8mBwj8fg/s1600/garming+calendar+null+2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjUCwAI-Lk_-PBxbi97C5MKhTHFmUPkwjQY4ygoAAy3hyzcWxX4aJjqb38dNtYPNkhPhn3oM8C3DeZtd7rO_csEOsunxJHj0KlV6YsgNGWperrsKG_70iHGz4p7zlB4tx8mBwj8fg/s1600/garming+calendar+null+2.png" /></a></div>
<div>
<br /></div>
Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com1tag:blogger.com,1999:blog-19212077.post-84783809428781754532014-06-23T21:28:00.000-07:002014-06-23T21:53:26.286-07:00Where does legacy code come from?<span style="font-size: x-large;"><b>Q</b>:</span> Where does legacy code come from, anyway?<br />
<br />
<span style="font-size: x-large;"><b>A</b>:</span> Oh, boy.... Well, you know that code you so lovingly crafted <i>today</i>? That's <i>tomorrow's </i>legacy code.Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-4256859794776959362013-11-23T07:40:00.001-08:002013-11-23T07:40:36.183-08:00Portable Class Libraries in F#Just ran across <a href="http://msdn.microsoft.com/en-us/library/vstudio/dd233169.aspx">Using Visual Studio to Write F# Programs</a>, specifically the section "Portable Libraries in F#," which answers a question I had the other day:<br />
<br />
<blockquote class="tr_bq">
Which version of FSharp.Core.dll should I reference in projects that reference my F# PCL assembly?</blockquote>
<br />
The link above answers that.<br />
<br />
<br />Curthttp://www.blogger.com/profile/12700204233463274869noreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-45481002638849783162007-12-03T12:18:00.001-08:002007-12-03T12:18:42.516-08:00Where Did My Object Go? Part 2<p>In <a href="http://www.codeneverwritten.com/2007/12/where-did-my-object-go-part-1.html" target="_blank">Part 1</a> of this article I discussed the possibility of an object instance being collected before a method returns in this scenario:</p><pre class="code"> <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">MyObject</span>().LongRunningMethod();<br /></pre><br /><p>as well as this scenario:</p><pre class="code"> <span style="color: rgb(43,145,175)">MyObject</span> o = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">MyObject</span>();<br /> o.LongRunningMethod();<br /></pre><br /><p>Here we'll discuss how this could become a problem. Frankly, it's pretty easy to cause the problem, but I think it generally involves some ugliness on the part of software design or implementation, largely involving clean-up of fields when the instance is finalized.</p><br /><h3>Don't Try This at Home</h3><br /><p>I don't think it's likely you'll see a lot of code that does this, but here's one way to run afoul of your object going way: export a reference to a field that the object cleans up when it's finalized. You can export the reference, say, by making that field visible through a property. Exposing a field that you're going to clean up in the finalizer would be an easy way to create a coupling between your object and other (arbitrary) client code that has no knowledge of your object's life span.</p><br /><h3>Call Stack Antics</h3><br /><p>Another way to invoke the potential problem is to lose your "this" reference on the call stack. The code below manages to lose the "this" reference by passing a field to the helper method rather than allowing the helper to access the field directly via its own "this" reference. When the helper tries to access <font face="Courier New">fs.Length</font> an <font face="Courier New">ObjectDisposedException</font> is thrown. </p><br /><p>Why does this throw? Well, the last live reference to the instance was lost when <font face="Courier New">LongRunningMethod</font> passed <font face="Courier New">_input</font> to <font face="Courier New">Helper</font>. Essentially we've again exported the field value from the instance and no longer hold a reference to the instance, allowing the GC to finalize it. <font face="Courier New">Helper</font> is left holding a reference to an object that has been finalized.</p><a href="http://11011.net/software/vspaste"></a><br /><p><strong>Note:</strong> Again, you will not see this behavior in a debug build. When running code marked as "debug" the JITter <a href="http://blogs.msdn.com/yunjin/archive/2005/05/15/417569.aspx" target="_blank">extends the lifetime</a> of the local object to the end of the method. So you will not see this effect if you've compiled with the /debug flag. </p><pre class="code"> <span style="color: rgb(0,0,255)">using</span> System;<br /> <span style="color: rgb(0,0,255)">using</span> System.IO;<br /><br /> <span style="color: rgb(0,128,0)">// Ugliness ensues.<br /></span> <span style="color: rgb(0,0,255)">sealed</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">MyUglyObject<br /></span> {<br /> <span style="color: rgb(0,0,255)">public</span> MyUglyObject(<span style="color: rgb(0,0,255)">string</span> inputPath)<br /> {<br /> <span style="color: rgb(0,128,0)">// Real production code would likely not delete the file when done...<br /></span> <span style="color: rgb(0,128,0)">// ...but this is a sample app.<br /></span> _input = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">FileStream</span>(<span style="color: rgb(43,145,175)">Path</span>.GetTempFileName(), <span style="color: rgb(43,145,175)">FileMode</span>.Open, <span style="color: rgb(43,145,175)">FileAccess</span>.Read, <span style="color: rgb(43,145,175)">FileShare</span>.Read);<br /> }<br /><br /> ~MyUglyObject()<br /> {<br /> <span style="color: rgb(0,0,255)">if</span> (_input != <span style="color: rgb(0,0,255)">null</span>)<br /> {<br /> _input.Close();<br /> _input = <span style="color: rgb(0,0,255)">null</span>;<br /> }<br /> }<br /><br /> <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span> LongRunningMethod()<br /> {<br /> Helper(_input); <span style="color: rgb(0,128,0)">// Our last reference to 'this' (implicit).<br /></span> }<br /><br /> <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">void</span> Helper(<span style="color: rgb(43,145,175)">FileStream</span> fs)<br /> {<br /> <span style="color: rgb(0,128,0)">// A long-running method can easily experience a garbage collection <br /></span> <span style="color: rgb(0,128,0)">// before returning. This one happens for force it to occur.<br></span> <span style="color: rgb(43,145,175)">GC</span>.Collect();<br /> <span style="color: rgb(43,145,175)">GC</span>.WaitForPendingFinalizers();<br /><br /> <span style="color: rgb(0,128,0)">// Ka-boom!<br /></span> <span style="color: rgb(0,0,255)">long</span> inputSize = fs.Length;<br /> <span style="color: rgb(0,128,0)">// ...<br /></span> }<br /><br /> <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(43,145,175)">FileStream</span> _input;<br /> }<br /><br /> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">Program<br /></span> {<br /> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">void</span> Main(<span style="color: rgb(0,0,255)">string</span>[] args)<br /> {<br /> <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">MyUglyObject</span>(<span style="color: rgb(163,21,21)">@"..\..\readme.txt"</span>).LongRunningMethod();<br /> }<br /> }<br /></pre><a href="http://11011.net/software/vspaste"></a><br /><h3>Can You See It?</h3><br /><p>As you can see above it takes a bit of effort to cause the code to blow up. If <font face="Courier New">Helper</font> had used <font face="Courier New">_input.Length</font> instead of taking a parameter the problem would not exist.</p><br /><p>But, what I find a bit creepy about the above code is that if <font face="Courier New">Helper</font> were a static method it would seem respectable:</p><pre class="code"> <span style="color: rgb(0,0,255)">private</span> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">void</span> Helper(<span style="color: rgb(43,145,175)">FileStream</span> fs)<br /> {<br> <span style="color: rgb(0,128,0)">// A long-running method can easily experience a garbage collection <br /></span> <span style="color: rgb(0,128,0)">// before returning. This one happens for force it to occur.<br></span> <span style="color: rgb(43,145,175)">GC</span>.Collect();<br /> <span style="color: rgb(43,145,175)">GC</span>.WaitForPendingFinalizers();<br /><br /> <span style="color: rgb(0,128,0)">// Ka-boom!<br /></span> <span style="color: rgb(0,0,255)">long</span> inputSize = fs.Length;<br /> <span style="color: rgb(0,128,0)">// ...<br /></span> }</pre><a href="http://11011.net/software/vspaste"></a><br /><p>At first glance it now looks like helper is a normal static helper function, as is likely seen in code bases across the world. It doesn't need a "this" reference, it takes a reference to the object it uses, everything appears fine on the surface. Would you see the "this" reference being lost by the code calling <font face="Courier New">Helper</font> in a code review? I'm not so sure I would have until recently. </p><br /><p> </p><br /><p> </p><br /><div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:5ab9e4f3-aaea-4ce5-83ea-be553bd2b340" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati tags: <a href="http://technorati.com/tags/Coding" rel="tag">Coding</a>, <a href="http://technorati.com/tags/Software%20Design" rel="tag">Software Design</a>, <a href="http://technorati.com/tags/CLR" rel="tag">CLR</a>, <a href="http://technorati.com/tags/C#" rel="tag">C#</a>, <a href="http://technorati.com/tags/Code%20Review" rel="tag">Code Review</a></div> Unknownnoreply@blogger.com3tag:blogger.com,1999:blog-19212077.post-79529222606337182062007-12-03T11:14:00.001-08:002007-12-03T12:19:21.637-08:00Where Did My Object Go? Part 1<p>I ran across this scenario a few months ago and was just <a href="http://channel9.msdn.com/ShowPost.aspx?PostID=362232#362232" target="_blank">reminded</a> of it. It takes a bit of an edge case to make it a problem, but it's interesting all the same.</p> <p>There's a regular idiom in C# in which we call a method on an object instance that we've created inline:</p><pre class="code"> <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">MyObject</span>().LongRunningMethod();<br /></pre><br /><p>There assumption may be an assumption that the lifetime of this instance of <span style="color: rgb(43,145,175)"><font face="Courier New">MyObject</font></span> extends at least until <font face="Courier New">LongRunningMethod</font> returns, but this isn't necessarily true. This same assumption is often made about local references to objects:</p><pre class="code"> <span style="color: rgb(43,145,175)">MyObject</span> o = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">MyObject</span>();<br /> o.LongRunningMethod();<br /></pre><br /><p><a href="http://11011.net/software/vspaste"></a>However, in both these cases the object instance may be collected before <font face="Courier New">LongRunningMethod</font> returns.</p><br /><h3>Does this really happen?</h3><br /><p>Yes, it can and does. The code below exercises this behavior. When you run it you will see the following output, indicating that the object was collected and finalized before <font face="Courier New">LongRunningMethod</font> returns:</p><br /><p><font face="Courier New" color="#008000"> Using release build<br></font><font face="Courier New" color="#008000"> Inline<br> Entering MyObject1.LongRunningMethod().<br> Finalizing in ~MyObject1().<br> Returning from MyObject1.LongRunningMethod(). </font><br /><p><font face="Courier New" color="#008000"> Local reference<br> Entering MyObject1.LongRunningMethod().<br> Finalizing in ~MyObject1().<br> Returning from MyObject1.LongRunningMethod().</font> <br /><p><strong>Note:</strong> You will not see this behavior in a debug build. When running code marked as "debug" the JITter <a href="http://blogs.msdn.com/yunjin/archive/2005/05/15/417569.aspx" target="_blank">extends the lifetime</a> of the local object to the end of the method. So you will <u>not</u> see this effect if you've compiled with the /debug flag.</p><br /><p>Note also that this article also assumes we're using CLR 2.0. Future versions could obviously behavior differently.</p><br /><p>Here's the code. Just drop it into <font face="Courier New">test.cs</font>, run <font face="Courier New">csc test.cs</font>, and execute <font face="Courier New">test.exe</font>.</p><pre class="code"> <span style="color: rgb(0,0,255)">using</span> System;<br /><br /> <span style="color: rgb(0,0,255)">sealed</span> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">MyObject<br /></span> {<br /> ~MyObject()<br /> {<br /> <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"Finalizing in ~MyObject1()."</span>);<br /> }<br /><br /> <span style="color: rgb(0,0,255)">public</span> <span style="color: rgb(0,0,255)">void</span> LongRunningMethod()<br /> {<br /> <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"Entering MyObject1.LongRunningMethod()."</span>);<br /><br /> <span style="color: rgb(0,128,0)">// A long-running method can easily experience a garbage collection <br /></span> <span style="color: rgb(0,128,0)">// before returning. This one happens for force it to occur.<br /></span> <span style="color: rgb(43,145,175)">GC</span>.Collect();<br /> <span style="color: rgb(43,145,175)">GC</span>.WaitForPendingFinalizers();<br /><br /> <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"Returning from MyObject1.LongRunningMethod()."</span>);<br /> }<br /> }<br /><br /> <span style="color: rgb(0,0,255)">class</span> <span style="color: rgb(43,145,175)">Program<br /></span> {<br /> <span style="color: rgb(0,0,255)">static</span> <span style="color: rgb(0,0,255)">void</span> Main(<span style="color: rgb(0,0,255)">string</span>[] args)<br /> {<br /><span style="color: rgb(0,0,255)"> #if</span> DEBUG<br /><span style="color: rgb(128,128,128)"> string build = "debug";<br /></span><span style="color: rgb(0,0,255)"> #else<br /></span> <span style="color: rgb(0,0,255)">string</span> build = <span style="color: rgb(163,21,21)">"release"</span>;<br /><span style="color: rgb(0,0,255)"> #endif<br /></span> <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"Using {0} build"</span>, build);<br /><br /> <span style="color: rgb(0,128,0)">// Try it both ways.<br /><br /></span> <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"Inline"</span>);<br /> <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">MyObject</span>().LongRunningMethod();<br /><br /> <span style="color: rgb(43,145,175)">Console</span>.WriteLine();<br /> <span style="color: rgb(43,145,175)">Console</span>.WriteLine(<span style="color: rgb(163,21,21)">"Local reference"</span>);<br /> <span style="color: rgb(43,145,175)">MyObject</span> o = <span style="color: rgb(0,0,255)">new</span> <span style="color: rgb(43,145,175)">MyObject</span>();<br /> o.LongRunningMethod();<br /> }<br /> }<br /></pre><br /><h3>Is this a problem?</h3><br /><p>Generally, I'd say it's not a problem. Once it has begun execution, <font face="Courier New">LongRunningMethod</font> doesn't need the original object reference unless it's making reference to that instance. In that case the GC won't be able to collect the object.</p><br /><p>I'll discuss how to make it a problem in <a href="http://www.codeneverwritten.com/2007/12/where-did-my-object-go-part-2.html" target="_blank">Part 2</a> of this article.</p><br /><p> </p><br /><div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:24332e3e-fe71-48b6-a509-a0c9cac22dcd" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati tags: <a href="http://technorati.com/tags/Coding" rel="tag">Coding</a>, <a href="http://technorati.com/tags/Software%20Design" rel="tag">Software Design</a>, <a href="http://technorati.com/tags/CLR" rel="tag">CLR</a>, <a href="http://technorati.com/tags/C#" rel="tag">C#</a></div> Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-87150263864617741432007-11-28T20:03:00.001-08:002007-11-28T20:03:14.815-08:00File. Close. No!<p>I enjoyed listening to Scott Hanselman's podcast <a href="http://www.hanselminutes.com/default.aspx?showID=107" target="_blank">interview of Larry Osterman</a> today. Larry has been working at Microsoft for more than 23 years now and usually has words of interest to software developers <a href="http://blogs.msdn.com/larryosterman/" target="_blank">on his blog</a>.</p> <p>As the discussion turned to security issues I was reminded of a security issue I pointed out to a colleague back in, well, I believe it was the first half of the 90's. The issue: the attack vector brought about by speaker-independent voice recognition. The scenario: the disgruntled office worker running through the cubicle farm, shouting "File. Close. No! File. Close. No!"</p> <p>It amuses me to think that perhaps the new ribbon-and-pearl command structure of Office 2007 apps has gone a long way in negating that issue. :)</p> <p> </p> <div class="wlWriterSmartContent" id="scid:0767317B-992E-4b12-91E0-4F059A8CECA8:2d74803d-abce-427d-8dda-877b05b4be99" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati tags: <a href="http://technorati.com/tags/Security" rel="tag">Security</a></div> Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-86638482328019103902007-06-22T20:09:00.001-07:002007-06-22T20:09:28.933-07:00Whither Orcas?<p>I've been perusing <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=17319EB4-299C-43B8-A360-A1C2BD6A421B&displaylang=en" target="_blank">An Overview of Microsoft Visual Studio Code Name "Orcas" White Paper</a> with a curiosity known only to those who are curious about what will ship in the Visual Studio "Orcas" release. :) I am intrigued. In the three areas in which Orcas purports to deliver key advances, I'm most intrigued with the third:</p> <ul> <li>Improve Developer Productivity <li>Manage the Application Life Cycle <li>Employ the Latest Technologies</li></ul> <p>After all, true geeks are more interested in the latest technologies than in process, right? :) Of interest to me in the Orcas release of Visual Studio, I see:</p> <p><strong>LINQ</strong> (pp. 8,13)</p> <p>I admit I'm a bit of a Luddite when it comes to language features. It took me a while to see that C#'s "using" syntax was clearly a good thing. What do you expect from a C++ developer whose first C++ compiler was a <em><a href="http://en.wikipedia.org/wiki/Cfront" target="_blank">cfront</a></em> translator--we didn't have C++ compilers back then. Don't give me syntactic sugar--let me do it the hard way! Give me a preprocessor!</p> <p>All the same, LINQ seems to be a boon to anyone who wants to query over structured data. I'll likely adopt it in (personal) record time.</p> <p><strong>Further support for building WPF applications</strong> (pp. 5, 19)</p> <p>Debugging support for WPF. I have to wonder what that will look like. Will I be able to step through XAML?</p> <p><strong>New APIs in Window Vista</strong> (p. 6)</p> <p>Seriously, are there really "more than 8,000 new native APIs available in Windows Vista?" My brain hurts. Maybe I need to buy a llama farm and learn to live the simple life. I mean, I started programming Windows code in 1991. That's later than many, earlier than most. Dear God, I even digested <a href="http://msdn.microsoft.com/archive/default.asp?url=/archive/en-us/dnarolegen/html/msdn_aboutole.asp" target="_blank">Kraig Brockschmidt's book, Inside OLE2</a>! Gah! Is my brain going to fill up and return E_OUTOFMEMORY? And will that be a fatal error?! :)</p> <p><strong>New managed add-in model</strong> (pp. 14, 16)</p> <p>I've seen some tough questions asked about how to control the impact of rogue add-ins in a managed application. The <a href="http://blogs.msdn.com/clraddins/default.aspx">CLR Add-In Team Blog</a> indicates someone at Microsoft is working at <a href="http://blogs.msdn.com/clraddins/archive/2007/01/12/welcome-to-the-clr-add-in-team-blog.aspx" target="_blank">addressing these issues</a>, as does this white paper.</p> <p><strong>Lightweight reader/writer lock with deadlock-free upgrade support</strong> (p. 14)</p> <p>Hmm, a slimmed-down read-writer lock that doesn't support recursion. This sounds a bit like what Jeffrey Richter describes in CLR via C# (second edition, pages 642-643). I can't wait to compare Richter's version in <a href="http://www.wintellect.com/" target="_blank">Wintellect's</a> Power Threading library with what Reflector tells me about Orcas' System.Threading.ReaderWriterLockSlim. It should be an educational experience. :)</p> <p><strong>New IO types that expose almost all pipe functionality provided by Windows</strong> (p. 15)</p> <p>It's about time. :)</p> <p><strong>A trace listener for ETW</strong> (p. 16)</p> <p>Woot! High-perf event tracing!</p> <p><strong>Peer Networking Classes</strong> (p. 17)</p> <p>I don't know how much of the <a href="http://msdn.microsoft.com/msdnmag/issues/06/10/PeerToPeer/" target="_blank">P2P</a> APIs this might encompass, but it's definitely an area I'll be experimenting with. I expect we'll be seeing some very cool apps born out of this space. Apps we haven't thought of yet.</p> <p> </p> <p>Woof. As usual my eyes are bigger than my stomach. I hope to have time to explore at least a few of these areas. :)</p> <div class="wlWriterSmartContent" id="0767317B-992E-4b12-91E0-4F059A8CECA8:46efead3-a2eb-4ab3-ae29-1c7fcd0210e9" contenteditable="false" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati tags: <a href="http://technorati.com/tags/LINQ" rel="tag">LINQ</a>, <a href="http://technorati.com/tags/WPF" rel="tag">WPF</a>, <a href="http://technorati.com/tags/Vista" rel="tag">Vista</a>, <a href="http://technorati.com/tags/ETW" rel="tag">ETW</a>, <a href="http://technorati.com/tags/Peer%20Networking" rel="tag">Peer Networking</a></div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-70555544236004846372007-06-22T17:58:00.001-07:002007-06-22T18:10:19.619-07:00Moving On...<p>It's that time again, when one contract ends and another begins. I'm never able to wrap up all the loose ends that I'd like to.</p> <p>Yet it's a bit renewing, helping one project through RTM and SP1, then picking up and beginning fresh on something totally different with a completely different set of people. It's interesting how from one project to the next people vary so much. It's like they're wired differently. :)</p> <p>Aside from the pleasure of meeting and working with new people, I also enjoyed this view from my desk in recent months. (Sorry about the cell phone picture quality.) Can you find the Space Needle?</p> <p align="center"><a href="http://www.codeneverwritten.com/images/MovingOn_F772/fs_view.jpg" atomicselection="true"><img style="border-top-width: 0px; border-left-width: 0px; border-bottom-width: 0px; border-right-width: 0px" height="240" alt="The view from my desk" src="http://www.codeneverwritten.com/images/MovingOn_F772/fs_view_thumb.jpg" width="320" border="0"></a> </p> <p>If experience is any indication my desk at my next assignment will likely face a beige wall in building 41 instead of downtown Seattle. But it involves some pretty cool software. Oh, well, you take the good with the bad. :)</p> <div class="wlWriterSmartContent" id="0767317B-992E-4b12-91E0-4F059A8CECA8:55b675e8-0c24-4aba-b998-de6e22be35b2" contenteditable="false" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati tags: <a href="http://technorati.com/tags/Contracting" rel="tag">Contracting</a>, <a href="http://technorati.com/tags/Seattle" rel="tag">Seattle</a></div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-33847926290105759682007-02-15T14:09:00.001-08:002007-02-15T14:09:06.727-08:00C#: Type issues with ref parameters<p>I've witnessed a few instances where programmers have tripped up on types when using C#'s <font face="Courier New">ref</font> parameters. Here's <a title="Casting error in VS2005" href="http://channel9.msdn.com/ShowPost.aspx?PostID=283089" target="_blank">a post illustrating this</a>. The temptation is to think that because one can assign a derived type to a base type reference that the same should work with C#'s <font face="Courier New" color="#000080">ref</font> and <font face="Courier New" color="#000080">out</font> parameters.</p> <p>It doesn't. It's simply not type safe.</p> <h3>The Problem</h3> <p>Here are the types from the above-mentioned post; I've added the <font face="Courier New">FavoriteColor</font> property for later discussion:</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"> <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Contact</span></p> <p style="margin: 0px"> {</p> <p style="margin: 0px"> }</p> <p style="margin: 0px"> </p> <p style="margin: 0px"> <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Recipient</span> : <span style="color: #2b91af">Contact</span></p> <p style="margin: 0px"> {</p> <p style="margin: 0px"> <span style="color: blue">public</span> <span style="color: blue">string</span> FavoriteColor { <span style="color: blue">get</span> { <span style="color: blue">return</span> <span style="color: #a31515">"Alice Blue"</span>; } }</p> <p style="margin: 0px"> }</p></div> <p>For discussion's sake, here's the declaration of the method in question:</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"> <span style="color: blue">bool</span> FetchContact(<span style="color: blue">ref</span> <span style="color: #2b91af">Contact</span> contact, <span style="color: blue">uint</span> row);</p></div> <p><font face="Courier New">FetchContact</font>'s signature indicates that it can return a <font face="Courier New">Contact</font> via the <font face="Courier New">contact</font> parameter.</p> <p>And now the code the poster wants to use:</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"> <span style="color: #2b91af">Recipient</span> recipient = <span style="color: blue">new</span> <span style="color: #2b91af">Recipient</span>();</p> <p style="margin: 0px"> FetchContact(<span style="color: blue">ref</span> (<span style="color: #2b91af">Contact</span>)recipient, row);</p></div> <p>It certainly appears that the calling code desires to get a <font face="Courier New">Recipient</font> from the call to <font face="Courier New">FetchContact</font>, but that's not within the interface contract of <font face="Courier New">FetchContact</font>. <font face="Courier New">FetchContact</font> returns a <font face="Courier New">Contact </font>via its <font face="Courier New">contact ref</font> parameter.</p> <h3>Try, Try Again</h3> <p>Now, it's true that the following fragment of code works; it adheres to the interface contract specified by <font face="Courier New">FetchContact</font>:</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"> <span style="color: #2b91af">Recipient</span> recipient = <span style="color: blue">new</span> <span style="color: #2b91af">Recipient</span>();</p> <p style="margin: 0px"> <span style="color: #2b91af">Contact</span> contact = recipient;</p> <p style="margin: 0px"> <span style="color: #2b91af">Fetcher</span>.FetchContact(<span style="color: blue">ref</span> contact, row);</p></div> <p>Well, of course that works, we've modified the code to pass a <font face="Courier New">ref Contact</font> as specified by the method signature. But why doesn't the first?</p> <h3>Type Safety</h3> <p>Let's try a different tack. To simplify, ignore for the moment that we're looking at a <font face="Courier New">ref</font> parameter. Instead, consider it an <font face="Courier New">out</font> parameter. And we'll also assume that there are more types derived from <font face="Courier New">Contact</font>, for example:</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"> <span style="color: blue">public</span> <span style="color: blue">class</span> <span style="color: #2b91af">Sender</span> : <span style="color: #2b91af">Contact</span></p> <p style="margin: 0px"> {</p> <p style="margin: 0px"> }</p></div> <p>Now, consider again, what type <font face="Courier New">FetchContact</font> is returning here as an <font face="Courier New">out</font> parameter?</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"> <span style="color: #2b91af">Contact</span> contact = recipient;</p> <p style="margin: 0px"> <span style="color: #2b91af">Fetcher</span>.FetchContact(<span style="color: blue">out</span> contact, row);</p></div> <p>The correct answer is "We're not sure." <font face="Courier New">FetchContact</font> could return a <font face="Courier New">Contact</font>, a <font face="Courier New">Recipient</font>, a <font face="Courier New">Sender</font>, or any other type derived from <font face="Courier New">Contact</font>. The problem of the original code is that it assumes that <font face="Courier New">FetchContact</font> is returning a <font face="Courier New">Recipient</font> and tries to coerce the type. This would not be typesafe as we don't know that the object returned is actually a <font face="Courier New">Recipient</font>. </p> <p>Consider what happens when <font face="Courier New">FetchContact</font> is (legally) implemented like this:</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"> <span style="color: blue">bool</span> FetchContact(<span style="color: blue">out</span> <span style="color: #2b91af">Contact</span> contact, <span style="color: blue">uint</span> row)</p> <p style="margin: 0px"> {</p> <p style="margin: 0px"> contact = <span style="color: blue">new</span> <span style="color: #2b91af">Sender</span>();</p> <p style="margin: 0px"> <span style="color: blue">return</span> <span style="color: blue">true</span>;</p> <p style="margin: 0px"> }</p></div> <p>The object passed back to the caller is obviously a <font face="Courier New">Sender</font>, not a <font face="Courier New">Recipient</font>. The only way for the caller to treat the returned value as a <font face="Courier New">Recipient</font> is to break type safety, and C# generally does not let one do this.</p> <h3>Hypothetically Speaking...</h3> <p>What if C# did let us ignore type safety? Let's suppose that this code could compile and execute:</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"> <span style="color: #2b91af">Recipient</span> recipient = <span style="color: blue">new</span> <span style="color: #2b91af">Recipient</span>();</p> <p style="margin: 0px"> <span style="color: #2b91af">Fetcher</span>.FetchContact(<span style="color: blue">out</span> (<span style="color: #2b91af">Contact</span>)recipient, row);</p> <p style="margin: 0px"> </p> <p style="margin: 0px"> <span style="color: blue">string</span> fave = recipient.FavoriteColor;</p></div> <p>Now <font face="Courier New">FetchContact</font> has returned a <font face="Courier New">Sender</font> that we've coerced into a <font face="Courier New">Recipient</font> reference. Not good. It might execute right up until we use the <font face="Courier New">FavoriteColor</font> property. Think about it. <font face="Courier New">FetchContact</font> returns an instance of <font face="Courier New">Sender</font>, which we're treating as a <font face="Courier New">Recipient</font>. But the <font face="Courier New">Sender</font> type doesn't have a FavoriteColor property. What would happen then? It would surely crash or return invalid data, just as we would see in C++.</p> <p>C# prefers type safety and doesn't allow this to happen. That's a good thing.</p> <h3>But it's a ref, Not an out Parameter</h3> <p>I believe this is the cause of the confusion around this issue. <font face="Courier New">ref</font> parameters are both <font face="Courier New">in</font> and <font face="Courier New">out</font> parameters. Noone would mind if we passed a <font face="Courier New">Recipient</font> instead of a <font face="Courier New">Contact</font> as an <font face="Courier New"><u>in</u></font> parameter so why can't we do it here? Because <font face="Courier New">ref</font> parameters, like <font face="Courier New">out</font> parameters, have a stricter requirement: you cannot assume the returned type is a more derived type than the parameter's given type. To do so would not be type safe. The parameter in question <u>must</u> be a <font face="Courier New">ref Contact</font>.</p> <h3>But This Works in Other Languages</h3> <p>This <u>may</u> sometimes work in languages that allow you to subvert type safety (most famously C and C++). It <u>will</u> only work so long as you are lucky about your class layouts or your assumptions remain true. When either class layouts or your assumptions change your code will no longer work.</p> <p>Here's an example in C++. I run it in the debugger and it crashes on line 20 due to the type coercion done on line 41. This should not come as a surprise.</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"><span style="color: #2b91af"> 1</span> <span style="color: blue">#include</span> <span style="color: #a31515"><string></span></p> <p style="margin: 0px"><span style="color: #2b91af"> 2</span> <span style="color: blue">using</span> std::string;</p> <p style="margin: 0px"><span style="color: #2b91af"> 3</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 4</span> <span style="color: blue">class</span> Contact</p> <p style="margin: 0px"><span style="color: #2b91af"> 5</span> {</p> <p style="margin: 0px"><span style="color: #2b91af"> 6</span> <span style="color: blue">public</span>:</p> <p style="margin: 0px"><span style="color: #2b91af"> 7</span> <span style="color: blue">virtual</span> ~Contact() { }</p> <p style="margin: 0px"><span style="color: #2b91af"> 8</span> };</p> <p style="margin: 0px"><span style="color: #2b91af"> 9</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 10</span> <span style="color: blue">class</span> Recipient : <span style="color: blue">public</span> Contact</p> <p style="margin: 0px"><span style="color: #2b91af"> 11</span> {</p> <p style="margin: 0px"><span style="color: #2b91af"> 12</span> <span style="color: blue">public</span>:</p> <p style="margin: 0px"><span style="color: #2b91af"> 13</span> Recipient()</p> <p style="margin: 0px"><span style="color: #2b91af"> 14</span> : m_favoriteColor(<span style="color: #a31515">"Alice Blue"</span>)</p> <p style="margin: 0px"><span style="color: #2b91af"> 15</span> {</p> <p style="margin: 0px"><span style="color: #2b91af"> 16</span> }</p> <p style="margin: 0px"><span style="color: #2b91af"> 17</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 18</span> string GetFavoriteColor() <span style="color: blue">const</span></p> <p style="margin: 0px"><span style="color: #2b91af"> 19</span> {</p> <p style="margin: 0px"><span style="color: #2b91af"> 20</span> <span style="color: blue">return</span> m_favoriteColor;</p> <p style="margin: 0px"><span style="color: #2b91af"> 21</span> }</p> <p style="margin: 0px"><span style="color: #2b91af"> 22</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 23</span> <span style="color: blue">private</span>:</p> <p style="margin: 0px"><span style="color: #2b91af"> 24</span> <span style="color: blue">int</span> m_otherStuff[256];</p> <p style="margin: 0px"><span style="color: #2b91af"> 25</span> string m_favoriteColor;</p> <p style="margin: 0px"><span style="color: #2b91af"> 26</span> };</p> <p style="margin: 0px"><span style="color: #2b91af"> 27</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 28</span> <span style="color: blue">class</span> Sender : <span style="color: blue">public</span> Contact</p> <p style="margin: 0px"><span style="color: #2b91af"> 29</span> {</p> <p style="margin: 0px"><span style="color: #2b91af"> 30</span> };</p> <p style="margin: 0px"><span style="color: #2b91af"> 31</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 32</span> <span style="color: blue">void</span> FetchContact(<span style="color: blue">unsigned</span> row, Contact** ppContact)</p> <p style="margin: 0px"><span style="color: #2b91af"> 33</span> {</p> <p style="margin: 0px"><span style="color: #2b91af"> 34</span> *ppContact = <span style="color: blue">new</span> Sender();</p> <p style="margin: 0px"><span style="color: #2b91af"> 35</span> }</p> <p style="margin: 0px"><span style="color: #2b91af"> 36</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 37</span> <span style="color: blue">int</span> _tmain(<span style="color: blue">int</span> argc, _TCHAR* argv[])</p> <p style="margin: 0px"><span style="color: #2b91af"> 38</span> {</p> <p style="margin: 0px"><span style="color: #2b91af"> 39</span> Recipient* pRecipient;</p> <p style="margin: 0px"><span style="color: #2b91af"> 40</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 41</span> FetchContact(0, (Contact**)&pRecipient);</p> <p style="margin: 0px"><span style="color: #2b91af"> 42</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 43</span> string fave = pRecipient->GetFavoriteColor();</p> <p style="margin: 0px"><span style="color: #2b91af"> 44</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 45</span> <span style="color: blue">delete</span> pRecipient;</p> <p style="margin: 0px"><span style="color: #2b91af"> 46</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 47</span> <span style="color: blue">return</span> 0;</p> <p style="margin: 0px"><span style="color: #2b91af"> 48</span> }</p></div> <p> Hope that helps.</p>Unknownnoreply@blogger.com1tag:blogger.com,1999:blog-19212077.post-5358933043556395812007-02-01T08:26:00.001-08:002007-02-01T08:26:16.500-08:00Say (code) what you mean<p>A bright, shiny object caught my eye few weeks ago while I was hiking in the snowy Cascades. Upon investigation I found a saucer shaped craft glistening in the sun. It appeared to be a space travel-capable sort of vehicle with a translucent bubble-shaped canopy that had sprung open, apparently on impact with this planet. I peered into the craft and saw a gray-green being with a large head and eyes. This being appeared to be well-frozen and so, concluding that continuing my investigation would not disturb this being, I continued to poke around the strange craft a bit more.</p> <p>In what I would describe as a cockpit I found a something like a display panel which was flashing this message:</p> <blockquote> <p><font face="Courier New" color="#0000a0" size="2">Exception in thread "nav" java.lang.ClassCastException: java.lang.Double<br>at NavigationWaypoint.<init>(NavigationWaypoint.java:10)<br>at FindWaypoint.FindNextWaypoint(FindWaypoint.java:94)<br>...</font></p></blockquote> <p>Obviously this sparked my curiosity! In looking around the cockpit I discovered a bit of paper--more like mylar, really--clutched in what for now I'll call the unfortunate being's hand. I liberated this piece of paper and found printing on it. I was shocked to see what the paper showed:</p> <div style="font-size: 10pt; background: white; color: black; font-family: courier new"> <p style="margin: 0px"><span style="color: #2b91af"> 7</span> <span style="color: blue">class</span> NavigationWaypoint</p> <p style="margin: 0px"><span style="color: #2b91af"> 8</span> {</p> <p style="margin: 0px"><span style="color: #2b91af"> 9</span> <span style="color: blue">public</span> NavigationWaypoint(<span style="color: #2b91af">Object</span> name) {</p> <p style="margin: 0px"><span style="color: #2b91af"> 10</span> <span style="color: blue">this</span>.name = (<span style="color: #2b91af">String</span>)name;</p> <p style="margin: 0px"><span style="color: #2b91af"> 11</span> }</p> <p style="margin: 0px"><span style="color: #2b91af"> 12</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> 13</span> <span style="color: blue">public</span> <span style="color: #2b91af">String</span> getName() {</p> <p style="margin: 0px"><span style="color: #2b91af"> 14</span> <span style="color: blue">return</span> name;</p> <p style="margin: 0px"><span style="color: #2b91af"> 15</span> }</p> <p style="margin: 0px"><span style="color: #2b91af"> 16</span> </p> <p style="margin: 0px"><span style="color: #2b91af"> </span>...</p> <p style="margin: 0px"><span style="color: #2b91af"> 32</span> <span style="color: blue">private</span> <span style="color: #2b91af">String</span> name;</p> <p style="margin: 0px"><span style="color: #2b91af"> 33</span> }</p></div> <p>What a tragedy! Clearly the author of this code (presumably an inexperienced alien programmer) had errantly designed the instance constructor to take an Object rather than a String. In doing so the coder then needed a typecast in order to coerce the Object to a String in order to set the <em>name</em> field.</p> <p>I don't know about most, but on <em>my</em> planet such use of a typecast is a pretty strong clue that the programmer should look around to see why the typecast is necessary; it may be indicative of a design error.</p> <p>In fact, in this case it is a design error. The NavigationWaypoint class has a <em>name</em> field that contains a string, yet the constructor allows the caller to pass in an object of any type. This unfortunate error and the use of a typecast caused the error to manifest itself during execution of the code; obviously some other code passed in a Double rather than a String, probably a simple coding error. If the constructor had been coded to accept a String this coding error would have been caught at compile time rather than during execution, saving this little fellow the exasperation of debugging on the fly and waking up frozen on a strange planet. If only the constructor had been coded to correctly represent the type's data....</p> <p> </p> <p>(This post was inspired by a true story that had nothing to do with navigation.)</p> <p> </p> <div class="wlWriterSmartContent" id="0767317B-992E-4b12-91E0-4F059A8CECA8:a96d05ed-fed7-4f63-8e1f-73b5c1fb05ed" contenteditable="false" style="padding-right: 0px; display: inline; padding-left: 0px; float: none; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati tags: <a href="http://technorati.com/tags/Coding" rel="tag">Coding</a>, <a href="http://technorati.com/tags/Design" rel="tag">Design</a>, <a href="http://technorati.com/tags/Development" rel="tag">Development</a>, <a href="http://technorati.com/tags/Software" rel="tag">Software</a></div>Unknownnoreply@blogger.com0tag:blogger.com,1999:blog-19212077.post-1161927990114878212006-10-26T22:46:00.000-07:002006-10-28T09:38:27.756-07:00C# Anonymous Delegates: Your Stack or Mine?<p>I want to take a moment to call out what I think is an interesting part of <a href="http://www.codeneverwritten.com/2006/10/ctrl-c-and-net-console-application.html">my previous post</a>. Anonymous delegates have an interesting capability. To illustrate, here's an example:</p> <p><pre><font color="#004080">using System;<br />using System.Threading;<br /><br />class Program<br />{<br /> static void Main(string[] args)<br /> {<br /> // 'num' lives on the main thread's stack.<br /> int num = 0;<br /> Console.WriteLine("initial num=" + num);<br /><br /> Thread thread = new Thread(<br /> delegate()<br /> {<br /> // Yet this delegate running on a different thread with<br /> // it's own stack has access to 'num' as well.<br /> num = 42;<br /> });<br /><br /> thread.Start(); // Start the worker thread.<br /> thread.Join(); // Wait until the worker thread has finished.<br /><br /> Console.WriteLine("final num=" + num);<br /> }<br />}</font></pre><br /><p></p><br /><p></p><br /><p>It's pretty simple. This program declares and initializes a variable named <font face="Courier New" color="#004080"><strong>num</strong></font>, creates and starts a thread that will set <font face="Courier New" color="#004080"><strong>num</strong></font> to a different value, then waits for the thread to to complete. In the program's output we see that <font face="Courier New" color="#004080"><strong>num</strong></font> has indeed been set to 42. Here's the view from the command line:</p><br /><p><pre><font color="#008000">F:\tmp>csc Program.cs<br />Microsoft (R) Visual C# 2005 Compiler version 8.00.50727.42<br />for Microsoft (R) Windows (R) 2005 Framework version 2.0.50727<br />Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.<br /><br /><br />F:\tmp>Program.exe<br />initial num=0<br />final num=42</font></pre><br /><p></p><br /><p>Okay, that's as expected. But wait--<font face="Courier New" color="#004080"><strong>num</strong></font> lives on the main thread's stack. How is it that the second thread we've created has access to <font face="Courier New" color="#004080"><strong>num</strong></font>? <font face="Courier New" color="#004080"><strong>num</strong></font> isn't on the second thread's stack and it would be a pretty scary thing if the second thread had direct access to the first thread's stack. All sorts of mayhem could ensue. Providing access to another thread's stack isn't exactly the sort of thing we want to happen in managed code.</p><br /><h3>Chicanery?</h3><br /><p>As it turns out, though it <em>appears</em> that <font face="Courier New" color="#004080"><strong>num</strong></font> is a stack variable in the main method <em>it is not</em>. What we're experiencing here is a convenience provided by the compiler. Or rather, a trick. A sleight-of-hand. An illusion. <font face="Courier New" color="#004080"><strong>num</strong></font> doesn't actually live on the stack.</p><br /><p>In fact, the compiler has made <font face="Courier New" color="#004080"><strong>num</strong></font> a field in a compiler generated class so that it can be made available <em>on the heap</em> to the delegate. Here's the compiled code, courtesy of <a href="http://www.aisto.com/roeder/dotnet/">.NET Reflector</a>:</p><br /><p> </p><br /><p><pre><font color="#408080">[CompilerGenerated]<br />private sealed class <>c__DisplayClass1<br />{<br /> // Methods<br /> public <>c__DisplayClass1() { }<br /> public void <main>b__0()<br /> {<br /> this.num = 0x2a;<br /> }</font></pre><pre><font color="#408080"> // Fields<br /> public int num;<br />}</font></pre><br /><p></p><br /><p>The compiler has given our anonymous delegate method a name: it's <font face="Courier New" color="#408080"><main>b__0()</font> on this compiler generated class. As a member of this class it obviously has access to <font face="Courier New" color="#004080"><strong>num</strong></font>. The illusion is completed by fitting out the Main method so that it has an instance of <font face="Courier New" color="#408080"><>c__DisplayClass1</font> to use:</p><br /><p> </p><br /><p><pre><font color="#408080">private static void Main(string[] args)<br />{<br /> Program.<>c__DisplayClass1 class1 = new Program.<>c__DisplayClass1();<br /> class1.num = 0;<br /> Console.WriteLine("initial num=" + class1.num);</font></pre><pre><font color="#408080"><br /> Thread thread1 = new Thread(new ThreadStart(class1.<main>b__0));<br /> thread1.Start();<br /> thread1.Join();</font></pre><pre><font color="#408080"><br /> Console.WriteLine("final num=" + class1.num);<br />}</font></pre><br /><p></p><br /><p>So now our <font face="Courier New" color="#408080">Main</font> method has an instance of an object on the heap and can set <font face="Courier New" color="#004080"><strong>num</strong></font> to zero since <font face="Courier New" color="#004080"><strong>num</strong></font> is a public field on the compiler generated class.</p><br /><p>And so, both threads are accessing a variable--not on the stack, but on the heap and accessible to both threads. This helpful behind-the-scenes work by the C# compiler allows us to keep the simplicity of the original code in this example; otherwise, we'd need to implement something like what the compiler has done for us. </p><br /><p> </p><br /><div class="wlWriterSmartContent" id="0767317B-992E-4b12-91E0-4F059A8CECA8:5f17122d-4172-44ad-bad3-b04665f80be7" contenteditable="false" style="padding-right: 0px; display: inline; padding-left: 0px; padding-bottom: 0px; margin: 0px; padding-top: 0px">Technorati tags: <a href="http://technorati.com/tags/.Net" rel="tag">.Net</a>, <a href="http://technorati.com/tags/C#" rel="tag">C#</a>, <a href="http://technorati.com/tags/Coding" rel="tag">Coding</a></div><br /><p>[Edit: Fix up formatting.]</p>Unknownnoreply@blogger.com1