Techno Fattie

Wednesday, February 1, 2012

Whine Less... Code More

Developers are a whiny bunch.

Today I was reading one of Scott Hanselman's latest posts on some improvements being made in WebForms, and was pretty amazed at how generally whiny the comments were.

You could read all the comments, but they can pretty much be broken down into 3 categories of whiny trolls.

The Hater

Dear Scott,

You suck! WebForms sucks! Microsoft sucks! And pretty much every technology they produce is total garbage. I still program using the MS stack of course... cause you know... I'd rather complain than learn a new technology.

The Righteous One

Dear Scott,

How can you even look at yourself in the mirror after writing such filthy code. I realize this is just a blog post... meant to be a simple demonstration of a new feature, but how dare you not follow all 5 of the SOLID principles, complete with a full suite of unit and integration tests (written first of course). You didn't even use an IoC!!!! And you call yourself a programmer! 

All .Net developers are pretty much worthless, incompetent boobs... except for me of course. I would write a better example myself, but I'm too busy telling people like you how crappy a programmer they are :P

The Hipster

Dear Scott,

Whoa dude! WebForms is so primitive man. Only old people and corporate shills program in WebForms. Everybody knows that MVC is what all the cool kids are using. That internal corporate app I wrote is like... blowing minds... all five of them. 

Besides, everybody knows that WebForms is way too much abstraction, and the ViewState, oh man was it terrible. I never knew what the ViewState was for, but I know it was bad! With MVC I can get down to bare metal baby! I still don't know what a Handler or Module is, and I never really touch the form collection or HttpContext... but it's so much less abstract than WebForms.

So, to all you whiny programmers out there, I have a some people you should meet. I know you know these people. You probably troll their blogs regularly.


Bob Martin, Michael Feathers, Ron Jeffries and Martin Fowler were doing awesome things while you were still drinking from a sippy cup.

David Heinemeier Hansson liked Ruby and needed a web framework. So he wrote one.

Rob Conery didn't like big heavy ORM's so he wrote a tiny one. He also created a startup using ASP.Net MVC... and then rewrote it using RoR just because he could.

Phil Haack helped bring MVC to the world of ASP.Net

Jeremy Miller and Oren Eini wake up in the morning and pee new frameworks that are awesome.

Joel Spolsky's company wrote an awesome bug tracker in classic asp. ASP FOR GOODNESS SAKE!


Jeff Atwood wrote Stackoverflow when MVC was still in beta.

Damien Edwards continues to rock out ASP.Net

Glenn Block is infusing WCF with web enabled awesome sauce.

John Resig made the entire web take Javascript seriously.

Steve Sanderson brought MVVM to web apps using Knockout.js

David Fowler is making realtime web stupid easy with SignalR

And last but not least... Scott Hanselman was pimping ASP.Net and make it look good back when it was still 1.0


So what do they all have in common?

They can't hear you over the sound of how awesome they are!


Not all of them work on the same technology stack, but all of them have been consistently awesome at what they do regardless of the technology they were using.


Technologies do not make awesome applications. Awesome people make awesome applications.

Stop spending so much time and effort complaining and start doing something amazing... right now!

Less Whine! More Awesome!

Monday, January 30, 2012

It's The Principal...

In ancient times... at least according to web standards, I wrote a couple of posts about unit testing with declarative security attributes. It turns out that while using declarative security is pretty awesome, it's clear nobody was thinking about people doing TDD :(

Getting around this was easy enough by simply overriding the Principal using the built in GenericPrincipal and GenericIdentity classes. We even refactored the security setup code into the Initialize method for our unit tests. However, we still had to think about security for every test class!

I can tell you right now that that is a big fat suck! I don't want to see any security related code in my unit test because I'm not testing security right now! What I really want is for my test to look like this and just work.

[TestMethod]
public void ShouldGetSuperSecretFromAgent()
{
    var agent = new SecretAgent();

    //This line will esplode!!!
    var secret = agent.GetSuperSecretStuff();

    Assert.IsNotNull(secret);
}

Fortunately, we still have one last trick up our sleeve that we can use to solve our problem once and for all. Writing a custom implementation of IPrincipal and IIdentity. This is so braindead simple, that I'm not even going to explain it... just show you the code.

public class StubPrincipal: IPrincipal, IIdentity
{
    public StubPrincipal(String name = "TestUser", Boolean isAuthenticated = true, String authenticationType = "Fake")
    {
        Name = name;
        IsAuthenticated = isAuthenticated;
        AuthenticationType = authenticationType;
    }

    //IPrincipal Members
    public IIdentity Identity
    {
        get { return this; }
    }

    public bool IsInRole(string role)
    {
        return true;
    }

    //IIdentity Members
    public string AuthenticationType { get; set; }

    public bool IsAuthenticated { get; set; }

    public string Name { get; set; }
}

This still leaves the business of wiring it all up. Since the whole point of this refactoring was to not have to worry about doing this for every test!

All your base class are belong to us!

The simplest approach I can think of is to create a base class that will wire up your custom StubPrincipal object in the constructor, and then derive all your test classes from it. Again, this is so braindead simple... just look at the code.

public class SecurityEnabledTest
{
    protected StubPrincipal Principal = new StubPrincipal();

    public SecurityEnabledTest()
    {
        Thread.CurrentPrincipal = Principal;
    }
}

And now our goal above is reached with one tiny modification.

[TestClass]
public class SecretAgentBehavior_UsingBaseClass: SecurityEnabledTest
{
    [TestMethod]
    [Description("Test relying on base class to set principal")]
    public void ShouldGetSuperSecretFromAgent()
    {
        var agent = new SecretAgent();

        //It works... WOOT!
        var secret = agent.GetSuperSecretStuff();

        Assert.IsNotNull(secret);
    }
}

Voila! Now you can go on your merry little way and focus on the actual method behavior instead of the security meta-data.

But Wait! There is even more awesome!

If you are thinking to yourself "Ok, that is great dude, but what if I actually want to test MY FREAKING SECURITY!"

I've got you covered. Here is a slightly more robust Principal object that will give you a lot more control over how it behaves, which should cover any testing scenario you can think of. It allows you to add roles, and has three modes of operation:
  1. Always Return True
  2. Whitelist
    1. This is how a normal principal operates. If the role is in the list, then you get access.
  3. Blacklist
    1. This works opposite to a normal principal. If the role is in the list, then you get denied access. This is useful for when there are multiple roles needed to perform an action (think nested calls), and you want to see how your code behaves when the user doesn't have one of them.
In the end I hope this helps unit testing efforts, and maybe demystifies the Principal/Identity objects a little bit. You can even use these same techniques to write your own custom security Principal for actual production uses. The concepts are identical.

Cheers,
Josh

Wednesday, October 5, 2011

Recursive Validation Using DataAnnotations

I saw a post on Stackoverflow today that piqued my interest.

The title really says it all:


DataAnnotations: Recursively validating an entire object graph


Using the DataAnnotations to do validation on object can be extermely useful, but there are many limitations to the existing code base. One such limitations, as Neil has discovered, is that the out of the box validator doesn't recursively apply validation.

Indeed looking at the MSDN docs for TryValidateObject state clearly that:
This method evaluates each ValidationAttribute instance that is attached to the object type. It also checks whether each property that is marked with RequiredAttribute is provided. It does not recursively validate the property values of the object.
 So how do we get around this? Well... there are several examples of people using reflection and LINQ to recurse over the individual properties and validate each one of them. Yuck!

I'm a big fan of working with the framework if at all possible, so I decided to implement a quick solution that fits nicely into the DataAnnotations world.

The idea is to simply tell the validation framework that you would like to do a little extra with some particular property. I want to be able to be able to opt in certain properties to further validation if necessary. Something like this.

public class Person {
  [Required]
  public String Name { get; set; }

  [Required, ValidateObject]
  public Address Address { get; set; }
}

Address could have it's own set of validation attributes, and I want to also validate those along with my Person type. Turns out this is pretty simple to do using existing framework components.


Let me just show you the code, and then I can explain what is going on.

public class ValidateObjectAttribute: ValidationAttribute {
   protected override ValidationResult IsValid(object value, ValidationContext validationContext) {
      var results = new List<ValidationResult>();
      var context = new ValidationContext(value, null, null);
         
      Validator.TryValidateObject(value, context, results, true);

      if (results.Count != 0) {
         var compositeResults = new CompositeValidationResult(String.Format("Validation for {0} failed!", validationContext.DisplayName));
         results.ForEach(compositeResults.AddResult);

         return compositeResults;
      }

      return ValidationResult.Success;
   }
}

public class CompositeValidationResult: ValidationResult {
   private readonly List<ValidationResult> _results = new List<ValidationResult>();

   public IEnumerable<ValidationResult> Results {
      get {
         return _results;
      }
   }

   public CompositeValidationResult(string errorMessage) : base(errorMessage) {}
   public CompositeValidationResult(string errorMessage, IEnumerable<string> memberNames) : base(errorMessage, memberNames) {}
   protected CompositeValidationResult(ValidationResult validationResult) : base(validationResult) {}

   public void AddResult(ValidationResult validationResult) {
      _results.Add(validationResult);
   }
}


The idea here is pretty simple. Any property decorated with the ValidateObjectAttribute will be validated as a whole, and the results aggregated together. The processing is as follows:

  1. Create a new ValidationContext using the current value as the target
  2. Attempt to validate that object, being sure to include all properties
  3. If there are any ValidationResults, store them and return as a single aggregate failure
  4. If there are no results, return ValidationResults.Success
Putting it all together, imagine for a minute that we had the following class structure:

public class Person {
  [Required]
  public String Name { get; set; }

  [Required, ValidateObject]
  public Address Address { get; set; }
}

public class Address {
  [Required]
  public String Street1 { get; set; }

  public String Street2 { get; set; }

  [Required]
  public String City { get; set; }

  [Required]
  public String State { get; set; }

  [Required, ValidateObject]
  public ZipCode Zip { get; set; }
}

public class ZipCode {
  [Required]
  public String PrimaryCode { get; set; }

  public String SubCode { get; set; }
}

We can simply make use of existing methods and validate the entire object graph. Also, making use of our CompositeValidationResult, we should be able to drill into each individual failure in context.


static void Main(string[] args) {
   var person = new Person {
      Address = new Address {
         City = "Awesome Town",
         State = "TN",
         Zip = new ZipCode()
      },
      Name = "Josh"
   };

   var context = new ValidationContext(person, null, null);
   var results = new List<ValidationResult>();

   Validator.TryValidateObject(person, context, results, true);

   PrintResults(results, 0);

   Console.ReadKey();
}

private static void PrintResults(IEnumerable<ValidationResult> results, Int32 indentationLevel) {
   foreach (var validationResult in results) {
      SetIndentation(indentationLevel);

      Console.WriteLine(validationResult.ErrorMessage);
      Console.WriteLine();

      if (validationResult is CompositeValidationResult) {
         PrintResults(((CompositeValidationResult)validationResult).Results, indentationLevel + 1);
      }
   }
}

private static void SetIndentation(int indentationLevel) {
   Console.CursorLeft = indentationLevel * 4;
}

Running the above should result in the following output:



Well, there you have it. A pretty simple solution that has the advantage of working alongside the Validation framework instead of against it!

Friday, September 23, 2011

Solving Ayende's Tax Woes

Oren Eini (a.k.a. Ayende Rahien) is going through the joy that is trying to find good developers. The other day he posted some sample code that an interviewee had turned in to a coding challenge. The results weren't pretty!

The problem involves calculating a persons taxes based on a set of tax brackets. 

It makes a great interview question because the problem is short enough to get done in an hour or so, but tricky enough to require some thought. Here are the specs as posted by Ayende:

Israel's Tax Brackets:

Tax Rate
Up to 5,07010%
5,071 up to 8,66014%
8,661 up to 14,07023%
14,071 up to 21,24030%
21,241 up to 40,23033%
Higher than 40,23045%

Acceptance Tests: 
  • 5,000 –> 500
  • 5,800 –> 609.2
  • 9,000 –> 1087.8
  • 15,000 –> 2532.9
  • 50,000 –> 15,068.1
Having not yet read the other comments or solutions, I thought it would be fun to take a crack at writing my own solution to the problem.

I am a huge proponent of unit testing, and more specifically Test Driven Development. Since we have a nice set of acceptance tests, it is pretty easy to get those into code.

I started with the simplest of tests I could think of.

[TestMethod]
public void ShouldCalculateTotalTaxesToBeZero() {
   var effectiveTax = new EffectiveTax();

   var result = effectiveTax.CalculateTaxes(0);

   Assert.AreEqual(0, result);
}

Which led me to create this simple implementation.

public class EffectiveTax 
{      
   public Decimal CalculateTaxes(Decimal grossIncome) 
   {
      return 0;
   }
}

Alright, so not very useful. But the tests pass!

Now we need to be able to expand on this a bit and add a tax bracket in the mix. A tax bracket has some lower-bound, and a rate. We can write another pretty simple test for that.

[TestMethod]
public void ShouldCalculateTaxesUsingSingleTaxBracket() {
   var effectiveTax = new EffectiveTax();
   effectiveTax.AddTaxBracket(lowerBound: 0, taxRate: 0.1M);

   Assert.AreEqual(0, effectiveTax.CalculateTaxes(0));
   Assert.AreEqual(100, effectiveTax.CalculateTaxes(1000));
   Assert.AreEqual(1000, effectiveTax.CalculateTaxes(10000));
}

(Note: The use of named parameters is to aid in the design process. Since I wrote the code before the method existed, the IDE can infer the parameter names and automatically generate a signature for me. Also, it helps to clarify what is going on in the test.)

We Add just enough code to get the tests passing, which is certainly more useful than the previous iteration, but far from complete. Some might object to my introducing a TaxBracket type into the mix so early, but writing just enough code doesn't preclude one from writing clean code. The extra type helps to tidy things up, and makes future refactoring work easier with little extra work.

public class EffectiveTax {

   private TaxBracket _taxBracket;

   public Decimal CalculateTaxes(Decimal grossIncome) {
      return grossIncome * _taxBracket.TaxRate;
   }

   public void AddTaxBracket(Decimal lowerBound, Decimal taxRate) {
      _taxBracket = new TaxBracket {
         LowerBound = lowerBound,
         TaxRate = taxRate
      };
   }

   private class TaxBracket {
      internal Decimal LowerBound { get; set; }
      internal Decimal TaxRate { get; set; }
   }
}

This rev is also incomplete since it doesn't take the lower-bound into account. So... we write another test case to cover that scenario.

[TestMethod]
public void ShouldCalculateOnlyTaxableIncome() {
   var effectiveTax = new EffectiveTax();
   effectiveTax.AddTaxBracket(lowerBound: 5000, taxRate: 0.1M);

   Assert.AreEqual(0, effectiveTax.CalculateTaxes(0));
   Assert.AreEqual(0, effectiveTax.CalculateTaxes(4999));
   Assert.AreEqual(0, effectiveTax.CalculateTaxes(5000));
   Assert.AreEqual(10, effectiveTax.CalculateTaxes(5100));
}

A minor change to the code, and now we can effectively handle a single flat tax, with an optional poverty line.

public Decimal CalculateTaxes(Decimal grossIncome) {
   var effectiveTax = 0.0M;
         
   if (grossIncome > _taxBracket.LowerBound) {
      var taxableIncome = grossIncome - _taxBracket.LowerBound;
            
      effectiveTax = taxableIncome * _taxBracket.TaxRate;
   }

   return effectiveTax;
}

However, what we want is a system with multiple tax brackets. Now we get to the testing scenario that was previously laid out for us. We can easily translate those tables into a test.

[TestMethod]
public void ShouldCalculateTaxUsingIsraelsTaxBrackets() {
   var effectiveTax = new EffectiveTax();
   effectiveTax.AddTaxBracket(lowerBound: 0, taxRate: 0.1M);
   effectiveTax.AddTaxBracket(lowerBound: 5070, taxRate: 0.14M);
   effectiveTax.AddTaxBracket(lowerBound: 8660, taxRate: 0.23M);
   effectiveTax.AddTaxBracket(lowerBound: 14070, taxRate: 0.30M);
   effectiveTax.AddTaxBracket(lowerBound: 21240, taxRate: 0.33M);
   effectiveTax.AddTaxBracket(lowerBound: 40230, taxRate: 0.45M);

   Assert.AreEqual(0, effectiveTax.CalculateTaxes(0));
   Assert.AreEqual(500, effectiveTax.CalculateTaxes(5000));
   Assert.AreEqual(609.2M, effectiveTax.CalculateTaxes(5800));
   Assert.AreEqual(1087.8M, effectiveTax.CalculateTaxes(9000));
   Assert.AreEqual(2532.9M, effectiveTax.CalculateTaxes(15000));
   Assert.AreEqual(15068.1M, effectiveTax.CalculateTaxes(50000));
}

It was obvious that we needed some sort of collection to hold the TaxBrackets, and that we would need to loop over them to calculate the effective tax. The decision to reverse the loop, greatly simplifies the processing.

Essentially we start with the highest amount of money that has a tax rate, and chop off that amount from the total amount remaining, taxing each chunk as we go and adding it to the total.

public class EffectiveTax {

   private readonly List _taxBrackets = new List();

   public Decimal CalculateTaxes(Decimal grossIncome) {
      var effectiveTax = 0.0M;
      var incomeLeftToTax = grossIncome;

      for (var i = (_taxBrackets.Count - 1); i >= 0; i--) {
         var taxBracket = _taxBrackets[i];

         if (incomeLeftToTax > taxBracket.LowerBound) {
            var taxableIncome = incomeLeftToTax - taxBracket.LowerBound;

            incomeLeftToTax -= taxableIncome;
            effectiveTax += taxableIncome * taxBracket.TaxRate;
         }
      }

      return effectiveTax;
   }

   public void AddTaxBracket(Decimal lowerBound, Decimal taxRate) {
      _taxBrackets.Add(new TaxBracket {
         LowerBound = lowerBound,
         TaxRate = taxRate
      });
   }

   private class TaxBracket {
      internal Decimal LowerBound { get; set; }
      internal Decimal TaxRate { get; set; }
   }
}

Finally we need to address a massive assumption with the current implementation. Mainly, that the tax brackets are in ascending order based on their lower bound. That is a pretty big assumption, and one that could lead to nasty bugs in the future.

For our last test, we mix up the ordering of the tax brackets and make sure everything still works.

[TestMethod]
public void ShouldCorrectlyOrderTaxBrackets() {
   var effectiveTax = new EffectiveTax();
   effectiveTax.AddTaxBracket(lowerBound: 40230, taxRate: 0.45M);
   effectiveTax.AddTaxBracket(lowerBound: 14070, taxRate: 0.30M);
   effectiveTax.AddTaxBracket(lowerBound: 0, taxRate: 0.1M);
   effectiveTax.AddTaxBracket(lowerBound: 8660, taxRate: 0.23M);
   effectiveTax.AddTaxBracket(lowerBound: 21240, taxRate: 0.33M);
   effectiveTax.AddTaxBracket(lowerBound: 5070, taxRate: 0.14M);

   Assert.AreEqual(0, effectiveTax.CalculateTaxes(0));
   Assert.AreEqual(500, effectiveTax.CalculateTaxes(5000));
   Assert.AreEqual(609.2M, effectiveTax.CalculateTaxes(5800));
   Assert.AreEqual(1087.8M, effectiveTax.CalculateTaxes(9000));
   Assert.AreEqual(2532.9M, effectiveTax.CalculateTaxes(15000));
   Assert.AreEqual(15068.1M, effectiveTax.CalculateTaxes(50000));
}

Clearly this fails miserably so with a little adjustment to our method, we can ensure the ordering is correct before we start processing. The added benefit is that the code is now even more expressive than the explicit for loop from the previous iteration.

public Decimal CalculateTaxes(Decimal grossIncome) {
   var effectiveTax = 0.0M;
   var incomeLeftToTax = grossIncome;

   var orderedBrackets = _taxBrackets.OrderByDescending(tb => tb.LowerBound);

   foreach (var taxBracket in orderedBrackets) {
      if (incomeLeftToTax > taxBracket.LowerBound) {
         var taxableIncome = incomeLeftToTax - taxBracket.LowerBound;

         incomeLeftToTax -= taxableIncome;
         effectiveTax += taxableIncome * taxBracket.TaxRate;
      }
   }

   return effectiveTax;
}

Now, there are some clear omissions here, like checking for negative values, but I think it accomplished the spirit of the question.

As I stated previously I haven't read any of the other solutions, so this may be an exact duplicate. Also, there may be much more elegant solutions to this problem, but as usual TDD has lead to something that is neat, clean, and well tested :)



Friday, April 8, 2011

Unit Testing and Declarative Security, Part 2


In a previous post I talked about using the PrincipalPermissionAttribute to achieve some last resort security that was tightly integrated into the framework.

The nice thing about this approach is that you don't have to worry about some other programmer forgetting to check security before calling a method in your API. The bad news is because of the tight integration, Unit Testing becomes a little tricker. Since there is not a security service to mock, we have to get our hands dirty and actually set the Principal so the method calls won't fail at runtime.

We got around this last time by using GenericPrincipal and GenericIdentity, two classes provided for us by the FCL writers. However, the added code distracts from the test we really want to write. Lets look at that example again.

[TestMethod]
public void ShouldGetSuperSecretFromAgentUsingGenericPrincipalAndIdentity()
{
    var awesomeSauce = new GenericPrincipal(
            new GenericIdentity("jbond"), new[] { "007" }
        );

    Thread.CurrentPrincipal = awesomeSauce;

    var agent = new SecretAgent();

    var secret = agent.GetSuperSecretStuff();

    Assert.IsNotNull(secret);
}

So this isn't terrible right now, but it is code that will have to be repeated over and over again for each test that calls that method. In this scenario we really aren't interested in testing the security, but rather the guts of the method. We want to test security, but not in this method. Ok, let's start DRYing up this code.

The easiest and simplest choice would be to just refactor out the code into a method, and then call it before our test. This is simple enough to do.

[TestMethod]
public void ShouldGetSuperSecretFromAgentUsingGenericPrincipalAndIdentity()
{
    SetUserRoles("007");

    var agent = new SecretAgent();

    var secret = agent.GetSuperSecretStuff();

    Assert.IsNotNull(secret);
}

private void SetUserRoles(params String[] roles)
{
    if(roles == null || roles.Length == 0) return;

    var principal = new GenericPrincipal(
            new GenericIdentity("jbond"), roles
        );

    Thread.CurrentPrincipal = principal;
}

That is slightly better, and gives a much better indication of what is going on when looking at the test, but I still don't like it for a couple of reasons:

  • The call to SetUserRoles still takes away from the purpose of the test. Remember this test isn't about security, but the behavior of the method itself. Everytime you look at this test you will first have to figure out why the security is there, and this increases friction and slows down the RED/GREEN/REFACTOR cycle.
  • Code is still repeated because everytime we test a path through any method with security we will have to make a call to SetUserRoles, and that sucks. Any code that can be copied and pasted is worth your time to refactor.

I really want to get to not thinking about security when I write my tests, so let's see if we can at least do that. Those of you familiar with any of the major Unit Testing Frameworks will know that they all have an attribute that designates one method that will run before every test is run. In MSTest it is the TestInitializeAttribute. We can use that to neatly tuck our security code away into a single method so we don't have to repeat it for every test.


[TestInitialize]
public void Init()
{
    SetUserRoles("007");
}

[TestMethod]
public void ShouldGetSuperSecretFromAgentUsingGenericPrincipalAndIdentity()
{
    var agent = new SecretAgent();

    var secret = agent.GetSuperSecretStuff();

    Assert.IsNotNull(secret);
}

//SetUserRoles Method


Now, this is certainly a lot better than the previous version since we only have to call SetUserRoles in one place. Also, our test method is free from the security clutter so we don't have any mental road blocks while reading the test. However, I am still not very happy with the end result.

Why?

Remember when I said I didn't want to have to think about the security while writing my tests? Well... I still do. Everytime I write a new method in my SUT, I will no doubt add another security attribute to it. Or, I will write a test to cover security, and then add the attribute to make my test pass. Either way, I will have to come back to the Init method and add another role to the list.

Nothing will cripple your unit testing efforts faster than brittle, hard to maintain tests!

So how do we get around this? Ok so I already told you in Part 1 that we could build a custom Principal and Identity in order to achieve the desired results, but I wanted to expound a little on the rationale for actually doing it.

In Part 3 we solve all our problems (I promise!)



Thursday, February 10, 2011

WPF != Fancy Winforms

I'm a big fan of Stackoverflow, and I was just recently looking at this very simple question regarding changing button color. On the surface it seems this would warrant a very simple answer, and indeed Chris' Answer was simple, straightforward and to the point.

However, it feels too much like how I would have done things back in the dark ages of WinForms. There seems to be this misconception that WPF is just a fancier version of the old Win32 standby. (note I am not trying to imply this is what Chris thinks, it merely serves as a convenient backdrop for this post)

But WPF is not even a cousin, or distant relative of WinForms. If WPF saw WinForms in the hallway it would beat him up and take his lunch money from him. Anyway, that is enough of a rant. On with what started out as my original answer to the question, which turned into this epic post...

Original Answer Starts Here:

So Chris' suggestion is pretty straightforward, and it is certainly easier to implement than what I am about to show you ;) However, if you are going to venture into the world of WPF then you need to experience what it has to offer.

In my opinion the two biggest advantages in WPF are:
  1. The power and flexibility of the declarative model
  2. An incredibly rich data binding infrastructure
Granted those are immensely deep topics within WPF, but without at least gaining a minimal understanding of those topics, it will be like driving a Lamborghini around in first gear all the time.

That being said, you can jump to the full solution here, copy and paste it into a clean solution, and play with it for a second. I'll be waiting patiently here to give you a detailed explanation of what is going on.

Ready? Ok then, lets get going.

Lets start with the core logic of the application, your requirements are:
  1. Examine a file on disk
  2. Change the appearance of a button based on content length
  3. Update the appearance of the button when the file changes
Since the appearance of the button is presentation specific, we simply won't worry about that when implementing our core logic. So what we really need to do is monitor the file for changes, and update a local variable with the length of the file, if it exists.

This is a perfect job for a FileSystemWatcher. The file watcher kicks off a thread in the background which utilizes some low level Win32 API's to monitor events on the file system. We can tie into those events via the watcher, and handle them in our application asynchonously.

Creating a new watcher is pretty simple and all we really need to provide is the Path. Here I am simply using the current location of the Executing Assembly for the base path. The second thing you see here is the Filter property. This works just like the filter you would use in the command line.

private FileSystemWatcher _fileWatcher;
private const String FileToWatch = "tempfile.txt";

public void InitializeFileWatcher()
{
    _fileWatcher = new FileSystemWatcher();
    _fileWatcher.Path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
    _fileWatcher.Filter = "*.txt";

    //Snip...
}

Next we want to subscribe to the different types of events available, and tell the watcher to start doing it's thing. In this case our event handler is just a thin wrapper around a simple method that does all the "heavy" lifting. Lastly we call our UpdateFileLength method directly because we need to know what the status of the file is right now, without waiting on an event from our watcher.

public void InitializeFileWatcher()
{
    //Snip...

    _fileWatcher.Created += fileWatcher_Handler;
    _fileWatcher.Changed += fileWatcher_Handler;
    _fileWatcher.Deleted += fileWatcher_Handler;
    _fileWatcher.Renamed += fileWatcher_Handler;

    _fileWatcher.EnableRaisingEvents = true;

    UpdateFileLength(Path.Combine(_fileWatcher.Path, FileToWatch));
}

private void UpdateFileLength(string filePath)
{
    Int64? length = null;

    if (Path.GetFileName(filePath) == FileToWatch)
    {
        var fi = new FileInfo(filePath);

        if (fi.Exists)
            length = fi.Length;
    }

    Dispatcher.Invoke((Action)(
        () => FileContentLength = length)
    );
}

void fileWatcher_Handler(object sender, FileSystemEventArgs e)
{
    UpdateFileLength(e.FullPath);
}

The UpdateFileLength method is pretty simple. It checks to see if the file is the one we are looking for, extracts the length if it exists, and updates a property on our MainWindow. Something that may seem a bit odd however, is the use of the Dispatcher and an anonymous method in order to set that property.

Remember how I said that the FileSystemWatcher kicks off a background thread. Well, technically UpdateFileLength could be getting executed from a different thread than the UI thread. And well... it's a big NO NO to access things in the UI from another thread. Without going into a a lot of detail, the Dispatcher is responsible for scheduling things to happen on the UI thread in WPF. Here we are ensuring that no matter what thread executes this method, that that line will always be executed on the UI thread.

Ok, so the last little bit is our property we use to store the current length of the file we are monitoring, but it is no ordinary property.

public static readonly DependencyProperty FileContentLengthProperty = DependencyProperty.Register(
    "FileContentLength",
    typeof(Int64?),
    typeof(MainWindow),
    new UIPropertyMetadata(null));

public Int64? FileContentLength
{
    get
    {
        return (Int64?)GetValue(FileContentLengthProperty);
    }
    set
    {
        SetValue(FileContentLengthProperty, value);
    }
}

What you are staring at here is known as a DependencyProperty, and they are pretty foundational to how WPF works, so take some time to learn about them. For our purposes, just know that what this provides for us is a way for WPF to monitor changes to our property, which allows for all sorts of fun stuff in the UI.

Now, on to the UI and where the real magic happens. Did you notice we didn't ever reference any buttons or set colors in the code behind? That's because 99% of the time in WPF there is no need to. The declarative model we have in XAML combined with the rich data binding ecosystem in WPF gives us the freedom to finally have true seperation of concerns between presentation and logic.

The first order of business is to set the DataContext on the Window itself so that we can access all of the properties defined in our code behind. Ok there is only one, but we still need it.

DataContext="{Binding RelativeSource={RelativeSource Self}}"

Next we need a button on our window. Ok, nothing special going on here, except that there is no content, no coloring, just a Style property bound to some static resource called "FileBoundButton"



Styles in WPF are another big complex topic, but just know that this isn't anything like CSS. You can set virtually any property on an element via a style, and include declarative triggers to change the appearance based on events, data, or even other elements. This is precisely how we are going to achieve the visual affect you are after and then some!



The style we are using is declared as a static resource on the window itself. You need a name if you want to be able to refer to it later, and using a TargetType of ContentControl instead of a Button means we could reuse this style a lot of different elements, not just a button.

We set the Background property to Green initially, and we also set the Content equal to the value of our FileContentLength property. Then we make use of DataTriggers to alter those settings based on the value of FileContentLength. The syntax of a DataTrigger can be a bit wonky at first, but if you were to spell it out in pseudo-code it would sound something like this:

set the Background property to Green
set the Content to DataContext.FileContentLength

IF the value of DataContext.FileContentLength is NULL
    THEN set the Background property to LightGray AND
         set the Content to "No File!"
ELSE IF the value of DataContext.FileContentLength is 0
    THEN set the Background property to Red

You might be wondering exactly what DataContext this is referring to. Essentially whatever framework element this style happens to be applied to. Because we didn't set the Button's DataContext explicitely it will inherit the DataContext of the Window. But be careful! Where the DataContext comes from isn't always apparent.

Now, if you put all this together and launch the app for the first time you should end up with a small window with a gray button in it that says "No File!"



Without closing the program, navigate to the executing directory of your application "[ProjectFolder]\bin\Debug" and create a new text file named "tempfile.txt" Now you should see the button change color to red and display a "0" since the file is empty.



Open the newly created text file and write something in there. Save the file and again, watch as your button magically changes before your eyes to green, and displaying "N" where N is the number of characters in your text file.



If you actually made it through this whole thing, then you have hopefully been opened up to a whole new world of possibilities by using WPF. Just remember that it is a very, very deep technology and you won't learn it over night. Here are some resources to get you started on your journey though.

The MSDN Walk Through. Heavy reading, but worth it.
Christian Moser's WPF Tutorial Site. Lots of easy to digest samples.
WPF Questions on Stackoverflow



`MainWindow.xaml`:



`MainWindow.xaml.cs`:

public partial class MainWindow : Window
{
    private FileSystemWatcher _fileWatcher;
    private const String FileToWatch = "tempfile.txt";

    public MainWindow()
    {
        InitializeComponent();
            
        InitializeFileWatcher();
    }

    public void InitializeFileWatcher()
    {
        _fileWatcher = new FileSystemWatcher();
        _fileWatcher.Path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        _fileWatcher.Filter = "*.txt";

        _fileWatcher.Created += fileWatcher_Handler;
        _fileWatcher.Changed += fileWatcher_Handler;
        _fileWatcher.Deleted += fileWatcher_Handler;
        _fileWatcher.Renamed += fileWatcher_Handler;

        _fileWatcher.EnableRaisingEvents = true;

        UpdateFileLength(Path.Combine(_fileWatcher.Path, FileToWatch));
    }

    private void UpdateFileLength(string filePath)
    {
        Int64? length = null;

        if (Path.GetFileName(filePath) == FileToWatch)
        {
            var fi = new FileInfo(filePath);

            if (fi.Exists)
                length = fi.Length;
        }

        Dispatcher.Invoke((Action)(() => FileContentLength = length));
    }

    void fileWatcher_Handler(object sender, FileSystemEventArgs e)
    {
        UpdateFileLength(e.FullPath);
    }

    public Int64? FileContentLength
    {
        get
        {
            return (Int64?)GetValue(FileContentLengthProperty);
        }
        set
        {
            SetValue(FileContentLengthProperty, value);
        }
    }

    public static readonly DependencyProperty FileContentLengthProperty = DependencyProperty.Register(
        "FileContentLength",
        typeof(Int64?),
        typeof(MainWindow),
        new UIPropertyMetadata(null));
}

Wednesday, February 9, 2011

Unit Testing and Declarative Security, Part 1


Security is hard. If you think it isn't your software is probably just waiting to be exploited by this guy:



Knowing this, the guys who put together the .Net framework gave us a pretty brain-dead approach to adding security declaratively1 to our code using the PrincipalPermissionAttribute. Securing a method call becomes trivial this way.

[PrincipalPermission(SecurityAction.Demand, Authenticated = true, Role = "007")]
public Secret GetSuperSecretStuff(){
    return Vault.SuperSecret;
}

Anybody who calls this method will have to be operating under a security context that is both authenticated and a member of the "007" role. However, calling this method without meeting the requirements will throw a big fat Exception. This can make unit testing a bit tricky since you most likely will not have the proper credentials.

For instance suppose the above method were defined on a SecretAgent type in my project and I wanted to write a unit test for it:

[TestMethod]
public void ShouldGetSuperSecretFromAgent()
{
    var agent = new SecretAgent();

    var secret = agent.GetSuperSecretStuff();

    Assert.IsNotNull(secret);
}

Running this code will result in a big fat exception, and your test output will read:

Test method TechnoFattie.Lib.Tests.SecretAgentBehavior.ShouldGetSuperSecretFromAgent threw exception:
System.Security.SecurityException: Request for principal permission failed.

Bummer :(

Getting around this is pretty easy though if you understand how security works in the .Net framework.

Most security in .Net is centered around checking the Principal on the currently executing thread to see if it contains a specific role, and using the PrincipalPermissionAttribute is no exception.

You could think of using security declared in this way as having wrapped every call to GetSuperSecretStuff like this:

if(Thread.CurrentPrincipal.IsInRole("007")){
    var secret = GetSuperSecretStuff();
}
else{
    throw new SecurityException("Request for principal permission failed.");
}

What we need is a way to completely control the Principal. Fortunately for us, replacing the principal is as simple as setting a property. You can assign any principal you want to Thread.Current.Principal so long as it implements the IPrincipal interface.

If we look the IPrincipal interface, we will notice it is pretty darn simple:

public interface IPrincipal
{
    IIdentity Identity { get; }
    bool IsInRole(string role);
}

You will also notice that it contains an Identity property, another very simple interface:

public interface IIdentity
{
    string AuthenticationType { get; }
    bool IsAuthenticated { get; }
    string Name { get; }
}

We could implement our own classes here and use them, but I generally prefer the path of laziness. And wouldn't you know it, the hard working guys at Microsoft decided they would spare us the grueling work of implementing three entire properties and one method. Having pity on the lesser developers like myself, they gave us...

GenericPrincipal and GenericIdentity

Standing on the shoulders of these giants we can rewrite our test method to take advantage of the no doubt hundreds of man hours required to not only implement these classes, but to carefully name them as well.

[TestMethod]
public void ShouldGetSuperSecretFromAgentUsingGenericPrincipalAndIdentity()
{
    var awesomeSauce = new GenericPrincipal(
            new GenericIdentity("jbond"), new[] { "007" }
        );

    Thread.CurrentPrincipal = awesomeSauce;

    var agent = new SecretAgent();

    var secret = agent.GetSuperSecretStuff();

    Assert.IsNotNull(secret);
}

Now our test will happily pass, and life is good once again. Security can seem like a somewhat mystical thing in .Net, but as you can see the underlying mechanics are pretty simple. In the next installment I am actually going to implement a custom Principal type in order to be able to test more complicated security scenarios, and to reduce the amount of code needed to ease maintenance.

1. Don't mistake this approach for a real security solution however. Ideally you should have already checked the user's credentials before hand and the method would never get called. This method is really only good as a fail-safe.