<?xml version='1.0' encoding='UTF-8'?><rss xmlns:atom="http://www.w3.org/2005/Atom" xmlns:openSearch="http://a9.com/-/spec/opensearchrss/1.0/" xmlns:blogger="http://schemas.google.com/blogger/2008" xmlns:georss="http://www.georss.org/georss" xmlns:gd="http://schemas.google.com/g/2005" xmlns:thr="http://purl.org/syndication/thread/1.0" version="2.0"><channel><atom:id>tag:blogger.com,1999:blog-1951153510791888567</atom:id><lastBuildDate>Sat, 31 May 2025 02:48:51 +0000</lastBuildDate><category>C#</category><category>Programming</category><category>problem</category><category>.Net</category><category>Delphi</category><category>design</category><category>WPF</category><category>HowTo</category><category>Microsoft</category><category>arduino</category><category>UI</category><category>FAQ</category><category>Debugging</category><category>Colors</category><category>UserExperience</category><category>Win32</category><category>comparison</category><category>installation</category><category>rant</category><category>recap</category><category>usability</category><category>Apple</category><category>C++</category><category>HSV</category><category>Interfaces</category><category>RGB</category><category>VirtualBox</category><category>VisualStudio</category><category>WTF</category><category>conference</category><category>cursor</category><category>resource</category><category>AboutMe</category><category>LCD</category><category>LINQ</category><category>Linux</category><category>Office</category><category>PDC2008</category><category>Ribbon</category><category>WinForms</category><category>Windows 8</category><category>benchmark</category><category>binding</category><category>dictionary</category><category>kit</category><category>networking</category><category>pascal</category><category>report</category><category>trip</category><category>Binary</category><category>COM</category><category>CompilerBug</category><category>DataGrid</category><category>FileFormat</category><category>IDL</category><category>Interop</category><category>JetBrains</category><category>Jolicloud</category><category>Reflection</category><category>Resharper</category><category>RhinoMock</category><category>SplashScreen</category><category>Text</category><category>UtahCodeCamp</category><category>VS2012</category><category>ValueConverter</category><category>WWSGD</category><category>array</category><category>blogger</category><category>blogspot</category><category>class</category><category>ethernet</category><category>firmware</category><category>hpebley3</category><category>humor</category><category>nunchuck</category><category>object</category><category>rave</category><category>references</category><category>router</category><category>set</category><category>sports</category><category>stepper motor</category><category>wii</category><title>Skylark Software</title><description>Giving wings to the imagination</description><link>http://www.skylark-software.com/</link><managingEditor>noreply@blogger.com (Harley Pebley)</managingEditor><generator>Blogger</generator><openSearch:totalResults>71</openSearch:totalResults><openSearch:startIndex>1</openSearch:startIndex><openSearch:itemsPerPage>25</openSearch:itemsPerPage><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-7883889621642346328</guid><pubDate>Sat, 23 Aug 2014 18:40:00 +0000</pubDate><atom:updated>2014-08-23T12:40:01.396-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">design</category><title>What you know and have impacts your design</title><description>&lt;iframe width=&quot;560&quot; height=&quot;315&quot; src=&quot;//www.youtube.com/embed/VjZzNoFXc4k?rel=0&quot; frameborder=&quot;0&quot; allowfullscreen&gt;&lt;/iframe&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;Description&lt;/h2&gt;You can only design from what you know and/or have available to you. Here&#39;s a short video showing the evolution of a electric switch design based on new information.&lt;br /&gt;
&lt;br /&gt;
&lt;h2&gt;Transcript&lt;/h2&gt;Shop equipment frequently have two push-button toggle switches to turn things on and off. I recently worked on a project where I wanted to replicate this behavior to control an appliance and do it inexpensively. My hope was to get by with junk bin parts.&lt;br /&gt;
&lt;br /&gt;
Looking around at my spare parts, I found a project box, a couple momentary switches and a relay with contacts rated above what I wanted to control. So I started with these items.&lt;br /&gt;
&lt;br /&gt;
It was a double-pole relay. My thought was to use one pole of the relay to hold itself energized and the other pole to switch my device. So, one switch energizes the relay and the relay then holds itself closed. This should allow me to turn on the device.&lt;br /&gt;
&lt;br /&gt;
I figured a transistor could be placed between supply voltage and the relay&#39;s coil with the base wired to the supply voltage. The &quot;off&quot; switch could connect to the base of the transistor and ground. In this configuration, the transistor would normally be on allowing, the relay to be energized. But when the button is pressed, the transistor would turn off the power to the coil, switching the relay off.&lt;br /&gt;
&lt;br /&gt;
I wired it all together and it worked!&lt;br /&gt;
&lt;br /&gt;
The relay circuit was too big to fit in the project box though, so I wired the switches through a four conductor wire and put the circuit in a separate box next to the switched item.&lt;br /&gt;
&lt;br /&gt;
Even though it worked, I wasn&#39;t too wild about having high voltage and low voltage running through the different poles of the relay. It seemed like a pretty bad hack.&lt;br /&gt;
&lt;br /&gt;
While I worked on other aspects of the project, I ran across something called a &quot;PowerSwitch Tail.&quot; This looks like a short extension cord but it has a twist. It has a solid-state relay built into it. Normally the outlets are turned off, but place a low voltage across these connectors and the outlets will turn on.&lt;br /&gt;
&lt;br /&gt;
This seemed like a much better solution than my relay hack.&lt;br /&gt;
&lt;br /&gt;
So I completely rethought my approach.&lt;br /&gt;
&lt;br /&gt;
I could have simply replaced the high voltage side of the relay circuit with a low voltage source going to the power tail&#39;s connectors. This would work, but now the relay seemed way overkill. I had a low voltage circuit controlling another low voltage circuit through a relay.&lt;br /&gt;
&lt;br /&gt;
Instead I replaced the relay based circuit with a flip-flop circuit. These can be built from discrete components, but I had a quad NAND gate chip in the parts box and this would shrink the size significantly.&lt;br /&gt;
&lt;br /&gt;
I wired up the new circuit and it worked. A much cleaner approach.&lt;br /&gt;
&lt;br /&gt;
As I worked on other aspects of the project, I had a realization: that flip-flop circuit was small enough it could fit in the project box with the switches. If I reconfigured the 4-conductor wire to have voltage, ground and signal, I could move the circuit to the box.&lt;br /&gt;
&lt;br /&gt;
In the end, I did this as it allows future changes to the switching mechanism. Right now I have the two push button toggle switch configuration. But at some point, I&#39;m thinking I want to have a current detecting switch to turn one appliance on and off based on another appliance being on or off. This is easily done with the new configuration but wasn&#39;t so convenient with the old.&lt;br /&gt;
&lt;br /&gt;
So, that&#39;s my story about how this design evolved over time as I discovered new resources and thought about the problem at a deeper level.&lt;br /&gt;
&lt;br /&gt;
Catch you next time.&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2014/08/what-you-know-and-have-impacts-your.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-988191709584155560</guid><pubDate>Wed, 09 Apr 2014 12:00:00 +0000</pubDate><atom:updated>2014-04-09T06:00:10.157-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">design</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><title>Are enumerations evil?</title><description>&lt;h2&gt;Or, How to refactor an enumeration to multiple classes&lt;/h2&gt;I ran across &lt;a href=&quot;http://encosia.com/first-class-functions-as-an-alternative-to-javascripts-switch-statement/&quot;&gt;this article about how to refactor a switch statement to a data structure in JavaScript&lt;/a&gt; a while ago. This is not a terrible refactoring technique. I&#39;ve used something similar with dictionaries in C# where the key was an enumeration and the value was an Action (or Func). It can be a minor refactoring to a single method that can help clean-up the code. Then this week I had a conversation with a fellow developer about the appropriateness of an enumeration in existing code from a couple different libraries he was reading.&lt;br /&gt;
&lt;br /&gt;
This led me to wonder afresh if perhaps enumerated types aren&#39;t something that we as the development community should treat as an anti-pattern. In the days before class types, they were a means for the compiler to force integers to known values and provide more readable code for the developer. The compiler could check values better at compile time and catch usage errors earlier. I have worked on languages without them and embraced them when they became available. At that point they were a good thing.&lt;br /&gt;
&lt;br /&gt;
Many times enumerations are used to change behavior of some code based on a variable&#39;s value. This is usually done through switch or if-then-else statements. Or, as discussed above, using some sort of dictionary like structure to store behavior associated with a specific enumerated value.&lt;br /&gt;
&lt;br /&gt;
The problem is this pattern tends to get replicated within the class containing the enumerated variable. The class using the enumeration needs to do different things based on the various values the variable can have and these different things spread throughout the class (or classes) using the enumeration. Then, when a value is added to the enumeration, each place the variable is tested needs to be updated to handle the new value.&lt;br /&gt;
&lt;br /&gt;
This can lead to a number of problems. With behavior based on the enum scattered throughout classes, the intent can be both obfuscated and duplicated. When adding a value to the enumeration, it&#39;s easy to miss a place that needs new behavior, introducing hard to detect bugs. The code is fragile in the face of changes. And because the state and associated behavior associated with the enumeration is mixed in with the class (or classes) using it, violation of the &lt;a href=&quot;http://en.wikipedia.org/wiki/Single_responsibility_principle&quot;&gt;Single Responsibility Principle&lt;/a&gt; frequently is seen.&lt;br /&gt;
&lt;br /&gt;
Refactoring to a data structure as mentioned above is a good first step. It helps address a number of the problems. But in today&#39;s object oriented world, there is a better way. In many (perhaps most) cases it&#39;s better to refactor to multiple classes, one for each value in the enumeration. Fortunately, this is fairly easily done.&lt;br /&gt;
&lt;br /&gt;
Here&#39;s the original starting code:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;enum SomeItemEnum = { one, two, three };
class A
{
&amp;nbsp;&amp;nbsp;SomeItemEnum someItemValue;
&amp;nbsp;&amp;nbsp;void SomeItemUser()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;switch(someItemValue)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case one:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case one
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case two:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case two
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case three:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case three
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;First, a base class is created as an ancestor for the enumeration.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;enum SomeItemEnum = { one, two, three };

&lt;b&gt;class SomeItemEnumBase
{
}&lt;/b&gt;

class A
{
&amp;nbsp;&amp;nbsp;SomeItemEnum someItemValue;
&amp;nbsp;&amp;nbsp;void SomeItemUser()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;switch(someItemValue)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case one:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case one
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case two:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case two
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case three:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case three
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;Then, each place where something needs to be done based on the value of the enumeration, a method is added to the class. If there is no default behavior for a method, it should be abstract, otherwise it should be virtual.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;enum SomeItemEnum = { one, two, three };

abstract class SomeItemEnumBase
{
&lt;b&gt;&amp;nbsp;&amp;nbsp;abstract void ComplicatedCode();&lt;/b&gt;
}

class A
{
&amp;nbsp;&amp;nbsp;SomeItemEnum someItemValue;
&amp;nbsp;&amp;nbsp;void SomeItemUser()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;switch(someItemValue)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case one:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case one
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case two:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case two
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case three:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case three
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;A child class should be made for each value of the enumeration with the value specific behavior moved to the appropriate overridden method.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;enum SomeItemEnum = { one, two, three };

abstract class SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;abstract void ComplicatedCode();
}

&lt;b&gt;class SomeItemEnumOne : SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case one
&amp;nbsp;&amp;nbsp;}
}

class SomeItemEnumTwo : SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case two
&amp;nbsp;&amp;nbsp;}
}

class SomeItemEnumThree : SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case three
&amp;nbsp;&amp;nbsp;}
}&lt;/b&gt;

class A
{
&amp;nbsp;&amp;nbsp;SomeItemEnum someItemValue;
&amp;nbsp;&amp;nbsp;void SomeItemUser()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;switch(someItemValue)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case one:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case one
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case two:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case two
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case three:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case three
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;Change the type of the class&#39; variable from the enumeration to the base type.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;enum SomeItemEnum = { one, two, three };

abstract class SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;abstract void ComplicatedCode();
}

class SomeItemEnumOne : SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case one
&amp;nbsp;&amp;nbsp;}
}

class SomeItemEnumTwo : SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case two
&amp;nbsp;&amp;nbsp;}
}

class SomeItemEnumThree : SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case three
&amp;nbsp;&amp;nbsp;}
}

class A
{
&lt;b&gt;&amp;nbsp;&amp;nbsp;SomeItemEnumBase someItemValue;&lt;/b&gt;
&amp;nbsp;&amp;nbsp;void SomeItemUser()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;switch(someItemValue)
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case one:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case one
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case two:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case two
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;case three:
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case three
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;break;
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}
&amp;nbsp;&amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;Instead of setting discrete values on the enumerated variable, now a class instance of the appropriate type can be set.&lt;br /&gt;
&lt;br /&gt;
Old method:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;someItemValue = SomeItemEnum.one;
someItemValue = SomeItemEnum.two;&lt;/code&gt;&lt;/pre&gt;New method:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;someItemValue = new SomeItemEnumOne();
someItemValue = new SomeItemEnumTwo();&lt;/code&gt;&lt;/pre&gt;All the switch/if-else statements can now be changed to simple method calls that have polymorphic behavior based on the class type.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;enum SomeItemEnum = { one, two, three };

abstract class SomeItemBase
{
&amp;nbsp;&amp;nbsp;abstract void ComplicatedCode();
}

class SomeItemOne : SomeItemBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case one
&amp;nbsp;&amp;nbsp;}
}

class SomeItemTwo : SomeItemBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case two
&amp;nbsp;&amp;nbsp;}
}

class SomeItemThree : SomeItemBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case three
&amp;nbsp;&amp;nbsp;}
}

class A
{
&amp;nbsp;&amp;nbsp;SomeItemEnumBase someItemValue;
&amp;nbsp;&amp;nbsp;void SomeItemUser()
&amp;nbsp;&amp;nbsp;{
&lt;b&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;someItemValue.ComplicatedCode();&lt;/b&gt;
&amp;nbsp;&amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;And finally, the unused enumeration declaration can be removed.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;&lt;strike&gt;enum SomeItemEnum = { one, two, three };&lt;/strike&gt;

abstract class SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;abstract void ComplicatedCode();
}

class SomeItemEnumOne : SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case one
&amp;nbsp;&amp;nbsp;}
}

class SomeItemEnumTwo : SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case two
&amp;nbsp;&amp;nbsp;}
}

class SomeItemEnumThree : SomeItemEnumBase
{
&amp;nbsp;&amp;nbsp;override void ComplicatedCode()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;// Some complicated code for case three
&amp;nbsp;&amp;nbsp;}
}

class A
{
&amp;nbsp;&amp;nbsp;SomeItemEnumBase someItemValue;
&amp;nbsp;&amp;nbsp;void SomeItemUser()
&amp;nbsp;&amp;nbsp;{
&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;someItemValue.ComplicatedCode();
&amp;nbsp;&amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;Now, when a new value is added, only places that actually care about the new value specifically (e.g. where its value is set) need to be touched. As a bonus, the compiler will complain about any unimplemented abstract functions, ensuring all required behavior is implemented.&lt;br /&gt;
&lt;br /&gt;
Finally, admittedly, in this toy example, the final result is more complicated and obtuse than the original. If production code is as simple as this example, then it doesn&#39;t make sense to make this change. However, when class A is larger and more complex, the increased clarity and robustness of the code can be significant. In my experience, the latter is more typical than the former and so in general, my conclusion is enumerations border on evil.&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2014/04/are-enumerations-evil.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-8167489061554685294</guid><pubDate>Fri, 14 Mar 2014 12:00:00 +0000</pubDate><atom:updated>2014-03-14T06:00:07.476-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C++</category><category domain="http://www.blogger.com/atom/ns#">problem</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><title>Weird compiler error: C2360: initialization is skipped by label</title><description>I ran into a new error the other day that was non-obvious at first glance.&lt;br /&gt;
&lt;br /&gt;
I had code structured something like (greatly simplified by way of example):&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;void MyFunction()
{
     int a = GetValueOfA();
     switch(a)
     {
          case 1:
               int b = 2;
               DoSomething(b);
               break;
          case 2:
               int c = 3;
               DoSomethingElse(c);
               break;
     }
}&lt;/code&gt;&lt;/pre&gt;This gave me an error on the second case &quot;error C2360: initialization of &#39;b&#39; is skipped by &#39;case&#39; label.&quot; *&lt;br /&gt;
&lt;br /&gt;
What?!? This is one of those cases where the message is technically accurate after you understand what it says but utterly useless to explain what is going on or what the solution is at first glance. Or perhaps I&#39;m slow. I stared at this for a bit before I comprehended what it was trying to tell me.&lt;br /&gt;
&lt;br /&gt;
The root of the issue is that, while the case statements appear to be in their own scope, they aren&#39;t. (I&#39;m sure I knew this at some point, but the memory was overridden long ago. Or perhaps I have too many languages floating around in my head.) The scope for variables inside a switch statement is all the cases, not just the current case. Therefore, in the code above, variables b and c are available anywhere inside the switch statement. The error says b is defined, but may not be initialized properly, when a = 2.&lt;br /&gt;
&lt;br /&gt;
All the solutions involve changing the scope of b and c. There are a couple immediately obvious solutions:&lt;br /&gt;
&lt;br /&gt;
1) Put braces around the contents of the case statements to limit their scope.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;void MyFunction()
{
     int a = GetValueOfA();
     switch(a)
     {
          case 1:
               {
                    int b = 2;
                    DoSomething(b);
               }
               break;
          case 2:
               {
                    int c = 3;
                    DoSomethingElse(c);
               }
               break;
     }
}&lt;/code&gt;&lt;/pre&gt;2) Put the contents of the case statements in their own functions, another way of limiting their scope.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;void PerformCase1()
{
     int b = 2;
     DoSomething(b);
}

void PerformCase2()
{
     int c = 3;
     DoSomethingElse(c);
}

void MyFunction()
{
     int a = GetValueOfA();
     switch(a)
     {
          case 1:
               PerformCase1();
               break;
          case 2:
               PerformCase2();
               break;
     }
}&lt;/code&gt;&lt;/pre&gt;3) Move the declaration to before the switch statement and don&#39;t do initialization/declaration on the same line.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;void MyFunction()
{
     int b, c;
     int a = GetValueOfA();
     switch(a)
     {
          case 1:
               b = 2;
               DoSomething(b);
               break;
          case 2:
               c = 3;
               DoSomethingElse(c);
               break;
     }
}&lt;/code&gt;&lt;/pre&gt;Another option would be to change the structure of the code such that the switch isn&#39;t necessary. In general, this would be my favored solution although in this specific case of legacy code, that would have involved more work than the budget allowed.&lt;br /&gt;
&lt;hr/&gt;* Actually my notes say I also got a second error on the switch stating &quot;transfer of control bypasses initialization of variable b&quot; but I could not reproduce this one. Perhaps I simplified too much. Or perhaps it was a different version of the compiler. Or perhaps different option settings. Or something else entirely.&lt;br /&gt;
&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2014/03/weird-compiler-error-c2360.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-7803729177587614807</guid><pubDate>Mon, 24 Feb 2014 13:00:00 +0000</pubDate><atom:updated>2014-02-24T06:00:01.183-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">C++</category><category domain="http://www.blogger.com/atom/ns#">COM</category><category domain="http://www.blogger.com/atom/ns#">IDL</category><category domain="http://www.blogger.com/atom/ns#">Interop</category><category domain="http://www.blogger.com/atom/ns#">problem</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><title>Constant integer values and multi-language COM interop</title><description>I recently moved some code from a legacy C++ application into a COM library for more general use. The original code was duplicated a couple times in different C++ applications. Then a need arose to use this code in C#. To clean up both the duplication and make it available to .Net applications, we decided to untangle it from the original applications and move it into its own COM library.&lt;br /&gt;
&lt;br /&gt;
One of the issues I ran into that took a bit to figure out involved constant values.&lt;br /&gt;
&lt;br /&gt;
The old C code had several things defined as integers with associated constant definitions to handle bit-mapped values. Some might argue these should be converted to enumerations but we wanted to minimize changes to existing code structure and so decided to keep them as integer constants. The issue with this was how to move them to a common location for all COM clients to access.&lt;br /&gt;
&lt;br /&gt;
It took a bit of research to find the answer as I didn&#39;t find a complete answer in one place. Hopefully this article will help fill that gap.&lt;br /&gt;
&lt;br /&gt;
IDL files can have #define statements. This works for C code. The IDL compiler maps these as corresponding #defines in the corresponding intermediate .h files. The problem is when .Net creates an Interop assembly, they are ignored. This means they don&#39;t exist for use in .Net languages.&lt;br /&gt;
&lt;br /&gt;
Next I used const definitions in the library. Again, this worked for C code but the Interop assembly in the .Net world did not have them.&lt;br /&gt;
&lt;br /&gt;
I moved the const definitions into an interface. Still, C was perfectly happy but the Interop ignored them.&lt;br /&gt;
&lt;br /&gt;
I search around some more. I ran into some forum discussions that indicated it was impossible.&lt;br /&gt;
&lt;br /&gt;
Finally I found a reference to something that pointed me in the correct direction. IDL files can have the concept of modules, something I hadn&#39;t run into before. I put the const declaration in a module section in the IDL file. In the intermediate .h file for C++, these are simply constants and callers are still happy. But in this case, when the .Net Interop file is created they are not ignored. The Interop generator maps them to an abstract class named with the name of the module and the constants become static consts inside the class. This makes them available for any .Net user to access.&lt;br /&gt;
&lt;br /&gt;
So, the IDL file ended up looking like this:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;library SomeComLibrary
{
    module Constants
    {
        const DWORD UniqueValue = 0xFFFFFFFF;
    }
}&lt;/code&gt;&lt;/pre&gt;C&#39;s intermediate .h file looks like this:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;#ifndef __Constants_MODULE_DEFINED__
#define __Constants_MODULE_DEFINED__
/* module Constants */
const DWORD UniqueValue = 0xffffffff;
#endif /* __Constants_MODULE_DEFINED__ */&lt;/code&gt;&lt;/pre&gt;And the .Net Interop file looks like this:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;namespace SomeComLibrary
{
    public abstract class Constants
    {
        public const uint UniqueValue = -1;
    }
}&lt;/code&gt;&lt;/pre&gt;The solution ended up being quite easy, but finding it was a bit of a challenge.&lt;br /&gt;
&lt;hr/&gt;Things I searched for trying to find a solution to this problem included:&lt;ul&gt;&lt;li&gt;idl const not in .net&lt;/li&gt;
&lt;li&gt;idl const not in interop&lt;/li&gt;
&lt;li&gt;idl const not in C# interop&lt;/li&gt;
&lt;li&gt;midl keywords&lt;/li&gt;
&lt;li&gt;idl const .net&lt;/li&gt;&lt;/ul&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2014/02/constant-integer-values-and-multi.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-2185553674169536130</guid><pubDate>Thu, 19 Dec 2013 13:00:00 +0000</pubDate><atom:updated>2013-12-19T06:00:02.584-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">HowTo</category><category domain="http://www.blogger.com/atom/ns#">problem</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">RhinoMock</category><title>How to get Ref parameter values in RhinoMock</title><description>Mocking ref (and out) parameters with RhinoMock is a bit tedious. I ran into something that could possibly be considered a bug. At the very least it&#39;s not really expected behavior. The good news is I found a work-around. Hopefully this will help someone else (including perhaps my future self).&lt;br /&gt;
&lt;br /&gt;
The basic problem is: Ref parameter values passed to mocked methods have the default values specified in the mock setup and not the values passed by the calling code.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;The background&lt;/h3&gt;Take the following interface as an example.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;interface ISomething
{
    void DoStuff(string a);
}&lt;/code&gt;&lt;/pre&gt;Now supposed this is mocked and some things need to be done based on the value of parameter a.&lt;br /&gt;
&lt;br /&gt;
Normally this is easily done:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public void Initialize()
{
     mockSomething = MockRepository.GenerateStub&lt;ISomething&gt;();
     mockSomething.Stub(s =&gt; s.DoStuff(Arg&lt;string&gt;.Is.Anything())
          .Do((Action&lt;string&gt;)(arg =&gt;
               {
                    // Perform general action with arg
                    
                    if (arg == &quot;abc&quot;)
                    {
                         // Special case action for arg
                    }
               }));
}&lt;/code&gt;&lt;/pre&gt;Every time something calls mockSomething.DoStuff, the code passed to the Do method will be executed and the parameter arg will contain whatever value was passed to DoStuff. This is routine stuff for RhinoMocks and works as expected.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;The setup&lt;/h3&gt;Now suppose the parameter for DoStuff was a ref.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;interface ISomething
{
    void DoStuff(ref string a);
}&lt;/code&gt;&lt;/pre&gt;This is where things get a bit dicey. The interface is still mocked and some things still need to be done based on the value of parameter a. So, some minor syntax changes in the arguments constraints to handle the ref stuff for the compiler are done:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;private delegate void DoStuffDelegate(ref string a);

public void Initialize()
{
     mockSomething = MockRepository.GenerateStub&lt;ISomething&gt;();
     mockSomething.Stub(s =&gt; s.DoStuff(ref Arg&lt;string&gt;.Ref(Is.Anything(), string.Empty).Dummy)
          .Do((DoStuffDelegate)((ref arg) =&gt;
               {
                    // Perform general action with arg
                    
                    if (arg == &quot;abc&quot;)
                    {
                         // Special case action for arg
                    }
               }));
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
&lt;h3&gt;The problem&lt;/h3&gt;The above code compiles. And it runs. It just doesn&#39;t run correctly. The problem is that second parameter in the Arg&amp;lt;T&gt;.Ref method. It indicates a return result for the the value. The problem is RhinoMocks sets the parameter value to the return result before calling Do&#39;s method. In other words, in this example, arg will always be string.Empty. The code in Do will never be called with the values sent to DoStuff by the original caller.&lt;br /&gt;
&lt;br /&gt;
Looking at the call stack, I could see the original method call with the correct parameter values. Then it went into the RhinoMock and proxy code and then Do&#39;s method was called, clearly with the unexpected value.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;Looking for solutions&lt;/h3&gt;Digging around, I found the WhenCalled method. This appears to be a bit earlier in the mock/proxy processing so I changed the test.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public void Initialize()
{
     mockSomething = MockRepository.GenerateStub&lt;ISomething&gt;();
     mockSomething.Stub(s =&gt; s.DoStuff(ref Arg&lt;string&gt;.Ref(Is.Anything(), string.Empty).Dummy)
          .WhenCalled(invocation =&gt;
               {
                    var arg = (string)invocation.Arguments[0];

                    // Perform general action with arg
                    
                    if (arg == &quot;abc&quot;)
                    {
                         // Special case action for arg
                    }
               }));
}&lt;/code&gt;&lt;/pre&gt;Nope. This didn&#39;t work either. The value for Arguments[0] has already been set to the return value.&lt;br /&gt;
&lt;br /&gt;
While searching around, I found other people asking about the same issue. In their cases they found alternative solutions based on constraints of when their methods were called and what values the parameters could have. With known values, constants can be used via hard coding. For example, instead of using Is.Anything() as above, Is.Equal(&quot;abc&quot;) can be used and the second parameter can be &quot;abc&quot;. Everything is fine.&lt;br /&gt;
&lt;br /&gt;
I was semi-successful with the special case by using this technique. But then I needed to do the special action and use Is.NotEqual(&quot;abc&quot;). I ran into the same problem as with Is.Anything(). I didn&#39;t know the original value for arg.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;The solution&lt;/h3&gt;Widening my search, I stumbled upon an old article by Ayende talking about the Callback method. He considered it for weird edge case parameter checking and indicated it shouldn&#39;t generally be used. As far as I could make out from his write-up, it&#39;s purpose is as an alternative to the Arg&lt;T&gt; constraints when they aren&#39;t sufficient.&lt;br /&gt;
&lt;br /&gt;
Having nothing to lose, I changed my code to give it a try:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;private delegate bool DoStuffCallbackDelegate(ref string a);

public void Initialize()
{
     mockSomething = MockRepository.GenerateStub&lt;ISomething&gt;();
     mockSomething.Stub(s =&gt; s.DoStuff(ref Arg&lt;string&gt;.Ref(Is.Anything(), string.Empty).Dummy)
          .Callback((DoStuffCallbackDelegate)((ref arg) =&gt;
               {
                    // Perform general action with arg
                    
                    if (arg == &quot;abc&quot;)
                    {
                         // Special case action for arg
                    }

                    return true;
               }));
}&lt;/code&gt;&lt;/pre&gt;Hurrah! This worked!&lt;br /&gt;
&lt;br /&gt;
Since Callback&#39;s intent is to determine if the constraint on the stub is valid, it gets the original parameter values, rather than the return result.&lt;br /&gt;
&lt;br /&gt;
And, yes, I realize I&#39;m misusing the intent of Callback. But when nothing else works, you go with what does.&lt;br /&gt;
&lt;br /&gt;
&lt;h3&gt;The conclusion&lt;/h3&gt;Since this met my needs, I stopped here. If this was a function rather than a method, I suppose a Do or Return method would have to be chained to the setup code after the Callback method in order to return a valid value for the stubbed function. Also note, if this stub should be ignored, then false can be returned from Callback instead of true. This would allow other stubs for the same method to be handled differently.&lt;br /&gt;
&lt;br /&gt;
I&#39;m not sure if this is a bug, intended behavior or an unconsidered edge case that has, at least to some, unexpected behavior. Both Out and Ref methods have the return result. It makes sense to be mandatory for Out, but I think it should be optional for Ref. I can see cases where you&#39;d want to stub in a particular value all the time. The current syntax supports this well. But I can also see cases where it shouldn&#39;t be changed, at least by the Ref handling code. An overloaded version of Ref without the parameter would work well. In any case, I don&#39;t think it should be set before WhenCalled and Do are are invoked. At a minimum it should be after and better yet only if the original value hasn&#39;t been changed by WhenCalled or Do.&lt;br /&gt;
&lt;br /&gt;
Well, that&#39;s my latest story regarding RhinoMocks. I hope it helps someone.&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2013/12/how-to-get-ref-parameter-values-in.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-5542733597182402444</guid><pubDate>Fri, 06 Dec 2013 13:00:00 +0000</pubDate><atom:updated>2013-12-06T06:00:00.927-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">AboutMe</category><category domain="http://www.blogger.com/atom/ns#">design</category><category domain="http://www.blogger.com/atom/ns#">problem</category><title>How to generate an alert tone from a computer</title><description>I recently read a Code Project thread that got into a &lt;a href=&quot;http://www.codeproject.com/Feature/WeirdAndWonderful.aspx?msg=4607552#xx4607552xx&quot;&gt;discussion about beeps, internal speakers and alerting the user.&lt;/a&gt; This reminded me of a story from a previous life...&lt;br /&gt;
&lt;br /&gt;
It was the early 90s and I worked for a company that provided software to E-911 dispatch centers. There was a machine room with racks of computers and then the actual dispatch center which only had user I/O devices. The monitors and keyboards were run through special extension hardware that allowed VGA, keyboard, mouse, serial and parallel ports to be removed from the computer by a fair distance. It seems like the system would drive them up to 100 feet away, but my memory could be faulty. In any case, we had all these extension boxes scattered throughout the center but all the built-in computer speakers were back in the server room.&lt;br /&gt;
&lt;br /&gt;
A feature of the software allowed dispatchers to place calls in a pending queue. This was for low priority calls that didn&#39;t have resources available for immediate dispatch. After a timeout, things in the queue would start escalating. First they&#39;d change color. Then they&#39;d start flashing. The Chief wanted the next level to be an audible alert. And, with this being the fire department, audible alert didn&#39;t mean a simple &quot;beep.&quot; It needed to be impossible to ignore, klaxon-loud and obnoxious. And of course there wasn&#39;t any budget for any significant hardware. I thought about it on the drive home and had an idea as I fell asleep.&lt;br /&gt;
&lt;br /&gt;
The next morning I stopped by Radio Shack and picked up a $10 monophonic amplifier. Something simple. (Amazingly, I just searched for it and they still &lt;a href=&quot;http://www.radioshack.com/product/index.jsp?productId=2062620&quot;&gt;sell the same model 20+ years later, albeit at a slightly higher price.&lt;/a&gt;) I also got a 1/8&quot; patch cord and power adapter. When I got to the dispatch center, I cut off one end of the patch cord and connected the leads to the ground and transmit pins on an RS-232 connector on one of the extension boxes. Then I plugged in the amplifier, turned the volume down low, created a short text file with some random characters and cat&#39;ed it to the appropriate /dev/tty port. An earful of noise rewarded my efforts.&lt;br /&gt;
&lt;br /&gt;
Now I knew my idea would work. Playing around with different repeating character sequences gave different patterns. Changing the baud rate would change the frequency. Eventually I came up with a combination that worked pretty well. It was loud, obnoxious and impossible to ignore. The Chief loved it. And it cost less than $20 and an hour or two of work.&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2013/12/how-to-generate-alert-tone-from-computer.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-7306232117106396473</guid><pubDate>Mon, 11 Nov 2013 13:00:00 +0000</pubDate><atom:updated>2013-11-11T06:00:04.676-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">problem</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">rant</category><title>When is the right time to select a source code control tool?</title><description>&lt;br /&gt;
&lt;blockquote&gt;If you’re about to start a new project it’s a good time to consider what version control solution you’re going to use.&lt;cite&gt;-- &lt;a href=&quot;http://blogs.msdn.com/b/visualstudiouk/archive/2013/08/05/well-i-like-team-foundation-server-and-i-like-git-but-which-is-better.aspx&quot;&gt;Article discussing TFS vs Git&lt;/a&gt;&lt;/cite&gt;&lt;/blockquote&gt;I read the above statement in an article recently and my brain threw an exception when it parsed it. You know how that works. You&#39;re scanning along the text and all of a sudden, half a paragraph later, an interrupt is raised &quot;Wait, did I really just read that?&quot; You stop and go back over it.&lt;br /&gt;
&lt;br /&gt;
There are plenty of articles covering &lt;em&gt;how&lt;/em&gt; to choose a source code control tool. Many places compare and contrast all the options,&lt;sup&gt;&lt;small&gt;&lt;a href=&quot;#WhenVCSTool1&quot;&gt;[1]&lt;/a&gt;&lt;/small&gt;&lt;/sup&gt; both open and close sourced. You can find articles that discuss the pros and cons of distributed VCSs vs centralized ones. However, I don&#39;t recall ever seeing one about &lt;em&gt;when&lt;/em&gt; to choose one. The following is my opinion on this seemingly under-discussed topic.&lt;br /&gt;
&lt;br /&gt;
The quote above is one of many similar statements I&#39;ve seen over the years. It wouldn&#39;t surprise me if many project startup policies include choice of VCS as one of their bullet points. So, I&#39;m not picking on this particular article, it just presents some common wisdom that I don&#39;t consider all that wise and I&#39;m using it as a jumping off point to open the discussion.&lt;br /&gt;
&lt;br /&gt;
First some context. Most of my career has been in developing shrink wrap software. The projects I work on are small parts of larger products that in turn are one of many that make up a company&#39;s product line.&lt;br /&gt;
&lt;br /&gt;
The VCS contains vital enterprise assets. It should contain everything needed to build the current products for a company: the source code, build scripts, installer scripts, developer environment configuration scripts. It should also contain all the supporting documentation for users, both external and internal. Because it maintains versions of all these files, it also contains metadata about all them. It tracks who changed what, when and, if good change set notes are used, why. It may also be linked to an issue tracker, putting those changes in a larger context than just the source code. There may be a CRM system that gets linked to it. It is one piece of a larger whole.&lt;br /&gt;
&lt;br /&gt;
For a development group to start a new project and consider what VCS they&#39;re going to use is like the accounting department opening a new checking account and considering what accounting package they&#39;re going to track the transactions in. The accounting department will have an existing system in place that tracks more than simple checking registry entries. They would not change this just for a single account. In the same way, the development group should have existing systems in place to handle not just VCS but all the support systems that surround a project. They should keep all the projects in the same ecosystem.&lt;br /&gt;
&lt;br /&gt;
Keeping everything in one place does a number of things. It decreases startup time; there&#39;s one less decision to make. It reduces training; developer&#39;s don&#39;t need to become proficient in yet another tool. It eliminates confusion about &quot;where do I go to get X?&quot; It enhances cohesion among projects; it&#39;s easier to share code that may be common. It reduces maintenance costs; there&#39;s one less server that needs to be provisioned, integrated, maintained, backed up, and so on.&lt;br /&gt;
&lt;br /&gt;
In my opinion, choice of VCS is something that should be done long before any particular project starts and should not be within the purview of any single project. So, when I read something that says a new project is a good time to choose a version control system, by initial, totally biased reaction is to scream &quot;NO!&quot;&lt;sup&gt;&lt;small&gt;&lt;a href=&quot;#WhenVCSTool2&quot;&gt;[2]&lt;/a&gt;&lt;/small&gt;&lt;/sup&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;hr/&gt;&lt;div id=&quot;WhenVCSTool1&quot; style=&quot;margin-left:2em;text-indent:-2em&quot;&gt;1. And in fact that was the focus of the above article.&lt;/div&gt;&lt;div id=&quot;WhenVCSTool2&quot; style=&quot;margin-left:2em;text-indent:-2em&quot;&gt;2. And the same could be said, to varying degrees, of any software project support tool, be it VCS as discussed here or issue tracking or process control or documentation tools or build tools or UI widget libraries or IDEs or -- the list can go on and on.&lt;/div&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2013/11/when-is-right-time-to-select-source.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-2316936719549235066</guid><pubDate>Fri, 03 May 2013 21:40:00 +0000</pubDate><atom:updated>2013-05-03T15:42:15.245-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">design</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><title>Extension methods are cool</title><description>&lt;blockquote&gt;You are creating a vocabulary, not writing a program. Be a poet for a moment.&lt;br /&gt;
&lt;p style=&quot;text-align:right&quot;&gt;&lt;cite&gt;-- Kent Beck&lt;/cite&gt;&lt;/p&gt;&lt;/blockquote&gt;When Microsoft first introduced extension methods to C#, my first reaction was &quot;eh&quot;. I viewed them as a novelty without much use. As time has worn on, I&#39;ve come to appreciate them more and more. Their biggest win for me is to add features to basic system defined types and to fix what I consider deficiencies in the .Net libraries.&lt;br /&gt;
&lt;br /&gt;
Static methods that take as a parameter an instance of the class they are defined in really annoy me. One frequent irritation: &lt;code&gt;string.IsNullOrEmpty()&lt;/code&gt;. Every time I go to use this I always start writing the variable I want to test and then realize the method is static and have to go back and insert the &quot;string.IsNullOrEmpty&quot; at the front. This is simply one of many, many other similar methods spread throughout the framework with this.&lt;br /&gt;
&lt;br /&gt;
Shortly after extension methods were added, one day while I was again grumbling at the IsNullOrEmpty implementation, I realized this would be an easy thing to fix. About five minutes later, after figuring out the syntax for extension methods, I had something like:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static class StringExtensions
{
&amp;nbsp; &amp;nbsp; &amp;nbsp;public static bool IsNullOrEmpty(this string target)
&amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return string.IsNullOrEmpty(target);
&amp;nbsp; &amp;nbsp; &amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Now I could write tests in the much more natural (for me) &quot;if (someString.IsNullOrEmpty())...&quot; format. Personally I find this much easier to read.&lt;br /&gt;
&lt;br /&gt;
Flush with this success I immediately added another library function I remembered from Delphi that, in my opinion, helps with readability:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static class ObjectExtensions
{
&amp;nbsp; &amp;nbsp; &amp;nbsp;public static bool IsAssigned(this object target)
&amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return target != null;
&amp;nbsp; &amp;nbsp; &amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Instead of &quot;if (someObj != null)...&quot; I could now say &quot;if (someObj.IsAssigned())...&quot;&lt;br /&gt;
&lt;br /&gt;
There is a real downside I with this though: Resharper does not recognize this as a test for null and reports a possible null value warning on subsequent accesses. &lt;br /&gt;
&lt;br /&gt;
I&#39;ll admit, these aren&#39;t earth-shaking, industry-changing algorithms. But in day-in, day-out coding, I find the resulting code much easier to read.&lt;br /&gt;
&lt;br /&gt;
Today I threw together a couple extensions to simplify work with Points, Rectangles and ranges:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static Extensions&lt;/code&gt;
{
&amp;nbsp; &amp;nbsp; &amp;nbsp;public static Point Center(this Rectangle bounds)&lt;/code&gt;
&amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; &amp;nbsp; return new Point((bounds.Left + bounds.Width) / 2, (bounds.Top + bounds.Height) / 2);
&amp;nbsp; &amp;nbsp; &amp;nbsp;}

&amp;nbsp; &amp;nbsp; &amp;nbsp;public static double DistanceTo(this Point p1, Point p2)
&amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;return Math.Sqrt(Math.Pow(p1.X - p2.X, 2) + Math.Pow(p1.Y - p2.Y, 2));
&amp;nbsp; &amp;nbsp; &amp;nbsp;}

&amp;nbsp; &amp;nbsp; &amp;nbsp;public static int ConstrainTo(this int constrainedValue, int min, int max)
&amp;nbsp; &amp;nbsp; &amp;nbsp;{
&amp;nbsp; &amp;nbsp; &amp;nbsp;&amp;nbsp; &amp;nbsp; &amp;nbsp;return Math.Max(min, Math.Min(constrainedValue, max));
&amp;nbsp; &amp;nbsp; &amp;nbsp;}
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
With these, I transformed a method where the purpose was lost in all the notation to one where the purpose was eminently clear. Extension methods truly enable the craftsman to apply the opening quote from Kent Beck. They easily allow the developer to introduce, at the application level, domain vocabulary to system and other 3rd party classes.&lt;br /&gt;
&lt;br /&gt;
Yes, extension methods are pretty cool!&lt;br /&gt;
&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2013/05/extension-methods-are-cool.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-6336124591568710518</guid><pubDate>Fri, 12 Apr 2013 12:00:00 +0000</pubDate><atom:updated>2013-04-12T06:00:13.667-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">HowTo</category><category domain="http://www.blogger.com/atom/ns#">installation</category><category domain="http://www.blogger.com/atom/ns#">JetBrains</category><category domain="http://www.blogger.com/atom/ns#">Microsoft</category><category domain="http://www.blogger.com/atom/ns#">problem</category><category domain="http://www.blogger.com/atom/ns#">Resharper</category><category domain="http://www.blogger.com/atom/ns#">VirtualBox</category><category domain="http://www.blogger.com/atom/ns#">VS2012</category><title>Unit Tests Not Found in VS2012 and How It Was Fixed (partially)</title><description>I am setting up a virtual machine for a new upcoming project. It will use some core libraries that have already been developed in-house with Visual Studio 2012 as the development environment. The team that developed the existing libraries did a good job to make sure there was a suite of unit tests that worked and was reasonably comprehensive. So, after I installed VS2012 and Resharper I retrieved the code from the repository, compiled it and tried to run the unit tests.&lt;br /&gt;
&lt;br /&gt;
The Resharper test runner (the one I normally use) listed all the tests and reported their status as &quot;Inconclusive. Test not run.&quot;&lt;br /&gt;
&lt;br /&gt;
The test runner built into Visual Studio didn&#39;t list any tests at all. Zip. Nada. Nothing.&lt;br /&gt;
&lt;br /&gt;
A web search revealed some posts indicating there was a compatibility issue between VS2012 and Resharper that was supposedly fixed in VS2012&#39;s Update 2. I downloaded and installed the update.&lt;br /&gt;
&lt;br /&gt;
After this, Resharper listed all the tests and reported their status as &quot;Pending&quot; without doing anything further. A change, but arguably not as good as before. To exit with things pending just seems strange. At least the previous &quot;Inconclusive&quot; state gives a sense that something&#39;s wrong, even if it doesn&#39;t say what.&lt;br /&gt;
&lt;br /&gt;
On the other hand, Microsoft&#39;s test runner... still did the same thing. Absolutely no indication that any tests even existed.&lt;br /&gt;
&lt;br /&gt;
After quite a bit more searching, chanting various incantations and sacrificing not a few livestock, I stumbled upon an ancient forum post from early last summer when VS2012 was still gestating as an RC. It indicated there was a bug with unit tests when they existed on a network share.&lt;br /&gt;
&lt;br /&gt;
Hmm. I wanted my VM to be just the build environment and had placed the source code on a shared folder that was mapped alongside all the other source code on the host machine&#39;s disk. I wondered what would happen if I moved the code to the C: drive.&lt;br /&gt;
&lt;br /&gt;
As soon as I loaded the project from its new location on C:, Microsoft&#39;s test runner immediately found and ran the tests.&lt;br /&gt;
&lt;br /&gt;
Unfortunately, Resharper&#39;s still doesn&#39;t work. It continues to set them to &quot;pending&quot; and never does anything else. Apparently this is a &lt;a href=&quot;http://devnet.jetbrains.com/message/5484329#5484329&quot;&gt;known issue&lt;/a&gt; that hopefully will be fixed soon.&lt;br /&gt;
&lt;br /&gt;
(Hopefully I&#39;ve added enough keywords to this that others will be able to find this problem and solution without having to spill blood all over the keyboard.)&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2013/04/unit-tests-not-found-in-vs2012-and-how.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-7690466478285269066</guid><pubDate>Thu, 06 Dec 2012 13:00:00 +0000</pubDate><atom:updated>2012-12-06T06:00:13.768-07:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">Debugging</category><category domain="http://www.blogger.com/atom/ns#">Microsoft</category><category domain="http://www.blogger.com/atom/ns#">problem</category><category domain="http://www.blogger.com/atom/ns#">UI</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>Apparent binding problems with NotSupportedException in PresentationFramework</title><description>I ran into this problem twice over the last couple weeks. Perhaps if I write an article, it&#39;ll help my future self (and just perhaps someone else) not spend so much time on it...&lt;br /&gt;
&lt;br /&gt;
I put together a simple WPF form with a ListView. The ListLiew&#39;s View contained a GridView with columns bound to a POCO&#39;s properties. This was all done in XAML. In the constructor, I created an ObservableCollection to contain the objects and set it to the ListView&#39;s ItemsSource property. An event fired when interesting things happened. The event handler created the POCO object, set its properties and added it to the collection.&lt;br /&gt;
&lt;br /&gt;
Everything should have worked.&lt;br /&gt;
&lt;br /&gt;
However, when items were added to the collection, the debug window reported:&lt;blockquote&gt;&lt;code style=&quot;font-size:80%&quot;&gt;A first chance exception of type &#39;System.NotSupportedException&#39; occurred in PresentationFramework.dll&lt;/code&gt;&lt;/blockquote&gt;Over the years, I&#39;ve found data binding to be a challenge to get working. Part of the problem is it&#39;s mostly silent when it fails. So, data simply doesn&#39;t show up where it&#39;s expected with no indication as to why. Because of this, I assumed this is where the problem lay and spent significant time trying to figure out what was happening.&lt;br /&gt;
&lt;br /&gt;
After quite a while I realized the event handler was called from a non-UI thread. I changed the line that added objects to the collection from:&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;ListViewDetails.Add(detailData);&lt;/code&gt;&lt;/pre&gt;to:&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;Dispatcher.Invoke((Action)(() =&gt;
    ListViewDetails.Add(detailData)));&lt;/code&gt;&lt;/pre&gt;and everything worked properly. A simple solution once I realized what was wrong.&lt;br /&gt;
&lt;br /&gt;
It&#39;d be really nice if the debug window would output the exception message and not just the type. This would have told me immediately what was wrong and I wouldn&#39;t have spent so much time going down a dead-end road.&lt;br /&gt;
&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2012/12/apparent-binding-problems-with.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-2128472050505218630</guid><pubDate>Wed, 31 Oct 2012 12:00:00 +0000</pubDate><atom:updated>2012-10-31T06:00:00.548-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">HowTo</category><category domain="http://www.blogger.com/atom/ns#">problem</category><category domain="http://www.blogger.com/atom/ns#">VisualStudio</category><title>Sandcastle Help File Builder and error MSB4062 on Team 2008 build agents</title><description>I recently had to add a &lt;a href=&quot;http://shfb.codeplex.com/&quot;&gt;Sandcastle Help File Builder&lt;/a&gt; task to our automated build process. Our product consists of both .Net 3.5 projects and native C++ projects. It compiles under Visual Studio 2008 with Team 2008 build agents.&lt;br /&gt;
&lt;br /&gt;
The latest version of Sandcastle is built against .Net 4.0, so, as part of its installation, I also installed the .Net 4.0 runtime. Everything worked fine in the GUI but when the build agent tried to run, it failed with:&lt;blockquote&gt;error MSB4062: The &quot;SandcastleBuilder.Utils.MSBuild.BuildHelp&quot; task could not be loaded from the assembly C:\Program Files\EWSoftware\Sandcastle Help File Builder\\SandcastleBuilder.Utils.dll. Could not load file or assembly &#39;file:///C:\Program Files\EWSoftware\Sandcastle Help File Builder\SandcastleBuilder.Utils.dll&#39; or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded. Confirm that the &amp;lt;UsingTask&gt; declaration is correct, and that the assembly and all its dependencies are available.&lt;/blockquote&gt;&lt;br /&gt;
The UsingTask declaration appeared correct and all the dependencies seemed to be in order. I searched for quite a while and found several places purporting to have answers, but none of them worked. As I expanded my search, I finally happened upon an &lt;a href=&quot;http://blogs.infosupport.com/building-visual-studio-2010-solutions-using-team-build-2008/&quot;&gt;InfoSupport article about building VS2010 solutions with the 2008 build agent&lt;/a&gt;. This article described a means to fix a problem with a similar error message and, even though it wasn&#39;t related to Sandcastle, I decided to give it a try.&lt;br /&gt;
&lt;br /&gt;
Short answer: it worked!!&lt;br /&gt;
&lt;br /&gt;
The fix feels more like a hacky workaround than a good solution, but absent anything better, and given the fact that it allows the build to actually function properly, it currently stands.&lt;br /&gt;
&lt;br /&gt;
The solution is to change a setting in a .Net configuration file.&lt;ol&gt;&lt;li&gt;Edit &lt;em&gt;%Program Files%\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\TFSBuildService.exe.config&lt;/em&gt;.&lt;/li&gt;&lt;li&gt;Find the line that assigns a value to the key &lt;em&gt;MSBuildPath&lt;/em&gt;.&lt;/li&gt;&lt;li&gt;Change the value from an empty string to the directory of the .Net runtime that should be used, e.g. &lt;em&gt;%WINDOWS%\Microsoft.NET\ Framework\v4.0.30319&lt;/em&gt;.&lt;/li&gt;&lt;li&gt;Save the file.&lt;/li&gt;&lt;li&gt;Either stop/stop the TFS build agent service or reboot the machine.&lt;/li&gt;&lt;/ol&gt;&lt;br /&gt;
I hope that helps someone else.&lt;br /&gt;
&lt;br /&gt;
&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2012/10/sandcastle-help-file-builder-and-error.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-6706596166596351751</guid><pubDate>Thu, 19 Jul 2012 12:00:00 +0000</pubDate><atom:updated>2012-07-26T10:52:42.926-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">rant</category><title>Are Coding Philosophies Irrelevant?</title><description>I recently read a &lt;a href=&quot;http://prog21.dadgum.com/142.html&quot;&gt;&lt;span style=&quot;text-decoration:line-through;&quot;&gt;rant&lt;/span&gt; opinion piece&lt;/a&gt; about how the behind the scenes part of an application is irrelevant. The author had some good points. One was, from an end user&#39;s perspective, how an application is put together is irrelevant. Another one was that success in the marketplace is not determined by which patterns are used, what the development tool-chain looks like or which language is used. I agree with all this. However he went on to say that therefore, these behind-the-scenes things are irrelevant.&lt;br /&gt;
&lt;br /&gt;
To this I respectfully disagree. If the code base for an application is only to instruct the computer how to do something now, then I suppose the author might have a point. But, I think the author forgot that the end user is only one user of the application and source code is important for more than the current compile. Another very important user is the developer. Over the course of an application&#39;s lifetime, there might be many developers who will work with that code. Or there might be one who maintains it for its entire life. In either case, the source is used as much, if not more, to communicate to those reading the code what is going on as it is for the computer.&lt;br /&gt;
&lt;br /&gt;
The computer just does as it&#39;s told. It doesn&#39;t care what it&#39;s told or the meaning behind the why or how. It doesn&#39;t have any concept about patterns or tool-chains or philosophies. These things are not used to communicate intent to the computer. As a simplistic example, the assignment of the sum of y and z to x, to the computer is meaningless. It doesn&#39;t care why this addition is done, or the importance of assigning the result to one place over another. The mechanics of line&lt;blockquote&gt;x = y + z&lt;/blockquote&gt;are clear to both computer and programmer but it could mean anything. And, the meaning is irrelevant to the computer. But, to the developer, it is crucial to understanding the bigger picture.&lt;br /&gt;
&lt;br /&gt;
To the computer, these two lines are equivalent to the one above.&lt;br /&gt;
&lt;blockquote&gt;balance = beginningBalance + deposit&lt;/blockquote&gt;&lt;blockquote&gt;newHeading = currentHeading + errorDelta&lt;/blockquote&gt;However, to a developer, assuming the variable names are accurate for the problem domain, they communicate very different things.&lt;br /&gt;
&lt;br /&gt;
In the same way, other more abstract organizations of how a given piece of software is written communicate, to various degrees and with various success, important information to the developer. Patterns, tool-chains and coding philosophies are irrelevant to the compiler. To the developer, they can, if effectively used, convey information crucial to understanding the problem the software attempts to solve and the original author&#39;s vision of how to do it.&lt;br /&gt;
&lt;br /&gt;
In the greater scheme of things, they are far from being irrelevant.&lt;br /&gt;
&lt;br /&gt;
They are critical.&lt;br /&gt;
&lt;br /&gt;
&lt;hr/&gt;Update: I just ran across this quote I thought was appropriate:&lt;blockquote&gt;The best programs are written so that computing machines can perform them quickly and so that human beings can understand them clearly. A programmer is ideally an essayist who works with traditional aesthetic and literary forms as well as mathematical concepts, to communicate the way that an algorithm works and to convince a reader that the results will be correct.&lt;br/&gt;-- &lt;cite&gt;Donald E. Knuth, &lt;i&gt;Selected Papers on Computer Science&lt;/i&gt;&lt;/cite&gt;&lt;/blockquote&gt;And this reminded me of another quote:&lt;blockquote&gt;You&#39;re creating a vocabulary, not writing a program. Be a poet for a moment.&lt;br/&gt;-- &lt;cite&gt;Kent Beck&lt;/cite&gt;&lt;/blockquote&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2012/07/are-coding-philosophies-irrelevant.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-3608744536173690168</guid><pubDate>Fri, 22 Jun 2012 07:11:00 +0000</pubDate><atom:updated>2012-06-22T01:25:01.394-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">Delphi</category><category domain="http://www.blogger.com/atom/ns#">dictionary</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><title>List all values of an enumeration</title><description>I&#39;m probably late to the party on this one, but I recently discovered a cool, handy little static method tucked away in the Enum class: GetValues. It simply returns all the values of an enum type. This enables nifty things like:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public enum TestEnum
{
    Value1,
    Value2,
    Value3,
    Value4
};

public void ShowEnumValues()
{
    Enum.GetValues(typeof (TestEnum))
        .Cast&amp;lt;TestEnum&gt;()
        .ToList()
        .ForEach(e =&gt; Console.WriteLine(e));
}&lt;/code&gt;&lt;/pre&gt;With this, any changes to TestEnum automatically get picked up at run-time without any additional changes to the rest of the code.&lt;br /&gt;
&lt;br /&gt;
Last year, I wrote about &lt;a href=&quot;http://www.skylark-software.com/2011/05/non-int-array-indexes-from-delphi-in-c.html&quot;&gt;using a dictionary to facilitate converting between an enum and human readable text&lt;/a&gt;. To adapt the code presented then to the above example, the following will convert all values in the enum to human readable text.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;private IDictionary&amp;lt;TestEnum, string&gt; enumToString =
    new Dictionary&amp;lt;TestEnum, string&gt;
        {
            {TestEnum.Value1, &quot;Value one&quot;},
            {TestEnum.Value2, &quot;Value two&quot;},
            {TestEnum.Value3, &quot;Value three&quot;},
            {TestEnum.Value4, &quot;Value four&quot;}
        };

public void ShowEnumStrings()
{
    Enum.GetValues(typeof(TestEnum))
        .Cast&amp;lt;TestEnum&gt;()
        .ToList()
        .ForEach(e =&gt; Console.WriteLine(enumToString[e]));
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
In the previous article, I lamented the fact that this C# solution, unlike the Pascal variant, does not provide a reliable means to check that all the values of the enumeration have a corresponding entry in the dictionary. Because of strong typing with generics, I know I can&#39;t have any thing that&#39;s not part of the enumeration in the dictionary, but I can&#39;t know I have all the values of the enumeration in the dictionary. In other words, I know I can&#39;t have any invalid values, but I can&#39;t know I have all the values.&lt;br /&gt;
&lt;br /&gt;
Until I found this method. Now I can at least write an easy test case for this. While it&#39;s not quite as good as a compile time check, it does give an early, reliable means of being alerted to the problem.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;[TestMethod]
public void EnsureAllEnumValuesAreInDictionary()
{
    Assert.IsTrue(
        Enum.GetValues(typeof(TestEnum))
            .Cast&amp;lt;TestEnum&gt;()
            .All(type =&gt; EnumToString.ContainsKey(type)),
        &quot;Enum value missing from enumToString dictionary&quot;);
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Since variables of this type typically do not change from instance to instance, they can be made static so they&#39;re only instantiated once. And since many times they are only used inside a single class, they can be made private. In these cases having a unit test might be problematic, not being able to test a private field. To solve this, code similar to the above test can be put in a static constructor, throwing an exception if there&#39;s a mismatch. &lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;private static readonly IDictionary&amp;lt;TestEnum, string&gt; EnumToString =
    new Dictionary&amp;lt;TestEnum, string&gt;
        {
            {TestEnum.Value1, &quot;Value one&quot;},
            {TestEnum.Value2, &quot;Value two&quot;},
            {TestEnum.Value3, &quot;Value three&quot;},
            {TestEnum.Value4, &quot;Value four&quot;}
        };

static UnitTest1()
{
    if (!Enum.GetValues(typeof (TestEnum))
             .Cast&amp;lt;TestEnum&gt;()
             .All(type =&gt; EnumToString.ContainsKey(type)))
        throw new InvalidOperationException(
            &quot;Enum value missing from enumToString dictionary&quot;);
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Finally, if this needs to be done much, making a generic helper function will clean-up code, hiding all the casting and repetition of the type.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;private static IEnumerable&amp;lt;T&gt; GetEnumValues&amp;lt;T&gt;()
{
    return Enum.GetValues(typeof (T)).Cast&amp;lt;T&gt;();
}

[TestMethod]
public void EnsureAllEnumValuesAreInDictionary1()
{
    Assert.IsTrue(
        GetEnumValues&lt;testenum&gt;().All(type =&gt; EnumToString.ContainsKey(type)),
        &quot;Enum value missing from enumToString dictionary&quot;);
}
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
All in all, I&#39;m pleased with finding this little nugget.&lt;br /&gt;
&lt;br /&gt;
A complete VS2008 solution containing the code examples above is &lt;a href=&quot;https://github.com/hpebley3/EnumEnumerationExample&quot;&gt;available on github&lt;/a&gt;.&lt;br /&gt;
&lt;br /&gt;
Hope this helps someone else.&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2012/06/list-all-values-of-enumeration.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-1259279928517411488</guid><pubDate>Mon, 04 Jun 2012 12:00:00 +0000</pubDate><atom:updated>2012-06-04T06:00:12.855-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">LINQ</category><category domain="http://www.blogger.com/atom/ns#">problem</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><title>Functional FizzBuzz in C#</title><description>Back when &lt;a href=&quot;http://www.codinghorror.com/blog/2007/02/why-cant-programmers-program.html&quot;&gt;Jeff Atwood first wrote about FizzBuzz,&lt;/a&gt; I implemented it a number of different ways in Delphi. It was an interesting exercise; I think I came up with around five different ways to implement it. I also did some performance testing and was surprised by the results. Perhaps someday I&#39;ll try to find that code and publish it. Over the years since, I&#39;ve used it, or variations, in interviews and have been surprised at how many applicants it weeded out.&lt;br /&gt;
&lt;br /&gt;
Recently I ran across an &lt;a href=&quot;http://www.trelford.com/blog/post/FizzBuzz.aspx&quot;&gt;article listing several ways to do it in various functional languages&lt;/a&gt; and wondered how functional I could code it in C#. So, I fired up Visual Studio and created a new console project. I didn&#39;t think my first attempt was too bad.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;namespace FunctionalFizzBuzz
{
  class Program
  {
    static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
    {
      return showFizz &amp;&amp; showBuzz
        ? &quot;FizzBuzz&quot;
        : showFizz
          ? &quot;Fizz&quot;
          : showBuzz
            ? &quot;Buzz&quot;
            : val.ToString(CultureInfo.InvariantCulture);
    }

    static string GenerateFizzBuzz(int start, int end)
    {
      return Enumerable
        .Range(start, end)
        .Aggregate(new StringBuilder(), (seed, val) =&gt;
          {
            seed.AppendLine(FizzBuzzResult(val % 3 == 0, val % 5 == 0, val));
            return seed;
          })
        .ToString();
    }

    static void Main(string[] args)
    {
      Console.WriteLine(GenerateFizzBuzz(1, 100));
    }
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
However, there were a couple things I didn&#39;t like about it. First, returning the whole result as a string seemed a bit overkill and intuitively not too memory friendly. For purposes of displaying 100 lines, it&#39;s not too bad, but for a more general use case, it&#39;s not good for composition. Second, the use of Aggregate bothered me a bit. How it works is not obvious to most people when first seeing it; it&#39;s use is a bit obtuse. And concatenating a bunch of strings just felt wrong.&lt;br /&gt;
&lt;br /&gt;
So, I replaced the string result with an IEnumerable&lt;string&gt;. This allowed changes which I think expresses the intent better. First, the Aggregate could be be changed to a Select, clarifying the GenerateFizzBuzz method. Second, the call to Console.WriteLine to generate each output line could be passed as a parameter to an iterator function. This is an example of how the new method makes it easier to use the output for different things. Another example is to count how many &quot;Fizz&quot; lines there are.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;static IEnumerable&lt;string&gt; GenerateFizzBuzz(int start, int end)
{
  return Enumerable
    .Range(start, end-start+1)
    .Select(val =&gt; FizzBuzzResult(val % 3 == 0, val % 5 == 0, val));
}

static void Main(string[] args)
{
  var result = GenerateFizzBuzz(1, 100).ToList();
  result.ForEach(Console.WriteLine);
  Console.WriteLine(&quot;Number of Fizzes: {0}&quot;, results.Count(l =&gt; l == &quot;Fizz&quot;));
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
With the GenerateFizzBuzz method cleaned up some, my attention turned to the FizzBuzzResult method. I wasn&#39;t terribly happy with the multiple nested conditional statement. While functional, it seemed more computational than declarative to me. What it did was a bit opaque. I like the parameter pattern matching available in the more functional languages and wondered how I could do something similar. I couldn&#39;t think of a way to let the compiler do it and regular expressions (the only pattern matching I can think of in the .Net libraries) only works on strings. However, it seemed pretty straight forward using a data structure.&lt;br /&gt;
&lt;br /&gt;
I created a dictionary with a boolean key and dictionary value. The nested dictionary also had a boolean key but with a string value. I initialized these with the four possible values. The case which should return the numeric value was set to null. Then then the result was simply the lookup value of the dictionaries unless it returned null, in which case it was the passed in value, converted to a string.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;private static readonly Dictionary&amp;lt;bool, Dictionary&amp;lt;bool, string&gt;&gt;
  FizzBuzzMap =
    new Dictionary&amp;lt;bool, Dictionary&amp;lt;bool, string&gt;&gt;
      {
        {true, new Dictionary&amp;lt;bool, string&gt; {{true, &quot;FizzBuzz&quot;}, {false, &quot;Fizz&quot;}}},
        {false, new Dictionary&amp;lt;bool, string&gt; {{true, &quot;Buzz&quot;}, {false, null}}}
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[showFizz][showBuzz] ?? val.ToString(CultureInfo.InvariantCulture);
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
I liked the way FizzBuzzResult looked, but the initialization code for the dictionaries was a bit ugly to my eye. I tried changing it to a single dictionary containing an array of booleans as the key.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;private static readonly Dictionary&amp;lt;bool[], string&gt;
  FizzBuzzMap =
    new Dictionary&amp;lt;bool[], string&gt;
      {
        {new[] {true, true}, &quot;FizzBuzz&quot;},
        {new[] {true, false}, &quot;Fizz&quot;},
        {new[] {false, true}, &quot;Buzz&quot;},
        {new[] {false, false}, null},
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[new [] {showFizz, showBuzz}] ?? val.ToString(CultureInfo.InvariantCulture);
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Ah, this looked much nicer. But... it raised a key not found exception. Oops. Fail. I hypothesized the key comparison during lookup looked at the arrays as objects, rather than the values they contained, and so raised the exception. I quickly wrote a comparison class for the dictionary and passed in an instance of it.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;internal class BoolArrayComparer : IEqualityComparer&lt;bool[]&gt;
{
  public bool Equals(bool[] x, bool[] y)
  {
    if (x.Length != y.Length)
      return false;
    return !x.Where((t, i) =&gt; t != y[i]).Any();
  }

  public int GetHashCode(bool[] obj)
  {
    return obj.Aggregate(0, (seed, val) =&gt; seed + val.GetHashCode());
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
Sure enough, it now worked properly. So the initialization looked pretty, but at the expense of having to have this extra, ugly class floating around spoiling things. Reflecting on the prior solution with the arrays, I realized structures have slightly different semantics and might work better with comparison. I changed the boolean array to a two member structure.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;internal struct FizzBuzzKey
{
  internal bool showFizz;
  internal bool showBuzz;
};

private static readonly Dictionary&lt;FizzBuzzKey, string&gt;
  FizzBuzzMap =
    new Dictionary&lt;FizzBuzzKey, string&gt;
      {
        {new FizzBuzzKey {showFizz = true, showBuzz = true}, &quot;FizzBuzz&quot;},
        {new FizzBuzzKey {showFizz = true, showBuzz = false}, &quot;Fizz&quot;},
        {new FizzBuzzKey {showFizz = false, showBuzz = true}, &quot;Buzz&quot;},
        {new FizzBuzzKey {showFizz = false, showBuzz = false}, null},
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[new FizzBuzzKey {showFizz = showFizz, showBuzz = showBuzz}] ?? val.ToString(CultureInfo.InvariantCulture);
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
And this worked without requiring a Comparer class. But it&#39;s quite a bit more verbose than the array notation; I really liked the succinctness of the array notation. Then I remembered structs can have constructors. I added one and this helped cut down the verbosity quite a bit.&lt;br /&gt;
&lt;br /&gt;
So, in the end I finished this little exercise with the following.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;namespace FunctionalFizzBuzz
{
  internal class Program
  {
    internal struct FizzBuzzKey
    {
      internal FizzBuzzKey(bool showF, bool showB)
      {
        showFizz = showF;
        showBuzz = showB;
      }

      internal bool showFizz;
      internal bool showBuzz;
    };

    private static readonly Dictionary&lt;FizzBuzzKey, string&gt;
      FizzBuzzMap =
        new Dictionary&lt;FizzBuzzKey, string&gt;
          {
            {new FizzBuzzKey (true, true), &quot;FizzBuzz&quot;},
            {new FizzBuzzKey (true, false), &quot;Fizz&quot;},
            {new FizzBuzzKey (false, true), &quot;Buzz&quot;},
            {new FizzBuzzKey (false, false), null},
          };

    static void Main(string[] args)
    {
      var results = Enumerable
        .Range(90, 11)
        .Select(val =&gt; FizzBuzzResult(val%3 == 0, val%5 == 0, val))
        .ToList();
      results.ForEach(Console.WriteLine);
      Console.WriteLine(&quot;Number of Fizzes: {0}&quot;, results.Count(l =&gt; l == &quot;Fizz&quot;));
    }

    private static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
    {
      return FizzBuzzMap[new FizzBuzzKey(showFizz, showBuzz)] ?? val.ToString(CultureInfo.InvariantCulture);
    }
  }
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
&lt;h3&gt;Final thoughts&lt;/h3&gt;One solution I considered during this process was to map the four values of booleans to integers and do a lookup after a conversion. Intuitively, I didn&#39;t like the approach because it added an extra level of abstraction. Levels of abstraction can be good if they clarify. However, in this case, I thought it would simply obfuscate. In spite of this, out of desire to be complete, I threw this implementation together too.&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;private static readonly Dictionary&lt;int, string&gt;
  FizzBuzzMap =
    new Dictionary&lt;int, string&gt;()
      {
        {3 /* true, true */, &quot;FizzBuzz&quot;},
        {2 /* true, false */, &quot;Fizz&quot;},
        {1 /* false, true */, &quot;Buzz&quot;},
        {0 /* false, false */, null},
      };

static string FizzBuzzResult(bool showFizz, bool showBuzz, int val)
{
  return FizzBuzzMap[(val%3 == 0 ? 1 : 0) + (val%5 == 0 ? 1 : 0)] ?? val.ToString(CultureInfo.InvariantCulture);
}&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
But it didn&#39;t work. It emitted &quot;Buzz&quot; in places it should have output &quot;Fizz.&quot; But not all the time. It took me a minute or two to find it.&lt;br /&gt;
&lt;br /&gt;
Can you spot the error?&lt;br /&gt;
&lt;br /&gt;
&lt;div id=&quot;toggleVisibilityFizzBuzz1&quot;&gt;&lt;a href=&quot;#fizzbuzzbug&quot; onclick=&quot;{
       var e = document.getElementById(&#39;toggleVisibilityFizzBuzz1&#39;);
          e.style.display = &#39;none&#39;;
       var e = document.getElementById(&#39;toggleVisibilityFizzBuzz2&#39;);
          e.style.display = &#39;block&#39;;
    }&quot;&gt;Click here to see answer&lt;/a&gt;&lt;/div&gt;&lt;div style=&quot;display: none;&quot; id=&quot;toggleVisibilityFizzBuzz2&quot; name=&quot;fizzbuzzbug&quot;&gt;The key for the FizzBuzzMap should actually be:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;(val%3 == 0 ? 2 : 0) + (val%5 == 0 ? 1 : 0)&lt;/code&gt;&lt;/pre&gt;&lt;/div&gt;&lt;br /&gt;
The fact that 1) this was the first bug I&#39;d produced during this exercise, 2) it wasn&#39;t immediately obvious what the problem was and 3) the need for the comments in the setup, all confirmed my suspicion this is not a good solution.&lt;br /&gt;
&lt;br /&gt;
Two other things I vacillated over was whether FizzBuzzResult needed to be a separate routine and, if so, what its parameters should be. At times I&#39;d roll it into the main routine and other times I&#39;d pass in just the numeric value and yet other times I&#39;d pass in the three parameters as shown. I concluded that a toy exercise like this is too small to really have a clear winner in this debate. Additional use cases provided by a larger application would probably make one of these various options a clear winner.&lt;br /&gt;
&lt;br /&gt;
After going through this process, I did a web search on &lt;a href=&quot;https://www.google.com/search?hl=en&amp;q=C%23+functional+fizzbuzz&quot;&gt;&quot;C# functional FizzBuzz&quot;&lt;/a&gt; and found a number of solutions &lt;a href=&quot;http://metadeveloper.blogspot.com/2009/09/fizzbuzz-functional.html&quot;&gt;including this interesting take&lt;/a&gt;.&lt;br /&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2012/06/functional-fizzbuzz-in-c.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-6019009352343893766</guid><pubDate>Mon, 02 Apr 2012 12:00:00 +0000</pubDate><atom:updated>2012-04-02T06:00:22.376-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">cursor</category><category domain="http://www.blogger.com/atom/ns#">design</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">resource</category><category domain="http://www.blogger.com/atom/ns#">WinForms</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>There and back again, again: Any resource&#39;s tale</title><description>&lt;h3&gt;Or, how to generically set and restore state when an exception is raised&lt;/h3&gt;&lt;p&gt;I&#39;ve written twice before (&lt;a href=&quot;http://www.skylark-software.com/2011/05/there-and-back-again-cursors-tale.html&quot;&gt;here&lt;/a&gt; and &lt;a href=&quot;http://www.skylark-software.com/2012/03/there-and-back-again-again-several.html&quot;&gt;here&lt;/a&gt;) about making cursor changes more robust with the using statement in C#. These allow states to be reset to correct values regardless of whether or not an exception is raised during some processing. As promised at the end of the last article, today I explain how to use lambdas to easily protect any type of &quot;resource&quot; without having to create a new class or sprinkle your code with try/finally blocks.&lt;/p&gt;&lt;p&gt;To set things up and provide a bit of context, the other day in a code review, I found this:&lt;/p&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;someFlag = true;
someStartStateMethod();
// Do some work
someResetStateMethod();
someFlag = false;&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;Over the years, I&#39;ve seen this pattern repeated, in different domains and different languages and not necessarily limited to setting a flag. Whenever I do, I ask &quot;if an exception happens anywhere in &#39;do some work,&#39; should the state be reset?&quot; I won&#39;t say the answer should always be &quot;yes,&quot; but I&#39;ve not yet found a &quot;no.&quot; And this case was no exception.&lt;/p&gt;&lt;p&gt;Since some of the places this was done was nested, I wanted a way to clean all this up that didn&#39;t involve adding try/finally blocks. Each try/finally would add another level of indentation; it would get pretty deep pretty fast. Also, it would clutter up the code with noise that didn&#39;t really have anything to do with the work needing to be done. In other words, I didn&#39;t want this:&lt;/p&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;someFlag = true;
try
{
   someStartStateMethod();
   try
   {
     // Do some work
   }
   finally
   {
      someResetStateMethod();
   }
}
finally
{
   someFlag = false;
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In my last article, I separated the code actually handling the protection from the code controlling the invocation of that protection by using inheritance. I created a base abstract class to handle the general IDisposable pattern and descendent classes to handle the actual protection. In that article, I showed a class to handle changing a cursor and then changing it back to the current value.&lt;/p&gt;&lt;p&gt;I quickly realized this code was simply another example of that pattern. I could do the same thing as earlier and put the &lt;em&gt;someStartStateMethod()&lt;/em&gt; and &lt;em&gt;someResetStateMethod()&lt;/em&gt; in a descendant class. If I followed that pattern, the code under review could be something more along the lines of:&lt;/p&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;using(new ChangeSomeFlag())
using(new ChangeSomeStateMethod())
{
   // Do some work
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;This is somewhat better.&lt;/p&gt;&lt;p&gt;However, in this case, creating a new class for each thing needing protection didn&#39;t seem too appealing. There would be a lot of small special purpose classes, some of which might only be used once. It seemed like a sledgehammer to drive a brad. For this code, I wanted to emphasize composition over inheritance.&lt;/p&gt;&lt;p&gt;Enter lambdas. Because lambdas allow you to treat code as data, they allow easy composition. The LINQ and Rx libraries are great examples. They provide many generic methods (e.g. Where, Select, Any) that have the ability to compose in functionality through the use of lambdas to work on specific types for specialized purposes.&lt;/p&gt;&lt;p&gt;In this particular case, lambdas can be used to contain the code that handles the protection and passed to a class whose sole job is to handle the invocation of that code at the appropriate time. Rewriting the previous example with a new, as yet undefined ResourceProtector class, its use looks like:&lt;/p&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;using(new ResourceProtector(() =&gt; someFlag = true, () =&gt; someFlag = false))
using(new ResourceProtector(() =&gt; someSetStateMethod(), () =&gt; someResetStateMethod()))
{
   // Do some work
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;In this code, two expressions are passed to the constructor of the ResourceProtector class that handle the saving and restoring of state. Here is a single class that can be reused over and over in different situations to protect different types of resources. I think this is a beautiful example of the single responsibility principle combined with the power of lambda expressions to handle composition.&lt;/p&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public class ResourceProtector : IDisposable
{
   private bool Disposed { get; set; }
   private Action EndProtection { get; set; }

   public ResourceProtector(Action startProtection, Action endProtection)
   {
      Disposed = false;
      EndProtection = endProtection;
      startProtection();
   }

   public void Dispose()
   {
      DisposeInt();
      GC.SuppressFinalize(this);
   }

   private void DisposeInt()
   {
      if (Disposed)
         return;

      EndProtection();
      Disposed = true;
   }

   ~ResourceProtector()
   {
      DisposeInt();
   }
}&lt;/code&gt;&lt;/pre&gt;&lt;p&gt;If you have any questions, suggestions or comments, please feel free to leave them below. Until next time, subscribe to the &lt;a href=&quot;http://twitter.com/skysoft&quot;&gt;Twitter feed&lt;/a&gt; to get notified of future articles and hear about other development related things.&lt;/p&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2012/04/there-and-back-again-again-any.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-462166181369098584</guid><pubDate>Wed, 21 Mar 2012 12:30:00 +0000</pubDate><atom:updated>2012-04-02T15:48:23.360-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">.Net</category><category domain="http://www.blogger.com/atom/ns#">benchmark</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">comparison</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><title>7 ways to remove duplicate strings from a list (with timing results)</title><description>Recently there was a &lt;a href=&quot;http://www.codeproject.com/Feature/clevercode.aspx?msg=4185820#xx4185820xx&quot;&gt;question on CodeProject&lt;/a&gt; about the fastest way to remove duplicate strings from a List&lt;string&gt;. There were a bunch of alternative solutions presented, but no comparison to see what was faster. This post will show each solution and time them in a standard way to determine which actually answers the question.&lt;br /&gt;
&lt;h4&gt;About the test&lt;/h4&gt;&lt;p&gt;Test setup creates a list of 1,000 random strings all 50 characters long. This is the expected result. It then creates duplicates for every other item and then for every 5th item. A list containing duplicates is created from the expected results and the duplicates. Note that for the even 5th items, there are actually two duplicates in the final list.&lt;/p&gt;&lt;p&gt;The core test method takes the list of duplicates, sets up a stopwatch and then calls the method to remove duplicates 1,000 times, each time passing in a new copy of the duplicate list. Since one of the methods under test changes the input list, this causes each iteration to work on the same, pristine input list. The elapsed time from the stopwatch is output and assertions are in place to make sure the method under test does what&#39;s expected.&lt;/p&gt;&lt;h4&gt;About the methods under test&lt;/h4&gt;I&#39;ve taken the code presented in the original thread and made slight modifications to make them all conform to the same interface. Some of them were code snippets or descriptions so I made my best guess as to the authors&#39; intent.&lt;br /&gt;
&lt;h4&gt;1. The original poster&#39;s solution&lt;/h4&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static IList&lt;string&gt; LoadUniqueList1(List&lt;string&gt; doubledList)
{
   var uniqueList = new List&lt;string&gt;();
   foreach (var item in doubledList)
   {
      var x = true;
      foreach (var compare in uniqueList)
      {
         if (item == compare)
         {
            x = false;
         }
         if (!x) break;
      }
      if (x)
         uniqueList.Add(item);
   }
   return uniqueList;
}&lt;/code&gt;&lt;/pre&gt;&lt;h4&gt;2. Same as above, except substituting Contains for the second loop&lt;/h4&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static IList&lt;string&gt; LoadUniqueList2(List&lt;string&gt; doubledList)
{
   var uniqueList = new List&lt;string&gt;();
   foreach (var item in doubledList)
   {
      if (!uniqueList.Contains(item))
         uniqueList.Add(item);
   }
   return uniqueList;
}&lt;/code&gt;&lt;/pre&gt;&lt;h4&gt;3. Using a SortedList&lt;/h4&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static IList&lt;string&gt; LoadUniqueList3(List&lt;string&gt; doubledList)
{
   var uniqueList = new SortedList&lt;string, string&gt;();
   foreach (var item in doubledList)
   {
      if (!uniqueList.ContainsKey(item))
         uniqueList.Add(item, item);
   }
   return uniqueList.Values;
}&lt;/code&gt;&lt;/pre&gt;&lt;h4&gt;4. Using a HashSet&lt;/h4&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static IList&lt;string&gt; LoadUniqueList4(List&lt;string&gt; doubledList)
{
   return new HashSet&lt;string&gt;(doubledList).ToList();
}&lt;/code&gt;&lt;/pre&gt;&lt;h4&gt;5. Using LINQ Distinct&lt;/h4&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static IList&lt;string&gt; LoadUniqueList5(List&lt;string&gt; doubledList)
{
   return doubledList.Distinct().ToList();
}&lt;/code&gt;&lt;/pre&gt;&lt;h4&gt;6. Using LINQ double iteration&lt;/h4&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static IList&lt;string&gt; LoadUniqueList6(List&lt;string&gt; doubledList)
{
   var uniqueList = new List&lt;string&gt;();
   uniqueList.Add(
      (from itm in uniqueList
      from compareItem in doubledList
      where itm == compareItem
      select compareItem).ToString());
   return uniqueList;
}&lt;/code&gt;&lt;/pre&gt;&lt;h4&gt;7. Sort and then build filtered list&lt;/h4&gt;&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public static IList&lt;string&gt; LoadUniqueList7(List&lt;string&gt; doubledList)
{
   var uniqueList = new List&lt;string&gt;();
   doubledList.Sort();
   string lastEntry = string.Empty;
   foreach (string str in doubledList)
   {
      if (str != lastEntry)
      {
         uniqueList.Add(str);
         lastEntry = str;
      }
   }
   return uniqueList;
}&lt;/code&gt;&lt;/pre&gt;&lt;h2&gt;Timing results&lt;/h2&gt;The table below shows the elapsed time results for three test runs and the average elapsed time. The last column is how the strategy performed.&lt;br /&gt;
&lt;br /&gt;
Before looking at the results, ask yourself &quot;Which are the top two best performers?&quot;&lt;br /&gt;
&lt;br /&gt;
&lt;div id=&quot;toggleVisibility1&quot;&gt;&lt;a href=&quot;#results&quot; onclick=&quot;{
       var e = document.getElementById(&#39;toggleVisibility1&#39;);
          e.style.display = &#39;none&#39;;
       var e = document.getElementById(&#39;toggleVisibility2&#39;);
          e.style.display = &#39;block&#39;;
    }&quot;&gt;Click here to show results&lt;/a&gt;&lt;/div&gt;&lt;div style=&quot;display: none;&quot; id=&quot;toggleVisibility2&quot; name=&quot;results&quot;&gt;&lt;table&gt;&lt;tr&gt;&lt;th&gt;Description&lt;/th&gt;&lt;th&gt;Pass 1&lt;/th&gt;&lt;th&gt;Pass 2&lt;/th&gt;&lt;th&gt;Pass 3&lt;/th&gt;&lt;th&gt;Average&lt;/th&gt;&lt;th&gt;Rank&lt;/th&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;1 Original&lt;/td&gt;&lt;td&gt;16,503&lt;/td&gt;&lt;td&gt;15,513&lt;/td&gt;&lt;td&gt;16,245&lt;/td&gt;&lt;td&gt;16,087&lt;/td&gt;&lt;td&gt;6&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;2 Use Contains&lt;/td&gt;&lt;td&gt;11,450&lt;/td&gt;&lt;td&gt;11,295&lt;/td&gt;&lt;td&gt;10,912&lt;/td&gt;&lt;td&gt;11,219&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;3 Sorted Use Contains&lt;/td&gt;&lt;td&gt;3,133&lt;/td&gt;&lt;td&gt;2,814&lt;/td&gt;&lt;td&gt;2,810&lt;/td&gt;&lt;td&gt;2,919&lt;/td&gt;&lt;td&gt;4&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;4 Hash Set&lt;/td&gt;&lt;td&gt;193&lt;/td&gt;&lt;td&gt;192&lt;/td&gt;&lt;td&gt;193&lt;/td&gt;&lt;td&gt;193&lt;/td&gt;&lt;td&gt;1&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;5 Distinct&lt;/td&gt;&lt;td&gt;254&lt;/td&gt;&lt;td&gt;246&lt;/td&gt;&lt;td&gt;233&lt;/td&gt;&lt;td&gt;244&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;6 LINQ iteration&lt;/td&gt;&lt;td colspan=&quot;4&quot;&gt;Failed to return correct results&lt;/td&gt;&lt;td&gt;n/a&lt;/td&gt;&lt;/tr&gt;
&lt;tr&gt;&lt;td&gt;7 Sort and filter&lt;/td&gt;&lt;td&gt;2,908&lt;/td&gt;&lt;td&gt;2,674&lt;/td&gt;&lt;td&gt;2,713&lt;/td&gt;&lt;td&gt;2,766&lt;/td&gt;&lt;td&gt;3&lt;/td&gt;&lt;/tr&gt;
&lt;/table&gt;&lt;br /&gt;
Unsurprisingly, the HashSet won and the original was the slowest. I was surprised Distinct was a close second; I expected it to come in closer to the two implementations using a sorted list.&lt;br /&gt;
&lt;br /&gt;
Any surprises for you?&lt;br /&gt;
&lt;/div&gt;&lt;br /&gt;
Comments about either the test methodology or results can be left below.&lt;br /&gt;
&lt;br /&gt;
Test project available &lt;a href=&quot;http://dl.dropbox.com/u/15523784/SkylarkSoftware/DuplicateRemoveTimingTests.zip&quot;&gt;here.&lt;/a&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2012/03/7-ways-to-removing-duplicate-strings.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-5593979859542366478</guid><pubDate>Mon, 12 Mar 2012 12:00:00 +0000</pubDate><atom:updated>2012-03-12T09:33:04.140-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">cursor</category><category domain="http://www.blogger.com/atom/ns#">design</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">resource</category><category domain="http://www.blogger.com/atom/ns#">WinForms</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>There and back again, again: Several resource&#39;s tale</title><description>&lt;h3&gt;Or, how to safely change a cursor or other resource&lt;/h3&gt;
&lt;p&gt;In a &lt;a href=&quot;http://www.skylark-software.com/2011/05/there-and-back-again-cursors-tale.html&quot;&gt;previous article&lt;/a&gt;, I presented a simple class that utilized the IDisposable pattern to set the cursor to a specific value and then automatically reset it to the initial state when some work was accomplished. This simple class had two limitations: it only worked with WPF and it only worked on cursors.&lt;/p&gt;
&lt;p&gt;To overcome these limitations, I refactored this to be more general. I changed the context to a generic type and added an abstract RestoreState method that&#39;s called when the class is either destroyed (preferred) or the finalizer is called. This allows all the basic plumbing regarding the IDisposable pattern to be contained in one class.&lt;/p&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;using System;

namespace ResourceProtection
{
    public abstract class ResourceChangeHandler&lt;TContext&gt; : IDisposable
    {
        protected TContext Context { get; set; }
        private bool Disposed { get; set; }

        protected ResourceChangeHandler(TContext context)
        {
            Disposed = false;
            Context = context;
        }

        public void Dispose()
        {
            DisposeInt();
            GC.SuppressFinalize(this);
        }

        protected abstract void RestoreState(TContext context);

        private void DisposeInt()
        {
            if (Disposed)
                return;

            RestoreState();
            Disposed = true;
        }

        ~ResourceChangeHandler()
        {
            DisposeInt();
        }
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;The beauty of this is it can be used as the base class for specific needs. The function of actually changing a resource is split out from the framework needed to manage the change. Here are three examples: one each for a WPF cursor changer, a WinForms cursor changer and a TreeView BeginUpdate/EndUpdate handler.&lt;/p&gt;
&lt;h3&gt;How to change a WPF cursor&lt;/h3&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public class WpfChangeCursor : ResourceChangeHandler&lt;FrameworkElement&gt;{
    private Cursor OriginalCursor { get; set; }

    public WpfChangeCursor(FrameworkElement element, Cursor newCursor)
            : base(element)
    {
        OriginalCursor = Context.Cursor;
        Context.Cursor = newCursor;
    }

    protected override void RestoreState()
    {
        Context.Cursor = OriginalCursor;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;To use this, instantiate an instance of WpfChangeCursor in a using block, passing in the element who&#39;s cursor should be changed and the new value for the cursor. In this case, the context for the base class is the element containing the cursor to be changed. The descendant class has the responsibility to remember the current value and changing the cursor.&lt;/p&gt;
&lt;h3&gt;How to change a WinForm cursor&lt;/h3&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public class WinFormChangeCursor : ResourceChangeHandler&lt;Cursor&gt;{
    private Cursor OriginalCursor { get; set; }

    public WinFormChangeCursor(Cursor newCursor)
            : base(Cusor.Current)
    {
        Cursor.Current = newCursor;
    }

    protected override void RestoreState()
    {
        Cursor.Current = Context;
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;This class is used by instantiating an instance of WinFormChangeCursor in a using block with the new value of the cursor passed to it. This is a little different from the WPF version since there is only one cursor for the application, rather than for each element. In this case, the context passed to the base is the current cursor value which is then used by RestoreState to put things back.&lt;/p&gt;
&lt;h3&gt;How to call BeginUpdate and EndUpdate safely&lt;/h3&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public class TreeViewUpdate : ResourceChangeHandler&lt;TreeView&gt;{
    public TreeViewUpdate(TreeView treeview)
            : base(treeview)
    {
        Context.BeginUpdate();
    }

    protected override void RestoreState()
    {
        Context.EndUpdate();
    }
}&lt;/code&gt;&lt;/pre&gt;
&lt;p&gt;And finally, here&#39;s a class to make sure EndUpdate is called for every BeginUpate on a TreeView. Like the WPF cursor changer above, the control is passed in as the context for the ancestor class. BeginUpdate is then called on the context. When the using block this class is controlled by finishes, the EndUpdate in RestoreState is called, again on the same context as the BeginUpdate.&lt;/p&gt;
&lt;p&gt;This technique provides for a level of separation between the framework needed to safely do and undo things from the actual work of doing and undoing them. It works well for certain classes of problems, specifically fixed things that happen over and over again. The examples above of doing repetitive things on framework level items are good examples.&lt;/p&gt;
&lt;p&gt;Sometimes though, one wants this type of functionality without the overhead of creating a new class each time. In the next article, I&#39;ll present a method of composing this type of behavior in a more adhoc manner.&lt;/p&gt;
&lt;p&gt;Until then, subscribe to the &lt;a href=&quot;http://twitter.com/skysoft&quot;&gt;Twitter feed&lt;/a&gt; to get notified of future articles and hear about other development related things. And if you have any questions, suggestions or comments, please feel free to leave them below.&lt;/p&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2012/03/there-and-back-again-again-several.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-2595429997719637609</guid><pubDate>Tue, 27 Sep 2011 12:00:00 +0000</pubDate><atom:updated>2011-09-27T06:00:09.503-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C++</category><category domain="http://www.blogger.com/atom/ns#">HowTo</category><category domain="http://www.blogger.com/atom/ns#">Microsoft</category><category domain="http://www.blogger.com/atom/ns#">problem</category><title>How to fix Visual Studio C++ Warning: LINK4075</title><description>At the beginning of last week&#39;s sprint, I picked up a task to reduce our warning count. One of the issues that I scratched my head over a couple minutes was a bunch of warnings with the text &lt;em&gt;warning LNK4075: ignoring &#39;/EDITANDCONTINUE&#39; due to &#39;/SomeOtherSetting&#39; specification.&lt;/em&gt; As indicated by the LNK identifier, I knew the linker emitted this warning. However, in my perusal of the linker options, I couldn&#39;t find where the EDITANDCONTINUE setting existed. I even glanced through the other property pages looking for it.&lt;br /&gt;
&lt;br /&gt;
Per my wont, I searched the web and eventually found it based on some oblique references on a &lt;a href=&quot;http://stackoverflow.com/questions/1574367/lnk4075-ignoring-editandcontinue-due-to-opticf-specification&quot;&gt;StackOverflow question&lt;/a&gt;. The reason I had trouble finding it? It&#39;s a compiler option. And it&#39;s not called EDITANDCONTINUE.&lt;br /&gt;
&lt;br /&gt;
This is controlled by the &lt;em&gt;Debug Information Format&lt;/em&gt; setting on the C/C++ General page. If the option is &lt;em&gt;Program Database and Edit and Continue,&lt;/em&gt; a.k.a. &lt;strong&gt;/ZI&lt;/strong&gt;, then the output obj files apparently have a flag embedded in them that is incompatible with certain settings in the linker. Hence, the linker emits the warnings when it hits these conditions. It would have been nice for the message to have contained the &lt;strong&gt;/ZI&lt;/strong&gt; option (which is what&#39;s used in the compiler) rather then than the EDITANDCONTINUE pseudo-option which isn&#39;t used anywhere, as near as I can tell.&lt;br /&gt;
&lt;br /&gt;
To fix this warning, either change the linker options that are incompatible with the &lt;strong&gt;/ZI&lt;/strong&gt; option or change the compiler option to something other than &lt;strong&gt;/ZI&lt;/strong&gt;, such as &lt;strong&gt;/Zi&lt;/strong&gt;. As of the time of this writing, the linker options incompatible with EDITANDCONTINUE include setting optimization to &lt;strong&gt;/OPT:REF&lt;/strong&gt; or &lt;strong&gt;/OPT:ICF&lt;/strong&gt;, turning off incremental compilation or setting one of &lt;/strong&gt;/ORDER&lt;/strong&gt;, &lt;strong&gt;/RELEASE&lt;/strong&gt; or &lt;strong&gt;/FORCE&lt;/strong&gt;. (These are from &lt;a href=&quot;http://msdn.microsoft.com/en-us/library/962ct2hz.aspx&quot;&gt;this MSDN page.&lt;/a&gt;)&lt;br /&gt;
&lt;br /&gt;
Hope this helps someone.&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2011/09/how-to-fix-visual-studio-c-warning.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>1</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-7367999940623349827</guid><pubDate>Fri, 23 Sep 2011 12:00:00 +0000</pubDate><atom:updated>2011-09-23T06:00:02.699-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">HowTo</category><category domain="http://www.blogger.com/atom/ns#">installation</category><category domain="http://www.blogger.com/atom/ns#">Microsoft</category><category domain="http://www.blogger.com/atom/ns#">problem</category><category domain="http://www.blogger.com/atom/ns#">VirtualBox</category><category domain="http://www.blogger.com/atom/ns#">Windows 8</category><title>Sharing folders with Windows 8 between VirtualBox machines</title><description>Currently Windows 8 runs just fine inside a VirtualBox machine. However, guest additions, the tools to enable certain useful features of VirutalBox, do not yet work with Windows 8. Today I wanted to use some Visual Studio projects from an existing Windows XP virtual machine in my new Windows 8 machine. The obvious first choice was to simply use a shared folder on the host in both virtual machines. However, this requires the guest additions, so I went looking for a work around.&lt;br /&gt;
&lt;br /&gt;
What I found to work was a second virtual hard drive. In VirtualBox, on my primary development machine, I created a new hard drive on the existing IDE controller. I then started the machine and went into Windows&#39; device manager. The disk manager started the new disk wizard. After initialization, I created and formatted an NTFS partition. I then copied the files I wanted to work with to this new disk. Finally I shutdown this machine.&lt;br /&gt;
&lt;br /&gt;
Next, in VirturalBox, I added the same, new hard drive image as a second drive on the Window 8 box&#39;s SATA controller. (If you add the drive to the IDE controller, Windows 8 will try to boot to it first and fail with a bad image error.) When I booted Windows 8 and went into Explorer, the second drive showed up with all the data I&#39;d copied to it.&lt;br /&gt;
&lt;br /&gt;
That&#39;s it, pretty simple and straight forward, but not the obvious (to me) first solution.&lt;br /&gt;
&lt;br /&gt;
Warning: I don&#39;t know what would happen if both virtual machines are run at the same time. I suspect (and hope) the second one started would get some sort of sharing violation and not allow the disk to be mounted. I can&#39;t imagine VirtualBox is smart enough to allow two machines to attach to the same vdi file at the same time without corrupting the data. However, it seems to work just fine as long as there is only one machine using the file at any given point of time.&lt;br /&gt;
&lt;br /&gt;
Hope this helps someone.&lt;br /&gt;
&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2011/09/sharing-folders-with-windows-8-between.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-3635120277838196386</guid><pubDate>Mon, 19 Sep 2011 12:00:00 +0000</pubDate><atom:updated>2011-09-19T21:32:37.228-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">Microsoft</category><category domain="http://www.blogger.com/atom/ns#">recap</category><category domain="http://www.blogger.com/atom/ns#">UserExperience</category><category domain="http://www.blogger.com/atom/ns#">Windows 8</category><title>First Thoughts Regarding Windows 8</title><description>&lt;p&gt;With all the hubbub around Microsoft&#39;s BUILD conference and the developer preview of Windows 8, I thought I&#39;d grab a copy to check it out. This is what I found; it&#39;s going to be pretty short...&lt;/p&gt;

&lt;h3&gt;Installation&lt;/h3&gt;
&lt;p&gt;I downloaded a copy of Windows 8,&lt;sup&gt;&lt;small&gt;&lt;a href=&quot;#Win8firstImpression1&quot;&gt;[1]&lt;/a&gt;&lt;/small&gt;&lt;/sup&gt; created a new machine in VirtualBox, attached the downloaded ISO to the CD and booted the machine.&lt;sup&gt;&lt;small&gt;&lt;a href=&quot;#Win8firstImpression2&quot;&gt;[2]&lt;/a&gt;&lt;/small&gt;&lt;/sup&gt; It started the install OK and then hung part way through. After waiting awhile, I powered off the VM. On restart, it tried to do an install restart but this time give me a failure message. So I powered it down again and then back up. This time during the restart it showed me the partitions on the drive. I deleted all the previously created partitions and it finally ran through the install to the end. When it finished, it did the typical Windows reboot but hung during the reload. I turned the machine off, detached the ISO image from the CD and turned it back on. This time it booted just fine. It asked me a couple of standard questions, like user name and password and took me to a phone/tablet looking screen.&lt;/p&gt;

&lt;h3&gt;Cursor problems&lt;/h3&gt;
&lt;p&gt;At this point the cursor pretty much went wonky. Yes, that&#39;s a technical term. When moving the cursor from the host OS to the Windows 8 machine, the cursor would jump to an odd place and then jump back off the guest screen back to the host. It was pretty much unusable. I tried installing VirtualBox&#39;s guest additions. The installer asked all the startup questions but then stopped when I told it to begin the actual install saying it didn&#39;t support that version of Windows. I suppose that&#39;s not too surprising. As a last ditch effort, I moved the virtual screen off my large secondary screen to the laptop&#39;s smaller main screen and all of a sudden the cursor started working correctly. At this point I&#39;m not sure if it&#39;s a problem with VirtualBox on the secondary screen or if it&#39;s a Windows 8 incompatibility or perhaps some of each. In any case, the cursor problem doesn&#39;t show up on the main screen and the mouse/keyboard capturing works as I&#39;d expect; i.e. once the guest OS has control, you have to hit the Host button to get back out.&lt;/p&gt;

&lt;h3&gt;Operation&lt;/h3&gt;
&lt;p&gt;Once the cursor started working correctly, I played around with a bit. IE10 works pretty much like you&#39;d expect a browser to although the UI is somewhat different in keeping with the Metro design. The biggest thing is the address bar is at the bottom of the screen. Other than that, it worked OK. Google returned search results. GMail showed me my mail. However, when I went to YouTube, it needed the Flash plug-in. I knew the Metro version of IE didn&#39;t support plug-ins, so I wasn&#39;t sure what would happen. But everything worked, sort of: clicking the link took me to Adobe&#39;s web site, downloading and installing worked just fine. Yet when I went back to YouTube, it still complained about no plug-in. I went to the desktop (one of the many tiles on the &quot;start page&quot;), clicked on the IE icon there and then navigated to YouTube. It worked. This is one of those differences between the Metro version and the desktop version. However, I had to know that going in, otherwise it would have simply looked like it didn&#39;t work. There was no indication saying the Metro version didn&#39;t support plug-ins or that the desktop version did.&lt;/p&gt;

&lt;p&gt;I tried clicking on some of the other tiles on the start page and didn&#39;t get too far. Most of them seem to need features unique to mobile devices. &lt;em&gt;Word Hunt&lt;/em&gt; wanted me to &quot;bump&quot; with a friend&#39;s device to initiate the connection. I assume that&#39;s some sort of bluetooth thing. &lt;em&gt;Labyrinth&lt;/em&gt; simply sat there staring at me. No instructions. Clicking, click-dragging and other random character presses yielded no results. I&#39;m guessing it wanted some sort of tilt sensor input. The last thing I tried was &lt;em&gt;BitBox.&lt;/em&gt; I had high hopes of getting somewhere since it actually started with a mini-tutorial. My hopes were dashed on about the third step when told to do a pinch operation to continue. Um, how do you do multi-touch with a mouse?&lt;/p&gt;

&lt;p&gt;At that point I pretty much gave up and turned the thing off. That was a bit of an adventure itself. First I tried sending the power off signal from VirualBox. This is equivalent to pressing the power button on a typical PC/Laptop. Nothing happened. I looked around a bit for a shutdown option. All I could find was logout. I ended up going to the desktop and pressing Alt-F4. That has worked since at least Windows 3.1, and it still does. I got a familiar &quot;what do you want to do? shutdown, restart&quot; type dialog. (I have subsequently learned there is a power button that&#39;s available after you logout.)&lt;/p&gt;

&lt;h3&gt;Opinions&lt;/h3&gt;
&lt;p&gt;My first impression after about an hour of playing with it is that it seems fairly comparable to the iPad and Android regarding user experience. (I&#39;ve played around with both these about as much as I have Windows 8.) Basically there are big squares that slide around and you can click on them. The applications open in full screen mode. Shrug. I guess some people might get excited about it. To me, it seems about the same as everything else on the market.&lt;/p&gt;

&lt;p&gt;What I find interesting about these devices is the infrastructure, development environment and community support that grows up around them. The iPad and Android ecosystems both have their strengths and weaknesses. I think it&#39;s too early to tell much about what will happen with the ecosystem around Windows 8. Will Microsoft learn from both their previous successes and mistakes, as well as those of Apple and Google, to become a market leader? Will they become another fairly equal player? Or will they become an also ran in this race?&lt;/p&gt;

&lt;p&gt;From an internal design perspective, I like the direction Microsoft is going better than Apple or Google. Apple has a split between the desktop/laptop OS X and the mobile device iOS. Google is trying to scale the mobile/browser experience to the desktop in ChromeOS. I think both these are weak strategies.&lt;/p&gt;

&lt;p&gt;Apple has two, separate code bases to maintain, much of which could probably be combined. I think long term this is going to cause compatibility problems much like Microsoft has had between the mobile/embedded Windows and the desktop version and more lately between WPF and Silverlight. Very similar systems with differing code bases have made the developer community pretty aggravated at times.&lt;/p&gt;

&lt;p&gt;Google has a similar problem with the bifurcation between Android and ChromeOS. Android probably has the potential for making a pretty nice desktop OS. Give some development effort, it&#39;d be pretty comparable, from a design perspective, as Windows 8. The high-level design documents for both would look very similar. However, Google has decided to try to expand the browser into an operating system. I&#39;ve experimented with ChromeOS and it works acceptably if all you want to do is available on the web. But frequently I want to use my computer off-line and the whole ecosystem is not up to this task. Perhaps in 5 years everything will be a web app. I doubt it though.&lt;/p&gt;

&lt;p&gt;Microsoft is pairing down the core of Windows and then placing different layers on top of it. From a design perspective this seems like the best long term solution. It has always appeared that desktop Windows was the first-class citizen and the embedded/phone OS by the same name (which only had passing resemblance to its big brother) was second-class. By putting a desktop UI on the same core as the mobile device UI, they can both become equal products, just for different markets. As a desktop developer, the biggest fear I have is, instead of raising the mobile UI to be equal to the desktop&#39;s, they are going to push the desktop down to second-class status. As it stands with this preview, the first and primary experience is the Metro look and feel. It works great on a tablet. I have yet to see it work well on a desktop. Without major changes to the current experience, I predict Windows 8 will work well on mobile devices but will not be adopted in the desktop world. Hmm, will Windows 8 make &lt;a href=&quot;http://www.google.com/search?q=the+year+of+the+linux+desktop&quot;&gt;the year of the Linux desktop&lt;/a&gt; finally a reality?&lt;/p&gt;
&lt;h3&gt;Updates&lt;/h3&gt;
&lt;p&gt;The above all happened on Friday. Monday morning, I started the Windows 8 virtual machine. It hung during boot. I turned it off and tried again. Again it hung (at a different place) during boot. I deleted the image. Too much hassle at this point.&lt;/p&gt;
&lt;p&gt;Monday evening: I created a VirtualBox machine hosted on my MacBook Pro. Pretty much the same configuration as I had on the other one hosted in Windows 7: 50GB hard drive with about 2.5GB of memory. It installed perfectly the first time and so far has worked flawlessly. (Well, other than the weirdnesses of a touch based interface driven by a keyboard/mouse.)&lt;/p&gt;
&lt;hr/&gt;
&lt;div id=&quot;Win8firstImpression1&quot; style=&quot;margin-left:2em;text-indent:-2em&quot;&gt;1. Download &lt;a href=&quot;http://msdn.microsoft.com/en-us/windows/apps/br229516&quot;&gt;Windows 8 preview here&lt;/a&gt;&lt;/div&gt;&lt;div id=&quot;Win8firstImpression2&quot; style=&quot;margin-left:2em;text-indent:-2em&quot;&gt;2. This is not intended to be a tutorial. There are already good tutorials to &lt;a href=&quot;http://www.pcworld.com/article/240119/how_to_download_and_install_windows_8_on_a_new_partition.html&quot;&gt;install onto a hard drive&lt;/a&gt; and &lt;a href=&quot;http://www.pcworld.com/article/240117/how_to_download_and_install_windows_8_into_a_virtual_machine.html&quot;&gt;into a virtual machine&lt;/a&gt; available.&lt;/div&gt;
&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2011/09/first-thoughts-regarding-windows-8.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-311163776041816454</guid><pubDate>Thu, 14 Jul 2011 12:00:00 +0000</pubDate><atom:updated>2011-07-14T06:00:01.537-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">benchmark</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">comparison</category><category domain="http://www.blogger.com/atom/ns#">LINQ</category><category domain="http://www.blogger.com/atom/ns#">Programming</category><category domain="http://www.blogger.com/atom/ns#">set</category><title>LINQ and set notation</title><description>So I learned something today.&lt;br /&gt;
&lt;br /&gt;
It&#39;s been a long time since I had any classes dealing with sets. I vaguely remember discussions including Venn diagrams and odd notation that didn&#39;t have any relevance to any other context that I was familiar with, but they were also pretty cool to study and get to know. However, they&#39;re the types of things that have a highly technical, mathematically rigorous side to them and also the day-to-day intuitive side that I use. Not needing it on a regular basis, the finer points of set algebra quickly sink into the background and aren&#39;t easily recalled.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;float: right; margin-bottom: 0.5em; margin-left: 0.5em;&quot;&gt;&lt;a href=&quot;http://www.flickr.com/photos/the_episodic_author/5936167552/&quot; title=&quot;Intersection by The Episodic Author, on Flickr&quot;&gt;&lt;img alt=&quot;Intersection&quot; height=&quot;75&quot; src=&quot;http://farm7.static.flickr.com/6026/5936167552_8a6fe2d0f2_t.jpg&quot; width=&quot;100&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Today I needed to do some set manipulation. I knew LINQ had some set related methods in it, such as Intersect which gives only the items that are in both lists.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;float: right; margin-bottom: 1em; margin-left: 0.5em;&quot;&gt;&lt;a href=&quot;http://www.flickr.com/photos/the_episodic_author/5936167562/&quot; title=&quot;Union by The Episodic Author, on Flickr&quot;&gt;&lt;img alt=&quot;Union&quot; height=&quot;75&quot; src=&quot;http://farm7.static.flickr.com/6125/5936167562_4bdb6a7da5_t.jpg&quot; width=&quot;100&quot; /&gt;&lt;/a&gt;&lt;/div&gt;And I knew it had the Union that gives all the items in both lists, without duplicates.&lt;br /&gt;
&lt;br /&gt;
Needing to find the differences between two lists, I suspected there was something to do that easily.&amp;nbsp;I had two string lists and needed the items from both lists that were only in one of the two lists. In other words, I needed the inverse of Intersect. First I looked at the options in the code completion list. Nothing jumped out at me. I couldn&#39;t recall the technical name so I did a web search for &quot;LINQ intersect inverse&quot; and found the Except method. The description sounded promising but, when I tried it, I didn&#39;t get what I expected. It only gave the things that were in the first list but not in the second list. In other words, it did not include the things in the second list that weren&#39;t in the first. Figuring the people who wrote these methods probably knew something about what they were doing, I went digging a little deeper.&lt;br /&gt;
&lt;br /&gt;
The next web search was for &quot;set intersect inverse&quot; that led me to a Wikipedia page on&amp;nbsp;&lt;a href=&quot;http://en.wikipedia.org/wiki/Intersection_%28set_theory%29)&quot;&gt;set intersection&lt;/a&gt;. Scrolling to the bottom &quot;see also&quot; section, I saw &lt;a href=&quot;http://en.wikipedia.org/wiki/Complement_%28set_theory%29)&quot;&gt;Complement&lt;/a&gt;. Ah-ha! That rang a bell from the distant past. Clicking on that link confirmed that Complement was in fact the difference between two sets.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;float: right; margin-bottom: 0.5em; margin-left: 0.5em;&quot;&gt;&lt;a href=&quot;http://www.flickr.com/photos/the_episodic_author/5936167574/&quot; title=&quot;RelativeComplement by The Episodic Author, on Flickr&quot;&gt;&lt;img alt=&quot;RelativeComplement&quot; height=&quot;75&quot; src=&quot;http://farm7.static.flickr.com/6014/5936167574_1c4eba52a4_t.jpg&quot; width=&quot;100&quot; /&gt;&lt;/a&gt;&lt;/div&gt;And this is where I started to learn something new: there are multiple types of differences in set theory. In general, the Complement refers to things not in a given set. First, there&#39;s the relative complement as implemented by LINQ&#39;s Except method. This gives the things from one list that are not in the other list. For example, if &lt;em&gt;list1 = new List&amp;lt;string&gt; {&quot;a&quot;, &quot;b&quot;, &quot;c&quot;}&lt;/em&gt; and &lt;em&gt;list2 = new List&amp;lt;string&gt;{&quot;b&quot;, &quot;c&quot;, &quot;d&quot;}&lt;/em&gt; then &lt;em&gt;list1.Except(list2)&lt;/em&gt; will return &quot;a&quot;.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;float: right; margin-bottom: 0.5em; margin-left: 0.5em;&quot;&gt;&lt;a href=&quot;http://www.flickr.com/photos/the_episodic_author/5935608821/&quot; title=&quot;AbsoluteComplement by The Episodic Author, on Flickr&quot;&gt;&lt;img alt=&quot;AbsoluteComplement&quot; height=&quot;75&quot; src=&quot;http://farm7.static.flickr.com/6126/5935608821_f641345480_t.jpg&quot; width=&quot;100&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Second, there&#39;s the absolute complement. This is the universe of all things not in a given set. Hopefully it&#39;s obvious that this can&#39;t be implemented in software.&lt;br /&gt;
&lt;br /&gt;
&lt;div style=&quot;float: right; margin-bottom: 0.5em; margin-left: 0.5em;&quot;&gt;&lt;a href=&quot;http://www.flickr.com/photos/the_episodic_author/5936167594/&quot; title=&quot;SymmetricDifference by The Episodic Author, on Flickr&quot;&gt;&lt;img alt=&quot;SymmetricDifference&quot; height=&quot;75&quot; src=&quot;http://farm7.static.flickr.com/6127/5936167594_d922029d20_t.jpg&quot; width=&quot;100&quot; /&gt;&lt;/a&gt;&lt;/div&gt;Finally, there is the &lt;a href=&quot;http://en.wikipedia.org/wiki/Symmetric_difference&quot;&gt;symmetric difference&lt;/a&gt;. This is the name of what I needed. It&#39;s the list of things that are in only one of two given sets. Thinking in terms of set operations, it&#39;s the relative complement between the union of the sets and the intersection of the sets. In LINQ terms it&#39;s &lt;em&gt;list1.Union(list2).Except(list1.Intersect(list2))&lt;/em&gt;. This got me what I want.&lt;br /&gt;
&lt;br /&gt;
Now that I had a technical term to search on, out of curiosity I tried &quot;symmetric difference LINQ&quot;. (It&#39;s always easier to find what you&#39;re looking for when you know the proper keywords.) This returned a link to a &lt;a href=&quot;http://stackoverflow.com/questions/2404301/linq-find-differences-in-two-lists&quot;&gt;StackOverflow question&lt;/a&gt; that not only gave the answer I came up with but also pointed out there&#39;s a SymmetricExceptWith method on the HashSet class.&lt;br /&gt;
&lt;br /&gt;
Curiosity now drove me to do a quick benchmark. Knowing LINQ has never been a speed demon, I assumed it probably wouldn&#39;t beat out the HashSet implementation. I threw together a quick console app that simply ran both the above LINQ query and HashSet.SymmetricExceptWith call on two short lists a million times and reported the elapsed times. I used three different types of input containers to see if that made much difference. Here&#39;s what I found...&lt;br /&gt;
&lt;table&gt;&lt;tr&gt;&lt;th&gt;Input type&lt;/th&gt;&lt;th&gt;Using LINQ&lt;/th&gt;&lt;th&gt;Using HashSet.SymmetricExceptWith&lt;/th&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;List&amp;lt;string&gt;&lt;/td&gt;&lt;td&gt;2.8 s&lt;/td&gt;&lt;td&gt;1.0 s&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;LinkedList&amp;lt;string&gt;&lt;/td&gt;&lt;td&gt;2.9 s&lt;/td&gt;&lt;td&gt;1.1 s&lt;/td&gt;&lt;/tr&gt;&lt;tr&gt;&lt;td&gt;HashSet&amp;lt;string&gt;&lt;/td&gt;&lt;td&gt;2.7 s&lt;/td&gt;&lt;td&gt;0.8 s&lt;/td&gt;&lt;/tr&gt;&lt;/table&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2011/07/linq-and-set-notation.html</link><author>noreply@blogger.com (Harley Pebley)</author><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="http://farm7.static.flickr.com/6026/5936167552_8a6fe2d0f2_t.jpg" height="72" width="72"/><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-651835007111680365</guid><pubDate>Fri, 08 Jul 2011 12:00:00 +0000</pubDate><atom:updated>2011-07-08T06:00:05.588-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">comparison</category><category domain="http://www.blogger.com/atom/ns#">Delphi</category><category domain="http://www.blogger.com/atom/ns#">pascal</category><title>Local procedures from Delphi in C#</title><description>Pascal has this nifty feature where you can declare procedures inside of procedures. Something like:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;procedure procA

    procedure procB
    begin
        // procedure B code here
    end;

begin
    // procedure A code here calling procB
end;&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
It&#39;s not the type of thing I used a lot, but there were times where it came in handy. It was a nice thing to have in the tool belt even if it wasn&#39;t pulled out too often. A couple times I have wanted to do this in C# and have resorted to other means.&lt;br /&gt;
&lt;br /&gt;
Today while reading &lt;a href=&quot;http://www.johndcook.com/blog/2011/07/06/maybe-c-hasnt-jumped-the-shark-after-all/&quot;&gt;an article by John Cook about C++&lt;/a&gt;, I realized this is trivially easy to do in C#: simply use named lambdas. It&#39;s one of those things that&#39;s so obviously simple and easy, I don&#39;t know why it didn&#39;t occur to me before.&lt;br /&gt;
&lt;br /&gt;
So, the above Pascal code could be written in C# like so:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;public void procA()
{
    Action procB = () =&gt; 
        {
            // procedure B code here
        }

    // procedure A code here calling procB()
}&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2011/07/local-procedures-from-delphi-in-c.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-4421121613057774140</guid><pubDate>Thu, 09 Jun 2011 05:44:00 +0000</pubDate><atom:updated>2011-06-08T23:44:03.302-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">arduino</category><category domain="http://www.blogger.com/atom/ns#">references</category><category domain="http://www.blogger.com/atom/ns#">stepper motor</category><title>Stepper motor references</title><description>Recently I have been playing around with stepper motors on my Arduino. (An overview of one project is on &lt;a href=&quot;http://www.hookedonlight.com/2011/05/time-lapse-turntable-project.html&quot;&gt;my photography blog&lt;/a&gt;.) Here&#39;s a list of online resources I&#39;ve found helpful in my education:&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.ehow.com/how_4738199_wire-stepper-motor.html&quot;&gt;How to wire a stepper motor&lt;/a&gt; has a good overview of the different types of steppers and how to identify the wires on an unknown motor.&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://arduino.cc/en/Reference/StepperUnipolarCircuit&quot;&gt;Circuits for Unipolar motors&lt;/a&gt; on the Arduino site uses a ULN2003 or ULN2004 chip. One circuit has a couple resistors and a diode to allow two pin control of the motor. The other uses only the chip but requires four pins. I built the two pin configuration and it worked flawlessly. Note: the ULN2003 will only source up to 500mA. Higher current motors will cause its magic smoke to escape.&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.circuitstoday.com/stepper-motor-controller&quot;&gt;Stepper motor controller&lt;/a&gt; circuit uses two logic chips, four each of resistors, transistors and diodes and is controlled by two pins. Since it uses discrete components, it&#39;s easily modified for higher current motors than the ULN2003/ULN2004 can support. I haven&#39;t built this one, but have the components to do so in the future.&lt;br /&gt;
&lt;br /&gt;
The &lt;a href=&quot;http://www.google.com/?q=28BYJ-48+stepper+motor&quot;&gt;28BYJ-48 stepper motor&lt;/a&gt; is a really cheap, high resolution stepper motor that comes in both 5V and 12V ratings. Not sure how reliable it is, but so far in my experiments it has worked well. It has a 64:1 reduction gear head built into it, so it is pretty high torque for the current draw (I think it&#39;s spec&#39;d to be around 250ma) and a whole lot of steps per revolution.&lt;br /&gt;
&lt;br /&gt;
&lt;a href=&quot;http://www.stepperworld.com/Tutorials/pgBipolarTutorial.htm&quot;&gt;Stepper Motors and Control&lt;/a&gt; is a good overview tutorial. It includes logic charts for different ways of driving stepper motors for different purposes: lower power, higher torque and higher number of steps. It also talks about identifying different types of steppers and how to select a current limiting resistor.&lt;br /&gt;
&lt;br /&gt;
I&#39;ll update this list if I find anything else that seems like it&#39;d be good to have here.&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2011/06/stepper-motor-references.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>2</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-7628792060756439193</guid><pubDate>Thu, 26 May 2011 12:00:00 +0000</pubDate><atom:updated>2011-05-26T06:00:03.162-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">cursor</category><category domain="http://www.blogger.com/atom/ns#">design</category><category domain="http://www.blogger.com/atom/ns#">resource</category><category domain="http://www.blogger.com/atom/ns#">WPF</category><title>There and back again: A Cursor&#39;s tale</title><description>I&#39;ve been working on UI code recently and have run into this quite a bit:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;Cursor = Cursors.Wait;
SomeLongRunningTask();
Cursor = Cursors.Default;&lt;/code&gt;&lt;/pre&gt;Pretty straight forward code. I see this type of thing a lot, not just in the C# code I&#39;m working on now, but I&#39;ve seen this in the past. In other languages. On other platforms. It&#39;s a common practice. The problem is it only works in some cases.&lt;br /&gt;
&lt;br /&gt;
This will have problems if any method in the &quot;long running task&quot; does the same thing. The cursor will be set back to default prematurely. Of course, this is easily solved by saving the old value prior to setting the new one.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;var oldCursor = Cursor;
Cursor = Cursors.Wait;
SomeLongRunningTask();
Cursor = oldCursor;&lt;/code&gt;&lt;/pre&gt;This is an improvement but will still fail if an exception is raised. This can be fixed with a try/finally.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;var oldCursor = Cursor;
Cursor = Cursors.Wait;
try
{
    SomeLongRunningTask();
}
finally            
{
    Cursor = oldCursor;
}&lt;/code&gt;&lt;/pre&gt;Ok. So now we have some code that works reasonably well. The issue now is one of code maintainability and clarity. Every method that needs to change the cursor needs to add nine lines before it can do any work of its own. It&#39;s nine lines where bugs could hide. It&#39;s nine lines obscuring the real purpose of the method. There&#39;s got to be a better way.&lt;br /&gt;
&lt;br /&gt;
Way back in my Delphi days, I had a small class which handled this chore for me. The constructor took a parameter containing the new cursor. The current cursor was saved in a class field, the cursor was changed and the constructor finished. The destructor simply set the cursor back to the saved value. In that environment, interfaces were reference counted and destroyed when the reference went to zero. The compiler took care of all the bookkeeping automatically. So I could create an instance of this class, store it in a local variable and, when the variable went out of scope, the object was destroyed, resetting the cursor. It worked really well. One line to change the cursor to whatever I wanted and it automatically reset to the original value when done. Pretty sweet.&lt;br /&gt;
&lt;br /&gt;
Unfortunately, C# does not have any deterministic way of handling object lifetimes. This is one of my biggest frustrations with the language. The closest thing we have is the hack that is the using statement. Since this is the best we have, I have put together a class, shown below, similar to the one I had before. The constructor takes the new cursor value and control whose cursor should be changed, saves the current one and, in the Dispose method, resets it back. Now we can have three simple lines with one code block rather than the nine lines with two blocks. It&#39;s a big improvement although still not the single line like I&#39;d prefer.&lt;br /&gt;
&lt;br /&gt;
In use, it looks like this:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;using ChangeCursor(this, Cursors.Wait)
{
    SomeLongRunningTask();
}&lt;/code&gt;&lt;/pre&gt;Arguably, this is a bit cleaner than even the first code snippet we started with.&lt;br /&gt;
&lt;br /&gt;
Since this takes a FrameworkElement, it&#39;s WPF specific. It&#39;d be easy enough to change the type to work with WinForms, if needed. The same technique could be used to handle other things where a state needs to be set to one value and then reset when some unit of work is done. For example, if using TreeViews with BeginUpdate/EndUpdate pairs.&lt;br /&gt;
&lt;br /&gt;
Hope this helps someone.&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;using System;
using System.Windows;
using System.Windows.Input;

namespace CursorResourceProtection
{
    public class ChangeCursor : IDisposable
    {
        private FrameworkElement Context { get; set; }
        private bool Disposed { get; set; }
        private Cursor OriginalCursor { get; set; }

        public ChangeCursor(FrameworkElement context, Cursor newCursor)
        {
            Disposed = false;
            Context = context;
            OriginalCursor = context.Cursor;
            context.Cursor = newCursor;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            if(Disposed)
                return;

            Context.Cursor = OriginalCursor;
            Disposed = true;
        }

        ~ChangeCursor()
        {
            Dispose(false);
        }
    }
}&lt;/code&gt;&lt;/pre&gt;&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2011/05/there-and-back-again-cursors-tale.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item><item><guid isPermaLink="false">tag:blogger.com,1999:blog-1951153510791888567.post-3831508274048501953</guid><pubDate>Wed, 11 May 2011 12:00:00 +0000</pubDate><atom:updated>2011-07-07T12:01:01.586-06:00</atom:updated><category domain="http://www.blogger.com/atom/ns#">array</category><category domain="http://www.blogger.com/atom/ns#">C#</category><category domain="http://www.blogger.com/atom/ns#">comparison</category><category domain="http://www.blogger.com/atom/ns#">Delphi</category><category domain="http://www.blogger.com/atom/ns#">dictionary</category><category domain="http://www.blogger.com/atom/ns#">pascal</category><title>Non-int array indexes from Delphi in C#</title><description>In Delphi, array indexes can be any type that resolves to an integer, not just integers. So for example, enum and bool types can be array indexes. This can be handy in many situations to reduce a if-then or switch construct to a simple assignment. A simple, contrived example:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;
MyEnum = (item1, item2, item3);
...
function enumToString(value: MyEnum): string
begin
switch(value)
case item1: result = &quot;Item one&quot;;
case item2: result = &quot;Item two&quot;;
case item3: result = &quot;Item three&quot;;
end;
end;
...
SomeLabel.Caption = enumToString(value);
...
&lt;/code&gt;&lt;/pre&gt;&lt;br /&gt;
becomes something like this:&lt;br /&gt;
&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;
MyEnum = (item1, item2, item3);
enumToString[MyEnum]: string = (&quot;Item one&quot;, &quot;Item two&quot;, &quot;Item three&quot;);
...
SomeLabel.Caption = enumToString[value];
...
&lt;/code&gt;&lt;/pre&gt;Not only does it reduce code, it also reduces possible bugs. Consider what happens when a value is added to MyEnum. The first example will simply return an empty string creating a possible silent failure that hopefully will be caught when tests are run. The second will generate a compiler error, forcing the programmer to intentionally decide what to do.&lt;br /&gt;
&lt;br /&gt;
In C#, array indexes must be one of the four integer types: int, uint, long or ulong. I really miss the ability to use bools and enums. While lamenting this lack as I looked at some code today similar to the original switch statement, I realized I could use a generic dictionary. The new code looks like this:&lt;br /&gt;
&lt;pre class=&quot;code&quot;&gt;&lt;code&gt;
MyEnum = (item1, item2, item3);
enumToString = new Dictionary&lt;MyEnum, string&gt; = {{item1, &quot;Item one&quot;}, {item2, &quot;Item two&quot;}, {item3, &quot;Item three&quot;)};
...
SomeLabel.Contents = enumToString[value];
...
&lt;/code&gt;&lt;/pre&gt;On one hand, it is a bit more wordy than the Delphi array; on the other, it&#39;s clearer how things are associated in the initializer. The biggest drawback is it doesn&#39;t have the compiler error when things are added to the enum. This is mitigated a bit by the runtime exception generated by a missing key; it&#39;s not quite as silent as just returning nothing in the original code. However, it still depends on good test coverage to find it.&lt;div class=&quot;blogger-post-footer&quot;&gt;&lt;hr /&gt;  &lt;a href=&quot;http://skylark-software.com&quot;&gt;Skylark Software&lt;/a&gt;&lt;/div&gt;</description><link>http://www.skylark-software.com/2011/05/non-int-array-indexes-from-delphi-in-c.html</link><author>noreply@blogger.com (Harley Pebley)</author><thr:total>0</thr:total></item></channel></rss>