Archive for the ‘Programming’ category

Unit Testing and Code Change

January 29th, 2010

This morning I made a small but important change to a chunk of code that our entire Silverlight application uses.  This code, lets call it the Manager, facilitates every work flow through the application.  The code change to the Manager amounts to deleting some unused code, changing some types, and some small tweaks to how new screens are called.  On the surface the actual lines of code changed appeared to be very simple, but I was nervous I would break something since this is a fundamental piece of code.  Everything uses the Manager.

Code can have subtle and dangerous dependencies.  Even when one is the author (as I am in this case), one cannot be completely sure of the consequences of a code change in a sufficiently complex system.  This is where unit tests come to the rescue.

I was able to execute my suite of unit tests, and after a successful report I ran through a few regressions with live data.  Everything works.  And I commited the code to our repository with a high level of confidence.

If something had broken I would have fixed it, and then written a unit test to check for the condition in the future.

Unit tests are a pain to write, but they sure do have a big payoff.

Code Snippet Editor

December 30th, 2009

I stumbled across this great Visual Studio code snippet editor and thought I should share the link.  I have already created a few snippets with it, and it my development time is benefiting from it.

The editor allows one to highlight existing code and export it into a snippet file.  This is a great launch pad for snippet development.  The editor runs in Visual Studio, and once a snippet is saved with a shortcut it is immediately available in the IDE.  The editor also allows the editing of existing snippet files.

C# 4.0 Goodness: The dynamic Type, The DLR, and The ExpandoObject Type

November 10th, 2009

I have been playing around with C# 4.0 Beta 2 and stumbled onto the ExpandoObject (in the System.Dynamic namespace, System.Core assembly).  The object is built to be used in the DRL (Dynamic Language Runtime).  The DLR is a way for strongly-typed code to play nicely with weakly-typed code like IronPython, and vice-versa.  In C# 4.0 the dynamic keyword is used to reference objects that are weakly typed, and the ExandoObject is a .Net class that pretends to be a weakly-typed object.

ExpandoObject allows for addition of member properties and methods are run-time similar to popular scripting languages like Javascript.  Yet ExpandoObject is a real .Net type, and implements a couple of  interesting .Net interfaces: IDictionary<string, object> and INotifyPropertyChanged.  A dictionary of members is provides through the dictionary interface, and property changed events are fired through the property changed interface.  The only way to really leverage the power of ExpandoObject is with the dynamic keyword/type, which skips compile-time checking.  Method and property calls are not shown in intellisense.  You don’t know if your code will execute property until run-time.  So to access the above mentioned interfaces, the ExpandoObject’s dynamic reference must be cast to the interface type.

Here is some very simple, sample code that illustrates the concepts discussed (runs in Visual Studio 2010 / .Net 4.0 Beta 2):


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Dynamic;

namespace DynamcMethodExample
{
    class Program
    {
        static void Main(string[] args)
        {
            dynamic person = new ExpandoObject();
            person.Name = "John";
            person.Gender = 'm';
            person.Age = 10;

            Console.WriteLine(person);
            Console.WriteLine(person.Name);
            Console.WriteLine(person.Gender);
            Console.WriteLine(person.Age);
            Console.ReadKey();

            person.MakeTacos = (Func<string>)(() => "Tacos are ready!");
            Console.WriteLine(person.MakeTacos());
            Console.ReadKey();

            ((INotifyPropertyChanged)person).PropertyChanged += (s, e) =>
                {
                    IDictionary<string, object> personAsDictionary = (IDictionary<string, object>)person;
                    Console.WriteLine("Property {0} changed to {1}.", e.PropertyName, personAsDictionary[e.PropertyName]);
                };

            person.Name = "Jane";
            person.Gender = 'f';
            person.Age = 11;
            Console.ReadKey();

        }
    }
}

New Types in .Net 4.0

October 29th, 2009

A lot of the hype around .Net 4.0 is surrounding new features such as the Dynamic Language Runtime (DLR), and C# 4.0 features such as the dynamic type and co/contra-variance.  Something not getting as much press, but in many ways more helpful is the inclusion of many new, useful types included in 4.0.  The BCL team has a blog article about many of these types.  Here are a couple of my favorites:

  • Enum.HasFlag(Enum enum)
    I have written this code a couple of times before.  It detects whether a bit is set in an enum Flag value.
  • Enum.TryParse<EnumType>(string value, out EnumType result)
    I have also had to write this.  I think every core value-type should have a TryParse, which leads to:
  • Guid.TryParse(string value, out Guid result)
  • String.Join and String.Concat now take IEnumerable<T>!  I have written string.Join(“,”, values.Select(v=>v.ToString()).ToArray()) more that a few times.

I am really looking forward to .Net 4.0.  If you want to get your hands on it now .Net 4.0 and Visual Studio 2010 are available for download here.

Google Wave Authors

October 27th, 2009

CNN is running a story about the two guys most responsible for Google Wave.  These are the brothers that built Google Maps.  If you haven’t seen Google Wave, here is a rather long video that goes into some detail:

Unit Testing in Silverlight

October 26th, 2009

Something I am a really big fan of is Unit Testing.  I was a big evangelist of unit testing at my last company.  The code my team wrote unit tests for was, on average, much better code than code that was written without unit testing.  Code-testing coverage via unit testing creates solid code.  It allows developers to thoroughly test their code in an automated fashion.  Unit tests give the developer confidence that they have introduced few or no regressions with new functionality added to old code.  All one needs to do is re-run the old unit tests to ensure everything still works.  Unit tests are a great form of documentation.  When a developer maintains code written by another they can inspect unit tests to see how the code is used, and can run these unit tests to ensure they aren’t breaking functionality they may not understand.  Ultimately unit tests act like a code specification.  In fact there is a style of coding called Test Driven Development (or its sexy new name, Behavior Drive Developer) that mandates that the tests be written first, and then the code is not considered complete until it satisfies the tests.  And even when unit testing is not take to that extreme, developing code that works well with unit tests usually ensures well-designed code from an object-oriented standpoint.  Code that is easily tested by a unit test is usually adequately decoupled and uses OO principles like inheritance, encapsulation and polymorphism in the right way.  Finally, writing code with unit tests can be faster.  Running tests can take less time than standing up an application and entering in the correct criteria to test the code in question.

At my current employer I have found myself working with a very mature (and very good) code-base that does not lend itself to unit testing.  It has probably been a year since I have written a unit test at work.  So when I started diving back into Silverlight I made it a goal to write our new framework to be as compatible with unit testing as possible.  This will help lesson the burden on our QA team, which has already written a lot of UI testing for our current ASP.Net web application.  We will also receive all the benefits mentioned above.

To start off I needed a unit testing framework.  NUnit is my old unit-testing friend and was my first thought.  However, NUnit and other unit testing frameworks don’t work in Silverlight-land, since Silverlight relies on a slightly different set of core .Net assemblies.  I did discover that there is a Silverlight version of NUnit and I considered it.  I also found the Silverlight Unit Testing Framework from Microsoft thanks to a post over on Scott Gu’s website.  The Silverlight Unit Testing Framework is based on the Microsoft library for normal .Net (which is also based on NUnit) but runs in Silverlight, in the browser.

Ultimately I chose the Microsoft library for a couple of important reasons.  First, there seems to be more acceptance and more example of the Microsoft library.  Second, the Silverlight Unit Testing Framework does one thing that is very unique compared to other unit testing frameworks: it runs the tests in the UI thread.  Jeff Wilcox, one of the authors of the framework, has an excellent post here about why Microsoft chose to do this, and it really makes sense.  Silverlight is a graphical library, and bugs will best be found if testing is written from a user-interaction standpoint.  Many things run on the UI thread, or are marshaled back and forth.  The Microsoft Silverlight Unit Testing Framework can work both as a unit testing framework and as a kind of integration testing framework.  The framework makes it very easy to test off the UI thread, and test asynchronously.  I found this excellent post on using the async features of the Silverlight Unit Testing Framework.  It really boils down to the testing environment being the same as the real run-time.  I have run across enough idiosyncrasies in the way Silverlight handles UI thread interaction to know that testing without it will miss a lot of bugs.

I have developed some “test” tests on business objects.  I also tested a thread manager I wrote using the built-in async functionality.  With the experience so far, I feel happy with the results.  My next step is to look at pluging in the unit tests into the automated build at work…

Microsoft WebsiteSpark Program

September 24th, 2009

Scott Guthrie just announced a new program that Microsoft is offering, for free: Microsoft WebSiteSpark Program.  It looks like there are giving away some free software and services to help small business develop with Microsoft.  It looks pretty smart, and pretty cool.

WebSiteSpark

CodeRush Xpress for Visual Studio 2008

September 10th, 2009

After watching this video about CodeRush XPress I decided to try it for myself.  I downloaded it on Tuesday morning and have been using it all week.  While I haven’t used all of the features, I have been impressed with several of the things with this free version of the product.  Two things I particularly like are the code snippet refactoring and the ability to auto-gen a class or function simply by writing the calling code then using the appropriate hot keys.  It saves a lot of typing.

As I mentioned, this is a free version.  The full version, which has a number of additional Visual Studio enhancements, is $249.  These types of tools are nice, but way overpriced.  I think they would make a lot more money if they sold it for a reasonable price.  Trying to get an employer to by software is like trying to pull teeth.  This free version adds a number of nice features to Visual Studio.  If you spend any real time in C# or VB.Net you should try it.

UK: We are sorry Turing

September 10th, 2009

I have written about Alan Turing before.  Today The Prime Minister of the UK apologized for the disgusting treatment of Turing in the 1950s.  It was long overdue.

Turing Home

Visual Studio 2010

September 1st, 2009

Scott Guthrie has a very informative series about Visual Studio 2010 over on his web site.  Today’s article is about enhanced multi-monitor support in VS 2010.  I have only had a chance to use VS 2010 in a virtual machine, and have not had a chance to take the multi-monitor stuff mentioned in his article for a test drive.  It does look very cool.

Something I am particularly interested in is support for varying numbers of monitors.  At work I have a dual 19″ monitor display rig.  At home I remote into my desktop from my single-monitor 17″ laptop.  I occasionally have trouble with windows displaying correctly when I remote in. particularly using Visual Studio 2008 with tool boxes that are on the second monitor.  In VS 2010, window settings are kept in the local user file for the project, so if nothing else one should be able to move off-screen windows on-screen with a little text editing.  I am interested to see what kind of built-in support VS 2010 will have to detect that the second monitor is not present in this type of situation.  If it doesn’t auto-detect, it might now be easy to build a tool to edit the user file, or swap out user files.