Friday, December 6, 2013

How to generate an alert tone from a computer

I recently read a Code Project thread that got into a discussion about beeps, internal speakers and alerting the user. This reminded me of a story from a previous life...

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.

A feature of the software allowed dispatchers to place calls in a pending queue. This was for low priority calls that didn't have resources available for immediate dispatch. After a timeout, things in the queue would start escalating. First they'd change color. Then they'd start flashing. The Chief wanted the next level to be an audible alert. And, with this being the fire department, audible alert didn't mean a simple "beep." It needed to be impossible to ignore, klaxon-loud and obnoxious. And of course there wasn't any budget for any significant hardware. I thought about it on the drive home and had an idea as I fell asleep.

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 sell the same model 20+ years later, albeit at a slightly higher price.) I also got a 1/8" 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'ed it to the appropriate /dev/tty port. An earful of noise rewarded my efforts.

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.

Monday, November 11, 2013

When is the right time to select a source code control tool?


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.-- Article discussing TFS vs Git
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're scanning along the text and all of a sudden, half a paragraph later, an interrupt is raised "Wait, did I really just read that?" You stop and go back over it.

There are plenty of articles covering how to choose a source code control tool. Many places compare and contrast all the options,[1] both open and close sourced. You can find articles that discuss the pros and cons of distributed VCSs vs centralized ones. However, I don't recall ever seeing one about when to choose one. The following is my opinion on this seemingly under-discussed topic.

The quote above is one of many similar statements I've seen over the years. It wouldn't surprise me if many project startup policies include choice of VCS as one of their bullet points. So, I'm not picking on this particular article, it just presents some common wisdom that I don't consider all that wise and I'm using it as a jumping off point to open the discussion.

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's product line.

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.

For a development group to start a new project and consider what VCS they're going to use is like the accounting department opening a new checking account and considering what accounting package they'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.

Keeping everything in one place does a number of things. It decreases startup time; there's one less decision to make. It reduces training; developer's don't need to become proficient in yet another tool. It eliminates confusion about "where do I go to get X?" It enhances cohesion among projects; it's easier to share code that may be common. It reduces maintenance costs; there's one less server that needs to be provisioned, integrated, maintained, backed up, and so on.

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 "NO!"[2]


1. And in fact that was the focus of the above article.
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.

Friday, May 3, 2013

Extension methods are cool

You are creating a vocabulary, not writing a program. Be a poet for a moment.

-- Kent Beck

When Microsoft first introduced extension methods to C#, my first reaction was "eh". I viewed them as a novelty without much use. As time has worn on, I'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.

Static methods that take as a parameter an instance of the class they are defined in really annoy me. One frequent irritation: string.IsNullOrEmpty(). 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 "string.IsNullOrEmpty" at the front. This is simply one of many, many other similar methods spread throughout the framework with this.

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:
public static class StringExtensions
{
     public static bool IsNullOrEmpty(this string target)
     {
          return string.IsNullOrEmpty(target);
     }
}

Now I could write tests in the much more natural (for me) "if (someString.IsNullOrEmpty())..." format. Personally I find this much easier to read.

Flush with this success I immediately added another library function I remembered from Delphi that, in my opinion, helps with readability:

public static class ObjectExtensions
{
     public static bool IsAssigned(this object target)
     {
          return target != null;
     }
}

Instead of "if (someObj != null)..." I could now say "if (someObj.IsAssigned())..."

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.

I'll admit, these aren't earth-shaking, industry-changing algorithms. But in day-in, day-out coding, I find the resulting code much easier to read.

Today I threw together a couple extensions to simplify work with Points, Rectangles and ranges:
public static Extensions
{
     public static Point Center(this Rectangle bounds)
     {
          return new Point((bounds.Left + bounds.Width) / 2, (bounds.Top + bounds.Height) / 2);
     }

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

     public static int ConstrainTo(this int constrainedValue, int min, int max)
     {
          return Math.Max(min, Math.Min(constrainedValue, max));
     }
}

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.

Yes, extension methods are pretty cool!

Friday, April 12, 2013

Unit Tests Not Found in VS2012 and How It Was Fixed (partially)

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.

The Resharper test runner (the one I normally use) listed all the tests and reported their status as "Inconclusive. Test not run."

The test runner built into Visual Studio didn't list any tests at all. Zip. Nada. Nothing.

A web search revealed some posts indicating there was a compatibility issue between VS2012 and Resharper that was supposedly fixed in VS2012's Update 2. I downloaded and installed the update.

After this, Resharper listed all the tests and reported their status as "Pending" 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 "Inconclusive" state gives a sense that something's wrong, even if it doesn't say what.

On the other hand, Microsoft's test runner... still did the same thing. Absolutely no indication that any tests even existed.

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.

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's disk. I wondered what would happen if I moved the code to the C: drive.

As soon as I loaded the project from its new location on C:, Microsoft's test runner immediately found and ran the tests.

Unfortunately, Resharper's still doesn't work. It continues to set them to "pending" and never does anything else. Apparently this is a known issue that hopefully will be fixed soon.

(Hopefully I'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.)

Thursday, December 6, 2012

Apparent binding problems with NotSupportedException in PresentationFramework

I ran into this problem twice over the last couple weeks. Perhaps if I write an article, it'll help my future self (and just perhaps someone else) not spend so much time on it...

I put together a simple WPF form with a ListView. The ListLiew's View contained a GridView with columns bound to a POCO'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'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.

Everything should have worked.

However, when items were added to the collection, the debug window reported:
A first chance exception of type 'System.NotSupportedException' occurred in PresentationFramework.dll
Over the years, I've found data binding to be a challenge to get working. Part of the problem is it's mostly silent when it fails. So, data simply doesn't show up where it'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.

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:
ListViewDetails.Add(detailData);
to:
Dispatcher.Invoke((Action)(() =>
    ListViewDetails.Add(detailData)));
and everything worked properly. A simple solution once I realized what was wrong.

It'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't have spent so much time going down a dead-end road.

Wednesday, October 31, 2012

Sandcastle Help File Builder and error MSB4062 on Team 2008 build agents

I recently had to add a Sandcastle Help File Builder 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.

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:
error MSB4062: The "SandcastleBuilder.Utils.MSBuild.BuildHelp" 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 'file:///C:\Program Files\EWSoftware\Sandcastle Help File Builder\SandcastleBuilder.Utils.dll' 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 <UsingTask> declaration is correct, and that the assembly and all its dependencies are available.

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 InfoSupport article about building VS2010 solutions with the 2008 build agent. This article described a means to fix a problem with a similar error message and, even though it wasn't related to Sandcastle, I decided to give it a try.

Short answer: it worked!!

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.

The solution is to change a setting in a .Net configuration file.
  1. Edit %Program Files%\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\TFSBuildService.exe.config.
  2. Find the line that assigns a value to the key MSBuildPath.
  3. Change the value from an empty string to the directory of the .Net runtime that should be used, e.g. %WINDOWS%\Microsoft.NET\ Framework\v4.0.30319.
  4. Save the file.
  5. Either stop/stop the TFS build agent service or reboot the machine.

I hope that helps someone else.

Thursday, July 19, 2012

Are Coding Philosophies Irrelevant?

I recently read a rant opinion piece about how the behind the scenes part of an application is irrelevant. The author had some good points. One was, from an end user'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.

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'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.

The computer just does as it's told. It doesn't care what it's told or the meaning behind the why or how. It doesn'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't care why this addition is done, or the importance of assigning the result to one place over another. The mechanics of line
x = y + z
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.

To the computer, these two lines are equivalent to the one above.
balance = beginningBalance + deposit
newHeading = currentHeading + errorDelta
However, to a developer, assuming the variable names are accurate for the problem domain, they communicate very different things.

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's vision of how to do it.

In the greater scheme of things, they are far from being irrelevant.

They are critical.


Update: I just ran across this quote I thought was appropriate:
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.
-- Donald E. Knuth, Selected Papers on Computer Science
And this reminded me of another quote:
You're creating a vocabulary, not writing a program. Be a poet for a moment.
-- Kent Beck