St. Louis ALT.NET meetup
The ALT.NET community is a loosely coupled, highly cohesive group of like-minded individuals who believe that the best developers do not align themselves with platforms and languages, but with principles and ideas. In 2007, David Laribee created the term "ALT.NET" to explain this "alternative" view of the Microsoft development universe--a view that challenged the "Microsoft-only" approach to software development. He distilled his thoughts into four key developer characteristics which form the basis of the ALT.NET philosophy:
- You're the type of developer who uses what works while keeping an eye out for a better way.
- You reach outside the mainstream to adopt the best of any community: Open Source, Agile, Java, Ruby, etc.
- You're not content with the status quo. Things can always be better expressed, more elegant and simple, more mutable, higher quality, etc.
- You know tools are great, but they only take you so far. It's the principles and knowledge that really matter. The best tools are those that embed the knowledge and encourage the principles (e.g. Resharper.)
The St. Louis ALT.NET meetup group is a place where .NET developers can learn, share, and critique approaches to software development on the .NET stack. We cater to the highest common denominator, not the lowest, and want to help all St. Louis .NET developers achieve a superior level of software craftsmanship.
Join us by becoming a member of the St. Louis ALT.NET meetup.
Print This PostHow not to unit test
I remember when I wrote my first unit test. It happened at a point of realization -- I had enough experience writing code that the pain of software bugs started to outweigh the joy of software development. I'd heard about unit tests from friends, read about them on blogs, heard about them at conferences. When I inevitably wrote my first test, it was pretty frightening. I understood enough about unit tests to limit each test to a single class method or property, but I did not understand that dependencies would be my undoing. My early tests traversed all layers "downstream" of the object under inspection, and even queried the database and live web services. My tests tended to look like this:
Since those early days, I've learned a lot about unit testing, specifically that it helps you break your dependencies so that your code can be tested in isolation. Testing across software "layers", i.e., testing a unit of code and its dependencies can be considered anti-testing, and actually gives you false confidence in your system when, in reality, it is a fragile cacophony.
1. Tests across layers require an exponential number of tests.
Every developer who writes dependency-traversing unit tests eventually comes to the sickening realization that no matter how many tests he writes, the possible combination of parameters and possible code branches that could be executed in any given test is, well, staggering. For every new layer, or every new dependency, the number of tests for a given member would be raised to the value of the number of tests for that dependency. In contrast, if the dependencies of a given unit of code are mocked or stubbed for the purposes of unit testing, the developer only has to write the tests that would test the code immediately under inspection. In other words, breaking dependencies = additive, keeping dependencies = exponential.
2. Tests across layers require simulated application state.
Any developer maintaining a large config file for his tests knows how much of a pain this is. If the application relies on:
- configuration values that are read by the application at startup;
- configuration values that are provided by background threads;
- configuration values that are retrieved from database calls;
then code that relies on this state, either directly or through dependencies, must have unit tests that recreate it for every test run. Again, this can be very prohibitive, especially if the volume of configuration data is vast, or in relatively inaccessible places (e.g., other threads).
3. Tests across layers can give false positives.
A unit test is typically named for the unit of code being tested, for example, CalculateCartTotal_SomeState_SomeExpectedResult(). If this unit test spans application layers the developer who wrote it won't immediately know if an error in the test is a result of a calculation failure, corrupt database data, missing session values, etc. The test might fail for reasons that have absolutely nothing to do with calculating a shopping cart's total price. Precious development time is often spent debugging test paths to determine where the offending dependency lies.
4. Tests across layers can give false negatives.
Because of #1, it is possible that all tests for a given method will pass, even though the method itself is flawed. This can occur because the chance of a developer missing a given combination of state and behavior in a unit test is significant. This is possible in test suites where dependencies are removed, of course, but is far less likely given the reduced number of possible tests and the ability to simulate known state (by mocking and stubbing) that will produce exact, expected results.
5. Unit tests are for code, not data or connectivity validation.
A common justification I hear for encouraging unit tests that cut across application layers is: "It helps us know if our data is correct." This justification confuses the role of unit tests and integration tests. Unit tests are designed to determine if code functions properly, not if a given system can connect or retrieve data from another system. Integration tests help us to validate those boundaries, but unit tests are only concerned with the behavior of code. The validation of data should occur as close to the data source as possible, even within the data source if possible.
6. Unit tests across layers are slow.
One of the primary benefits of dependency-ridden unit tests is that they are fast. A developer can run a suite of unit tests in a matter of seconds, or minutes if the code base is particularly large. This means that the developer gets instant feedback about changes made to the system. If unit tests cross data access boundaries, or query live services, performance will drop dramatically. In a high-pressure deadline-driven environment, this encourages developers to ignore unit tests altogether, or leave them for "later" (you know, the later that never comes). Without unit tests as a feedback mechanism the developer will revert back to the days of design-by-debugging.
7. Remember: testing the sum of the parts = testing the whole!
So if dependencies are bad in unit tests, how does one test the system in tot0? If all dependencies are tested in isolation, that is, without reference to, or reliance on, any other testable code, they will work when combined if all unit tests pass. Software systems should be decoupled anyway -- your code should have a sparse number of direct references to concrete types, and instead, rely on references to abstract classes or interfaces which can easily be mocked or stubbed with mocking frameworks. Real unit tests help you see where these dependencies are, and eliminate them.

In this example, ClassA has a direct dependency on ClassB, as show by field _b. When a unit test is written for SomeMethodThatUsesB(), ClassB will directly affect the outcome of the test. In contrast, If ClassA depends on an interface for ClassB:
then the implementation of ClassB can be replaced with a mock object with known state and behavior, that will affect the unit tests for SomeMethodThatUsesB() in a known and controllable way. Not only is this good unit test design, it is good object design as well (the implementation for ClassB can be extended in your application without breaking classes, like ClassA, that depend on the interface IClassB).
The good news is that writing correct and accurate unit tests will make you a better developer. The bad news is that people often feel a warm fuzzy feeling if their tests span layers in an application, because they believe it offers better "coverage". Nothing is further from the truth. Breaking applications down into discreet units and testing each unit in isolation, under controlled conditions, is the only way to achieve accurate test results and prevent those early AM calls from disturbing your beauty sleep. Now go forth and test.
Print This PostSt. Louis Day of .NET 2010
St. Louis .NET developers had a busy weekend last Friday and Saturday -- over 650 of them attended the third annual St. Louis Day of .NET. The conference, which began in a crowded WashU meeting room three years ago, has pulled speakers, attendees, and sponsors from all over the United States, and has even gained the attention of Microsoft. For $200 (or $125, if registrants took advantage of the early bird special), attendees were treated to over 100 sessions on .NET-oriented technologies, open discussion sessions, a great party at Ameristar's HOME nightclub, and a special keynote by Microsoft representative Brian Goldfarb. Secondary perks like great swag, prizes, networking, and a used bookstore (that donated all proceeds to charity) added to the legitimacy of the event. The Midwest is often eclipsed by the big conferences on each coast, but last weekend that didn't matter -- St. Louis developers had a solid, professional, mature conference to call their own.
I attended a number of interesting sessions, a few of which I will briefly enumerate here (IEnumerable<Session>?), although my mental saturation point was nearly reached late Saturday as I struggled to retain retain retain. For a taste of what the event offered as a whole, check out the sessions and speakers pages on the official website.
WTF# - Ken Sipe
My exposure to F# has been pretty limited, mostly due to time constraints and no immediate reason to add it to my skillset, but Ken's talk sparked my interest and convinced me that I need to invest some time in this new functional language from Microsoft. I enjoy Javascript and LINQ, which are not pure functional language implementations but definitely have functional flavor; and a friend who shall remain nameless but who KNOWS WHO HE IS always bugs me to try Scheme, so perhaps this is a good way to ease myself into that world of out-of-control parentheses and alpha-geeks who mock IDEs other than Emacs. F#, a derivative of oCaml, is a strongly typed language that can leverage .NET framework libraries. Ken demonstrated that it is more performant than C# in parallel operations, and in many cases results in a smaller IL footprint when it is compiled. Since parallelism is the Big New Thing, and since I want the most bank for my buck from the four cores idling in my beefy development box, the magnetism of F# is is multiplied. Off to write some lambdas bitches!
Open Discussion: Entity Framework vs. NHibernate - Jesse Phelps
The open discussions were some of my favorite sessions at #STLDODN. This particular session was very important to me because I have strong opinions about both EF and NHibernate, and it was good to let everyone know that NHibernate is the One True ORM... I mean, discuss the pros and cons of both ORMs in the context of specific business needs. There were knowledgeable people present who had used each and had much to contribute to the discussion. I was even further impressed that there were DBAs present who wanted to know what all the hullabaloo was about, and had very specific questions about the performance, the quality of ORM generated SQL, and the place for things like stored procedures in a system that uses an ORM. Jesse did a great job guiding the discussion; additionally, no fist fights broke out.
NHibernate and Friends - Lee Brandt
I have been learning the NHibernate ORM for the last couple of months, so this session was a good refresher on some of the associated libraries that work with NHibernate. Lee covered Fluent NHibernate, a library that allows a developer to specify mapping configurations via a fluent interface (method chaining) instead of those eeeevil XML files. Personally I think the fluent interface can become a little messy with more complicated mappings, but that downside is offset by two key benefits: a) using fluent allows the developer to refactor both entity objects and affect the mapping directly (since the fluent interface is strongly typed code), and b) there is a performance gain because XML files do not need to be parsed when the application starts. Lee also demonstrated LINQ to NHibernate, an open source LINQ provider that allows NHibernate sessions to be queried using LINQ syntax. My favorite quote of the conference came from this session: "We take what the Java guys do and stick an 'N' on the front. That's our originality."
Open Discussion: Silverlight vs. WebForms vs. MVC - Kevin Grossnicklaus
Like the NHibernate open discussion, this session compared and contrasted three approaches to writing applications in a web-centric environment. Kevin is an unabashed Silverlight enthusiast, and provided compelling reasons (ease of development, rich user experience, single programming language) for using Silverlight as a platform for internal web applications. Many there, including myself, have jumped onto the MVC wagon, and argued that web technologies should not fight the web stack, but embrace it (i.e., Javascript should be in everyone's toolbox, ViewState is evil, and id attributes should not be hijacked). The WebForms developers were fewer in number than I expected, and were interested in understanding *why* the MVC developers had jumped ship. Everyone had at least some experience with Webforms, so it was much easier to compare technologies. Nik Kalyani, co-founder of DotNetNuke was present for the discussion, and provided some observations about the challenges he experienced using WebForms as a platform for the DotNetNuke CMS.
Going Independent 101: Lessons Learned from a Decade of Independence - Michael Eaton
By far my favorite session, Michael's highly practical and highly personal talk about working for oneself was both entertaining and inspiring. Michael started by telling everyone about his personal path from corporate cube dweller to independent software developer, being very careful to point out his mistakes along the way so those who might follow could avoid the traps he fell into. He covered practical topics like time management, finding clients, self-discipline, hiring an attorney and an accountant, etc. He talked about the tools he uses to successfully run projects, including his trusty notebooks for brainstorming and tracking client time (It's not software! Heresy!). He stressed the point that, above all, being independent gives him the flexibility to invest in his family and personal life, often a powerful motivation factor for those who want to be self-employed. Michael's hard work and success definitely lit many fires in the room.
There were many more great sessions that I was unfortunately unable to attend -- nearly 11 sessions running in parallel every hour. I was forced to pick and choose, and the decisions were difficult but I was not disappointed with the quality and variety of the sessions I attended. A big thanks to all organizers and volunteers who made STLDODN 2010 a big success!
Print This PostDynamic CSS and the Plan of Attack
I'm working on an ASP.NET website where I need to generate dynamic CSS, mostly for "theming" purposes. I really don't like .NET skins or themes -- I prefer straight CSS and markup; besides, it needs to be configurable through an administration page and persisted to a database. Here are the options I'm contemplating:
- Allow the client to define CSS styles and generate a flat file based on what is in the database when the web application loads (if no file exists, write one -- reference that for every subsequent request). The downside is that I have to write to the filesystem, which means at least one publicly exposed directory must be writeable by some process. The upside is that browsers will cache the file, so no subsequent requests are needed.
- Allow the client to define CSS styles and write them to the output stream using a specialized instance of IHttpHandler. The upside is that, well, this appeals to the code monkey in me. The downside is that I'm not sure if a browser will cache this since it's not a CSS file per se. I suppose some experimentation is in order.
If anyone has experience with this, please let me know what solution you settled on.
Print This PostNew Events page
I have added a new page for developer events in the St. Louis/Kansas City areas. If I have missed a big event (not local user group meetings), please let me know.
Also, Illinois, I have not purposefully left you out. I just don't know what goes on over there in those corn fields!
Print This Post.NET Rocks Roadtrip: Destination St. Louis
Yesterday the .NET Rocks! Roadtrip came through St. Louis and local developers were treated to a very special live broadcast of the .NET Rocks! podcast by Carl Franklin and Richard Campbell, two tech heads who are just south of sane and a whole lot of fun to hang with! The roadtrip is a fifteen-city trek across America in a large RV, sponsored by Microsoft product teams and many .NET component, control, and tool providers. The roadtrip team can be tracked in real-time with a feature-rich Silverlight app that integrates Bing mapping technology, live tweets featuring the hashtag #dnr_roadtrip, and Flickr image posts of the roadtrip team and RV.
During the first hour the podcast was recorded live with special guest Kate Gregory--developer, writer, professor, and computer science PhD. The discussion began with some brief overviews of Windows 7 development features and .NET Framework 4 enhancements that leverage them. The banter was lively and the dual of wits commenced when Kate revealed that her two favorite languages are C++ and Visual Basic. (A confession which, in a room of C# developers, is tantamount to heresy!) She was quick to point out that Microsoft's MFC libraries have received a hefty update in .NET 4, so people who write "trivial" applications like game engines, device drivers, and operating system libraries have finally received some love. I had never heard Kate speak before, and it was quite an entertaining and enlightening hour. I hope she will continue to be a guest on future .NET Rocks! podcast episodes (hint, hint). To listen to the full 41 minute podcast, and read a more robust description of Kate Gregory's accomplishments, check out the podcast page for show #551.
Richard took stage for the second hour and demonstrated the new load testing features in Visual Studio 2010 Ultimate Edition. He totes a "datacenter in a bag" which consists of four mini microcomputers, a switch and a bunch of network cables. In the mix were two Windows 2008 web servers, an SQL Server 2008 database box, and a Windows 7 client machine running Visual Studio 2010 Ultimate for load testing. Richard started with the price tag: ~$12,000 for 2010 Ultimate, which is not a bad investment considering comparable load testing suites are typically priced in the 10k range. And 2010 comes with an IDE as well! (joke) He fired up his web servers (both running a mock storefront ASP.NET web application), created a load testing project in Visual Studio, specified the testing parameters (there are many testing scenarios to choose from), connected the IDE to the target web server's performance monitor, and let the test run for about sixty seconds. When the test finished, Richard showed us many colorful graphs and explained that a) colorful graphs are a good way to convince your boss that you are being productive, and b) each colorful graph actually has extremely valuable data that can help pinpoint bottlenecks in hardware and software. One thing that I was particularly impressed with is that Visual Studio also monitors the machine *performing* the load testing as well. This is important because if the machine performing the testing can't keep up with the rigor of the test parameters, the data might lead to wrong conclusions. When Richard was finished I found myself wishing I had a spare 12k to drop on Ultimate, but all the loose change in my couch only amounts to about $0.70, so it will be a while.
For the third hour, Carl showed off pictures of his amazing recording studio, audio and video equipment, and the plethora of musical devices he keeps stashed away in his home. Truly a man of many talents, Carl plays just about any instrument and sings too. After making us wish we were all artists and not code monkeys, he showed us some hot features of Silverlight 4 and the Expression suite of tools, specifically video encoding and playback. He demonstrated how Silverlight video had been leveraged during the Olympics to provide coverage for the duration, and how it is being used to provide an interactive experience with Sunday Night Football. He pulled up the latest copy of Expression Encoder and demonstrated how videos can be "tagged" at certain time stamps with a piece of data (think CommandArgument in ASP.NET), and those tags could be intercepted during playback in a WPF or Silverlight application with a special event handler. The data that each tag contains can then be used to instruct the application to respond to that moment of video playback (maybe show a slide, cause UI controls to change state, go to a URL in a browser, etc.). For the grand finale, Carl demonstrated a Silverlight application that interacts with an attached webcam, which can identify a specific artifact that the webcam is "seeing" (in this case, it was a piece of paper with a specific symbol on it), and then replace that artifact with another image, a video, a textbox--essentially anything that could be rendered in Silverlight. Carl held the paper up to his face and his face was instantly turned into a giant textbox that could even accept input from the keyboard. Whenever he would move his face, the textbox would follow the plane of his head and adjust itself accordingly. While textboxes are great fun, he mentioned that real-world applications already exist for such technology, such as on-screen annotations during a football game (the yellow highlighted line of scrimmage superimposed over the field, for example).
Once all presentations were complete, swag was distributed to lucky attendees by random draw. The kicker was that they had to answer a trivia question before they received their prizes. Question topics ranged from obscure facts about the .NET Rocks! podcast to identifying incorrect regular expressions for email validation. Most people were fairly nervous at first but special "clues" were present in each question that made guessing lots of fun.
Special thanks to Carl, Richard, Kate, and the local St. Louis .NET attendees and sponsors who worked hard to make an enjoyable evening. You guys are the best!
Print This PostWhy Agile Works
The ability to err early and often is essential to getting real work done. We are taught this in school when teachers tell us to write a rough draft of our final paper, store it away for a day or so, then revisit it several times refining and correcting as we go. Unfortunately most of us always waited until the last minute to write our first (and final) draft, and produced something frightening as a result. Writing software is not so dissimilar.
Print This PostIE does something better than Firefox, hell freezes over
Like most web developers, I write markup and Javascript that will work on both IE and Firefox, and if I'm particularly ambitious, Chome and Safari. I've been writing a lot of Javascript lately, which has been a good learning experience but frustrating at the same time. I don't have the luxury of using jQuery on my current project -- I am pretty much restricted to Prototype for legacy reasons. I was in the throes of reconciling a piece of code that copied values from one set of input fields to another, then accessing the innerHTML property of the target fields' containing div. I was doing simple value assignments ($("textBox1").value = $("textBox2").value), and in IE everything worked like a peach. Then I tested in Firefox and, to my amazement, the target input fields remained blank, even though FireBug assured me that the values were in fact being copied. I was certain I was making a mistake somewhere in code, and spent an hour or so meticulously pouring over every line of Javascript, attempting to find the roadblock. In desperation, I turned to the Google in search of an answer. What I found surprised me enough that I felt compelled to write this post.
Firefox does not reflect dynamic DOM changes in the innerHTML property of a given DOM element.
This means that if you set the value of a text box to "123", then call the innerHTML property of the DOM element that contains the text box, the value of the text box according to innerHTML will appear to be whatever it was prior to your alteration. In practice, when the page posts back to the server, the value will actually be "123" and not what innerHTML reports, but the fact that Firefox ignores the change gives me yet one more gray hair.
To get around this glaring oversight, I had to use the setAttribute() method on the DOM input element:
$("textBox1").setAttribute("value", $("textBox2").value);
This accomplishes both tasks -- updating the actual input value and changing the innerHTML property accordingly.
You've won this round IE... you've won this round.
Print This PostRed Gate releases Reflector 6
Lutz Roeder scored major points with developers the world over when he released his .NET Reflector software, a tiny package of TNT that lets the user examine compiled .NET assemblies, and even disassemble them (for debugging purposes). I know it's a tool I couldn't live without. I've used it countless times to examine APIs of core .NET libraries, as well as third party, ill-documented assemblies. (What? No documentation? Perish the thought!) In 2008, Red Gate acquired the rights to enhance and publish reflector, and so their first polished incarnation has wandered into the wild. .NET Reflector 6 is still free, but an optional "pro" version may be purchased for a paltry $195.00. Reflector has been upgraded to support the new .NET 4.0 framework, and both versions come with Visual Studio integration. Reflector Pro includes the ability to decompile from within Visual Studio, and debug step-through capabilities as well. (You know, for those times when you're certain that Microsoft has screwed something up in their base class libraries because your own code is pristine.) Add-ins for Reflector can be found on the Reflector Codeplex site in case the gun just isn't big enough for you out-of-the-box.
Print This Post

Avoid Unnecessary Comments
This morning's short read is "5 Types of Comments to Avoid Making in Your Code". No developer doubts the benefit of good comments, but when the signal-to-noise ratio tips in favor of noise, productivity can actually be hindered. I know I'm guilty of using at least one of these forbidden comment types in my code, but
Print This Post