Drop in the Bucket
One coder in the sea of s/w knowledge

What's Your Wordle?

Visualizing Your Blog

I've been into data visualizations lately. I'm inspired by code_swarm and wordle.

Here's the wordle of my blog:

weighted word cloud of the words on my blog

Basic Databinding in XAML with Silverlight

There are a lot of really great detailed posts about databinding in your XAML application, in both Silverlight and Avalon (WPF). This isn't one of them :). This post will focus on the mechanics for a couple of ways you can make databinding work. There are many other, and arguably better, ways of doing these same simple things. I'm constantly suprised by how flexible WPF and XAML are in how they can be programmed; which is great when your wild and creative ideas work, and horrible when you can't accomplish the simpliest thing.

Binding Syntax

The basic syntax is pretty simple. This little snippet of XAML sets the Text property of the TextBlock to whatever the value of the LocalTime property is.
The curlies inside the attribute tell the XAML parser there's some magic code inside. Binding is one of the keywords. Where did the LocalTime property come from? Enter the DataContext.

Setting and Changing the DataContext

The DataContext is the name of the control's (page's) property for the source of the data. This little application:

consists of an un-named TextBlock and a button called the announceTimeButton. The DataContext is set in two places; the constructor and in the button's event handler.

The LocalInformation class is a little class which serves as this application's "ViewModel" (i.e., the thing you bind your XAML controls to). For reference, here's the source for that class:

What if you didn't want to new up a different instance for some reason? What if the LocalInformation class was expensive to construct, or if, gosh darn it, you were just tickled
to be programming in a statefull environment again. Enter INotifyPropertyChanged

Implement INotifyPropertyChanged

I'll change the page's code to use a statefull instance of the LocalInformation class. I'll set the DataContext initially in the constructor, but leave it alone after that. Don't worry the binding
defined in the XAML will stick.

When the announceTimeButton is clicked the LocalInformation object will be tickled, and the magic that comes from having your "ViewModel" implement the INotifyPropertyChanged interface will kick into action. All elements bound to the affected properties will be, ummmm...re-bound? Notice the special new UpdateLocalTime method:

For the purpose of this example, I put the firing of the PropertyChanged event inside this method. Most of the time you'll see this refactored into it's own method so that all the properties of the class can take advantage it. The name of the property that is being updated is passed through the PropertyChangedEventArgs. The only other important change to our LocalInformation class is the addition of the interface itself, which forces the edition of the PropertyChanged event.

Automatic Updates

So, what if you wanted some thread or timer to update the local time automatically. After all, pushing that button is awfully tedious. I know what you're thinking, you'll make some sort of "timer", and on it's callback you'll call UpdateLocalTime. Well, you're close. A plain old timer will work, you just have to be carefull that the call to fire the PropertyChanged event makes it back on to the same thread that's running the UI (like good ol' WinForms). This is completely possible with a class called the Dispatcher, so if you wanted to but it in your model, you'd need to pass it in or get it...yadda, yadda, yadda.

Luckily, this common scenario is all encapsulated by another class called the DispatcherTimer (clever name isn't it). I'll make this part of my view model and initialize it in the constructor.

Then I'll add the tick handler and public methods to start and stop the timer.

Notice the smooth databinding in the following application:

The point here is that the property update won't be seen unless it happens on the UI's thread.

Magical Databinding

There's a lot not covered here. It's just the basics as I've learned them. We didn't talk about the binding mode or dependency properties or a thousand other things that come into play when building a Silverlight UI out of XAML. In Silverlight, there are definitely more than one way to do just about anything. Databinding in general is one of the cornerstone concepts around WPF and Silverlight.

Positioning Dynamically Created User Controls in Silverlight

Note: This app was created using Silverlight 2.0 Beta 2

Help Me. I See Spots

Something you'll hear over and over again about Avalon (WPF) and Silverlight is how different it is when compared with more established UI platforms: like WinForms, HTML, ASP.NET, etc... I came face to face with this when I wanted to write a little spike that placed a dynamically generated user control wherever I clicked the mouse. Here's a screenshot of the application in all it's splendor:

screenshot

Wait a minute! Go ahead and try it out in the little blue area below.

How This Works

The page is really simple.

page

Notice that it doesn't contain any elements other than the TextBlock with the instructions. The Canvas element ties the MouseLeftButtonUp event to an appropriately named event handler which will serve as our click event.

Next is the XAML markup for the "ball". This is the user control that we'll create dynamically.

ball

The Width and Height are "intentionally left blank" because we're going to dynamically set the size of the ball as well as it's position.

Positioning the user control is the tricky part. If you were declaring the user control in the page's XAML, you could simply use the attached properties of Canvas.Top and Canvas.Left. The trouble with the dynamic control, is that in the code behind there are no positioning properties like you might expect (X, Y, Left, and Top), and the attached properties are nowhere to be found.

My solution was to supply the control with a render transformation. Specifically, I tie a TranslateTransform at construction time. I explose an X and Y property on the control itself, and alter the transform in the setters.

   15 public partial class Ball : UserControl
   16 {
   17 
   18     private const double DefaultRadius = 25.0;
   19     private const double DefaultX = DefaultRadius;
   20     private const double DefaultY = DefaultRadius;
   21 
   22     private double _x;
   23     private double _y;
   24 
   25     private TranslateTransform _translation = 
   26         new TranslateTransform();
   27 
   28     public double X
   29     {
   30         get
   31         {
   32             return _x;
   33         }
   34         set
   35         {
   36             _x = value;
   37             _translation.X = _x - Radius;
   38         }
   39     }
   40 
   41     public double Y
   42     {
   43         get
   44         {
   45             return _y;
   46         }
   47         set
   48         {
   49             _y = value;
   50             _translation.Y = value - Radius;
   51         }
   52     }
   53 
   54     public double Radius { get; private set; }
   55 
   56     public Ball() : this(DefaultRadius)
   57     {
   58     }
   59 
   60     public Ball(double r)
   61     {
   62         validateConstructor(r);
   63         Radius = r;
   64         Width = 2 * r;
   65         Height = 2 * r;
   66         RenderTransform = _translation;
   67         InitializeComponent();
   68     }
   69 
   70     private static void validateConstructor(double r)
   71     {
   72         if(r <= 0.0)
   73         {
   74             throw new ArgumentException("Please provide...
   75         }
   76     }
   77 }

The page simply news up a Ball and sets the x and y according to the mouse click.

   21 
   22 private void LayoutRoot_MouseLeftButtonUp(object sender, ...
   23 {
   24     Point clickPoint = e.GetPosition(LayoutRoot);
   25     Ball b = new Ball( );
   26     b.X = clickPoint.X;
   27     b.Y = clickPoint.Y;
   28     LayoutRoot.Children.Add(b);
   29 }
   30 
Download the Code

ASP.NET MVC Preview 4: A few things left to do

I decided, I'd try out Preview 4 tonight. In honest to goodness TDD form, I wrote the following test:

   13 [TestFixture]
   14 public class EmployeeControllerTests
   15 {
   16     [Test]
   17     public void List_Should_Render_View_Of_Employees()
   18     {
   19         var controller = new EmployeeController();
   20         var result = controller.List() as ViewResult;
   21         Assert.IsNotNull(result);
   22         Assert.AreEqual("List", result.ViewName);
   23     }
   24 }

The code for the controller is:

    9 public class EmployeeController : Controller
   10 {
   11     public ActionResult List()
   12     {
   13         return View();
   14     }
   15 }

The test fails. The name of the view is null (assertion on line 22 of the test method). Why in the name of all that is ScottGu would this basic test fail? In the actual view, when rendered through the view engine, the view name is "List" as expected (that's the job of the parameter-less call to the controller's View method).

Testing of the controller in isolation is still not fully baked. There still seems to be some disconnect in one of the fundamental goals of the framework: make it easy for Morts like me to write testable code.

Please Read the Error Message

Generic List Doesn’t Support the Query Pattern

I recently wrote similar code to this little fragment (this is a sanitized version for the purpose of this example).

 

   12 
   13 List<int> nums = new List<int> { 0, 1, 1, 2,
   14                     3, 5, 8, 13, 21 };
   15 
   16 var evenQ = from n in nums
   17             where n % 2 == 0
   18             select n;
   19 

 

I was shocked when I received this error message

WTF! What do you mean, a list doesn’t support the query pattern!? That’s absolutely ridiculous. I’m quiting C# development, and I’m converting to writing Rails apps on the Mac….

We interrupt this moment of panic for the following public service announcement:

Developers, do you get tired of reading those pesky error messages? Me too, but remember the compiler team has gone through a lot of trouble to tell you when you’re an idiot and help you recover. Take it from me, if you read the entire error me sage instead of the first half sentence, you’ll be better informed of why you’re such a bonehead and more likely to recover. Now back to our regularly scheduled moment of sanity.

...”missing a using directive?”. Yes, as it turns out I prematurely used one of my favorite VS features: remove and sort using statements.

All is well, and the universe is in a causal state again. Turns out that if you don’t have any dependencies on statements or extensions in System.Linq “remove and sort” will remove the LINQ using statement (duh), and thus all the LINQ goodness will be hidden from the compiler.

Simply adding using System.Linq; fixed this particular goof. Yes, perhaps I’ll read the entire error message next time.

Goodbye Motorola

The Post I Should Never Have Written

I spent the entire month of April, writting and re-writting this post. You see, I used to work for Motorola. As a matter of fact, all combined I worked for them for a total of nearly 13 years. Some of my original drafts blasted middle management, upper management, CEOs, and pointed out all that was wrong with the company.

I finally decided to shelve the burn Motorola post. Motorola is burning by itself without any additional help from me. I will say one thing, the one thing that I feel doomed Motorola, more than any of its problems with management: Motorola forgot that it survived by providing a place for people to innovate. The company started treating everyone like an interchangeable commodity. The company turned its back on being loyal towards its people, and as a result the company lost the loyality of its people—mainly through fear. The end result was the company cutting its own lifeline: innovation.

Refactoring the Sieve of Eratosthenes

I have recently been reading "Agile Principles, Patterns, and Practices in C#" by Robert C Martin and Micah Martin. So far, it's been an enjoyable read. Early on the authors explain the concept of refactoring by showing how they would go about refactoring the "Sieve of Eratosthenes":http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes. The algorithm is a way to generate a list of prime numbers. The final refactored solution is full of loops and breaks, which is fine, but like most things -- it looked like a job for LINQ! I decided to repeat the exercise using as much LINQ as I could reasonably stuff into algorithm. Here is my green pass (of a red-green-refactor cycle).
   18 
   19 public static IList<int> GenerateListOfPrimes(int maxNumber)
   20 {
   21     IList<int> result = new List<int>();
   22 
   23     if (maxNumber > 1)
   24     {
   25         var candidateNumbers =
   26           Enumerable.Range(2, maxNumber - 1);
   27 
   28         double stopNumber = System.Math.Sqrt(maxNumber);
   29 
   30         int nextPrime = 2;
   31 
   32         while (nextPrime <= stopNumber)
   33         {
   34             candidateNumbers =
   35             (from n in candidateNumbers
   36             where
   37               n <= nextPrime ||
   38               n % nextPrime != 0
   39             select n).ToList();
   40 
   41             nextPrime =
   42                (from p in candidateNumbers
   43                 where p > nextPrime
   44                 select p).First();
   45 
   46         }
   47 
   48         result = candidateNumbers.ToList();
   49 
   50     }
   51 
   52     return result;
   53 }
   54 
Well, it uses LINQ, but it ain't lovely. I ended up refactoring the code in much the same way that the authors did. Primarily by breaking up the long method (Extract Method). The final pass of the method ended up looking like this:
   31 
   32 public int[] GeneratePrimes(int maxNumber)
   33 {
   34     int[] result = new int[] { };
   35     if (maxNumber > 1)
   36     {
   37         InitializeRangeOfNumbers(maxNumber);
   38         InitializeLastNumberToCheck(maxNumber);
   39         int prime = 2;
   40         while (RemainingNumbersContainFactorsOf(prime))
   41         {
   42             RemoveFactorsOf(prime);
   43             prime = NextPrime(prime);
   44         }
   45 
   46         result = _remainingNumbers.ToArray();
   47 
   48     }
   49 
   50     return result;
   51 
   52 }
   53 
The implementation of the methods look like this:
   54 
   55 private void InitializeLastNumberToCheck(int maxNumber)
   56 {
   57     _lastNumberToCheck = Math.Sqrt(maxNumber);
   58 }
   59 
   60 private void InitializeRangeOfNumbers(int maxNumber)
   61 {
   62     _remainingNumbers = Enumerable.Range(2, maxNumber - 1);
   63 }
   64 
   65 private int NextPrime(int currentPrime)
   66 {
   67     return
   68         (from p in _remainingNumbers
   69          where p > currentPrime
   70          select p).First();
   71 }
   72 
   73 private bool RemainingNumbersContainFactorsOf(int prime)
   74 {
   75     return prime <= _lastNumberToCheck;
   76 }
   77 
   78 private void RemoveFactorsOf(int prime)
   79 {
   80     _remainingNumbers =
   81         (from n in _remainingNumbers
   82          where
   83            n <= prime ||
   84            n % prime != 0
   85          select n).ToList();
   86 }
   87 
You might be interested to know that the LINQ implementation is (ever so) slightly faster than the Martin version. Both versions can compute the first 100,000 primes in less than a second. I haven't dug into the reason why. For fun, I decided to implement an algorithm that would fall into the LINQ way a little easier. I came up with this:
   27 
   28 public int[] GeneratePrimes(int maxNumber)
   29 {
   30     int [] result = new int [] { };
   31     if(maxNumber > 1)
   32     {
   33         var primeNumbers =
   34             from n in Enumerable.Range(2, maxNumber - 1)
   35             where n.IsPrime()
   36             select n;
   37 
   38         result = primeNumbers.ToArray();
   39 
   40     }
   41     return result;
   42 }
   43 
The @IsPrime@ method is the trick.
   48 
   49 static class IntExtensions
   50 {
   51     public static bool IsPrime(this int p)
   52     {
   53         bool result = false;
   54         if (p > 1)
   55         {   
   56             IEnumerable<int> testNumbers =
   57                 from n in Enumerable.Range(2, (int)Math.Sqrt(p))
   58                 where 
   59                     p != n && 
   60                     p % n == 0
   61                 select n;
   62             result = testNumbers.Count() == 0;
   63         }
   64         return result;
   65     }
   66 }
   67 
This algorithm might look a little nicer (from a LINQ point of view), but it's tragically slow. Essentially, the code performs some heavy looping for each number in the range being tested. I could probably juice up the prime test a little bit by digging into some of the more advanced algorithms, but for now it was a fun exercise.

Download the Source

Deming was the Brooks of Business

W. Edwards Deming was an incredibly lucid business visionary that understood what really makes business tick. Deming had a holistic understanding of producing a product  from employee, to management, to customer. Through his publications and work with post WWII Japanese industry, he proved that his observations and hypothesis are not only valid but powerful tools for success (e.g., 1977 Ford Pinto vs. 1977 Toyota Corolla). Here is a block quote from wikipedia that explains his philosophy (in a nutshell).

Deming's 14 points

Deming offered fourteen key principles for management for transforming business effectiveness. In summary:

  1. Create constancy of purpose toward improvement of a product and service with a plan to become competitive and stay in business. Decide to whom top management is responsible.
  2. Adopt the new philosophy. We are in a new economic age. We can no longer live with commonly accepted levels of delays, mistakes, defective materials, and defective workmanship.
  3. Cease dependence on mass inspection. Require, instead, statistical evidence that quality is built in. (prevent defects instead of detect defects.)
  4. End of the practice of awarding business on the basis of price tag. Instead, depend on meaningful measures of quality along with price. Eliminate suppliers that cannot qualify with statistical evidence of quality.
  5. Find Problems. It is a management’s job to work continually on the system (design, incoming materials, composition of material, maintenance, improvement of machine, training, supervision, retraining)
  6. Institute modern methods of training on the job
  7. The responsibility of the foreman must be to change from sheer numbers to quality… [which] will automatically improve productivity. Management must prepare to take immediate action on reports from the foremen concerning barriers such as inherent defects, machines not maintained, poor tools, and fuzzy operational definitions.
  8. Drive out fear, so that everyone may work effectively for the company.
  9. Break down barriers between departments. People in research, design, sales and production must work as a team to foresee problems of production that may be encountered with various materials and specifications.
  10. Eliminate numerical goals, posters, slogans for the workforce, asking for new levels of productivity without providing methods.
  11. Eliminate work standards that prescribe numerical quotas.
  12. Remove barriers that stand between the hourly worker and his right of pride of workmanship.
  13. Institute a vigorous program of education and retraining.
  14. Create a structure in top management that will push every day on the above 13pts.

Seven Deadly Diseases

The Seven Deadly Diseases:

  1. Lack of constancy of purpose.
  2. Emphasis on short-term profits.
  3. Evaluation by performance, merit rating, or annual review of performance.
  4. Mobility of management.
  5. Running a company on visible figures alone.
  6. Excessive medical costs.
  7. Excessive costs of warranty, fueled by lawyers who work for contingency fees.

What is surprising is how relevant this work still is. What is equally surprising is how many companies simply don't learn from history and the collective experience. What do they teach in business school anyway? I can recall a point in time where a certain company stopped doing most of the 14 points and caught in earnest most of the seven deadly diseases. That point in time was the beginning of an all too certain end.

I'll admit that I have no right to cast stones. The software industry has long had our own version of Deming in Brooks. I can't tell you how many times management has attempted a full-on interview-hire cycle to try and pull in features and schedules. What do they teach in Computer Science anyway? I've always wanted to structure a software team around Brooks concept of the "surgical team". I've never seen it done, but it sounds like it would work.

Why did I write this post? I've recently been asked my opinion, "What would you do if you were CEO/CIO/CxO?". I think it surprises the people asking that I have a long list of answers. I'm also trying to satisfy a condition of my employment in the form a lengthy essay that flies square in the face of Disease #3 -- and it just seems that something isn't quite right.

Featured Developer in Community Credit


I am one of the featured developers in Community Credit!

Community Credit is a great site devoted to rewarding those who contribute to the .net community. I am truly honored. Thanks Dave

The most embarrassing thing is the quick head shot that I put together. Check out this mug:

This truly shows off my l337 PhotoShop skillz, as I ripped my head out of a random Christmas photo and put it on a neutral background (please note the sarcasm).

My First CodeProject Article: LINQ to Life

One Down, n to Go

I posted my first article to code project today. I decided that it would be fun to write Conway's Game of Life using LINQ. I wanted to stress how query expressions, lambda expressions, extension methods, and the rest of the .net 3.5 enhancements make code more expressive, readable, and easier to understand. Please click through the image, and take a look.

The First Time is Always the Hardest

I had a little trouble knowing what's what in their article submission editor. I even got this screencast:

 ...to work fine in the preview screen. No dice on the actuall submission. I had to punt back to providing a link to the screen cast stie.

I'm Amazed

I hadn't even finished all the cleanup: figuring out why my download link wasn't showing up, removing that last typo, punting on the embedded screen cast, when I noticed that the article had been read 473 times, had 2 votes (5/5), and a positive comment.

Wow! Certainly, that's humbling, and I'm very gratefull for the positive feedback. I'm just amazed people have read my work :)