# Friday, September 17, 2010

Earlier this week I got into a bit of spat with a couple of Tweeps on Twitter.  It started with someone I follow and respect re-tweeting something someone tweeted about him which basically said the tools which he is associated with aid developers in creating bad design.  I responded to this tweet in support of this person whom I respect by saying…

Tools don’t do bad design.  Bad developers do bad design.

Immediately after tweeting this I got multiple reply’s stating that just because you do bad design or write bad code you are not necessarily a bad developer. 

To be blunt…this confused the hell out of me.  If you knowingly create a bad design or write bad code how can you be a good developer?  I guess the key word in that previous statement is *knowingly*.  But if you don’t know what good design/code is in my book you can’t be a good developer.

Don’t get me wrong.  We have all been in the position when due to forces outside of our control we have been forced to write imperfect code or create a less than perfect design.  To me this is one place where you can quantifiably determine the good developer from the bad developer.  A good developer, when writing imperfect code due to factors outside of there control, will do one or more of the following:

  1. Get upset because they know they are writing less than perfect code/design.
  2. Leave a comment stating why the code/design was done in this factor.
  3. Add a ToDo for refactoring later.
  4. Will do the imperfect code/design in such a way that the refactoring effort will require less effort.

This argument of writing bad code does not a bad developer make really rattles me.  That is exactly what it does!

OK…Let me have it!

posted on Friday, September 17, 2010 8:58:51 AM (Central Daylight Time, UTC-05:00)  #    Comments [1]
# Friday, September 10, 2010

In the past 10 years I have gone from being an intern doing VBA in Access to architecting and coding enterprise level systems with some of the coolest technologies and methodologies.  I have learned so much, and have had a great time doing it.  Sounds perfect right…but not for me…I want more.  Up to this point, for the most part, I have done all this in a bubble.  Until recently I haven’t been overly involved in the development community and today I am officially declaring the end of that.

I have recently accepted a position with Skyline Technologies.  I am very excited about the opportunity of bringing my knowledge and experience to the group at Skyline.  I am going to use this new start as a spring board to getting more involved in the development community locally and beyond.

What really inspired me though was listing to John Sheehan on Rob Conery’s new podcast This Developer’s Life.  If you haven’t started listening to This Developer’s Life yet…do it…now!  In episode 1.0.2: Fame and Notoriety Rob talks to John Sheehan and Scott Hanselman about fame and how it relates to their careers.  Of course Scott was great, and hilarious, as usual but what I really enjoyed was John’s story.

In one particular part of the interview John details a point in his life when he decided to “raise his profile” and details what his goals where and how he was going to do it.  To me this sounded like a great starting point and what better to add that extra motivation than making it public! :)

Raising My Profile – a 12 month plan

  1. One substantial blog post per week.
  2. Speak at at least 6 user group meetings or conferences.
  3. Contribute to one or more open source projects.
  4. Raise my Twitter follower count to at least 250 legitimate followers.
  5. Become an MVP

So that’s my plan…and we will see how it goes!

posted on Friday, September 10, 2010 5:30:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [0]

* Download Complete Source Code

In my previous post I covered doing automated user interface testing of a WPF application using Iron Ruby and Cucumber.  The reason I was drawn to this path was my current interest in Ruby, Rails, and BDD.  What made Bewildr such a draw for me, other than writing my tests in IronRuby, was the fact that I can use with Cucumber and have a truly human-readable natural language test.

  1. Scenario: The Log On window should be displayed on application start
  2.     Given I ensure that there are no instances of "CompositeAppPoc.Shell.exe" running
  3.     When I start "C:\\MyCompositeAppPoc.Shell.exe"
  4.     Then 1 window is displayed with name "Log On"
  5.       And Terminate the app

Again, because of the learning curve and the fact that I would be introducing a completely new programming language, and let’s face it a completely new way of thinking, into a corporate environment that I will not be around to support long-term I had to pursue a more conventional solution, which led me to White.

White is an automated UI testing framework similar to Bewildr in that they both rely on the MS UI Automation Framework to hook and manipulate the user interface.  What makes White a better choice given my current situation is that from a programmers perspective it is implemented and reads exactly like the standard .NET test frameworks.

  1. [TestMethod]
  2. public void OnApplicationStart_TheLogOnWindow_ShouldBeDisplayed() {
  3.     //Act
  4.     Window window = _app.GetWindow("Log On");
  5.     //Assert
  6.     window.ShouldNotBeNull();
  7. }

Take a look at the video clip below to see what running a White test looks like.

Getting up and running with White is very easy.  Other than downloading the binaries from CodePlex all you need is a tool like UISpy to help you dig deep into how the UI elements are rendered.

At the highest level White operates on the concepts of Application and Windows.  Application being the application you are testing and Windows being the main surface of the application.  As a best practice I would recommend spinning up the application, retrieving your window(s) and killing your application as part of test setup and teardown.

  1. #region Private Fields
  2.  
  3. private Application _app;
  4. private Window _window;
  5.  
  6. #endregion
  7.  
  8. #region Setup & Tear Down
  9.  
  10. [TestInitialize]
  11. public void MyTestInitialize() {
  12.     _app = Application.Launch(@"c:\pathtomyapp\myapp.exe");
  13.     _window = _app.GetWindow("MyWindow");
  14. }
  15.  
  16. [TestCleanup]
  17. public void MyTestCleanup() {
  18.     _app.Kill();
  19. }
  20.  
  21. #endregion

With all that in place let’s walk through setting up a couple tests.

The first thing I want to test is that when my application spins up for the first time the Log On window is displayed.  Because this is an Application level test I am going to put it in a test class called ApplicationTests.  I will use the practice of spinning up the app and killing it as I described above.  My test will simply attempt to retrieve a window with title “Log On” and make sure it is not null.

  1. [TestClass]
  2. public class ApplicationTests {
  3.     #region Private Fields
  4.  
  5.     private Application _app;
  6.  
  7.     #endregion
  8.  
  9.     #region Setup & Tear Down
  10.  
  11.     [TestInitialize]
  12.     public void MyTestInitialize() {
  13.         _app = Application.Launch(
  14.         @"c:\wpf\compositeapppoc\compositeapppoc.shell\compositeapppoc.shell\bin\debug\compositeapppoc.shell.exe");
  15.     }
  16.  
  17.     [TestCleanup]
  18.     public void MyTestCleanup() {
  19.         _app.Kill();
  20.     }
  21.  
  22.     #endregion
  23.  
  24.     [TestMethod]
  25.     public void OnApplicationStart_TheLogOnWindow_ShouldBeDisplayed() {
  26.         //Act
  27.         Window window = _app.GetWindow("Log On");
  28.         //Assert
  29.         window.ShouldNotBeNull();
  30.     }
  31. }

My next test is going to be to make sure that when I enter an invalid username and password and click the log on button a message is displayed telling me my credentials are not valid.  Because this test is specific to the Log On window I am going to create a new test class called LogOnTests.  I will use the practice of spinning up the app, getting my window and killing the app as I described above.  My test will enter an invalid username and password, click the log on button, and verify that the error message label is visible.

  1. [TestClass]
  2. public class LogOnTests {
  3.  
  4.     #region Private Fields
  5.  
  6.     private Application _app;
  7.     private Window _window;
  8.  
  9.     #endregion
  10.  
  11.     #region Setup & Tear Down
  12.  
  13.     [TestInitialize]
  14.     public void MyTestInitialize() {
  15.         _app = Application.Launch(
  16.             @"c:\wpf\compositeapppoc\compositeapppoc.shell\compositeapppoc.shell\bin\debug\compositeapppoc.shell.exe");
  17.         _window = _app.GetWindow("Log On");
  18.     }
  19.  
  20.     [TestCleanup]
  21.     public void MyTestCleanup() {
  22.         _app.Kill();
  23.     }
  24.  
  25.     #endregion
  26.  
  27.    [TestMethod]
  28.     public void Entering_InvalidCredentials_AndClickingThe_LogOnButton_ShouldDisplayThe_InvalidCredentialsMessage() {
  29.         //Arrange
  30.         _window.Get<TextBox>("txtUsername").Text = "InvalidUsername";
  31.         _window.Get<TextBox>("txtPassword").Text = "InvalidPassword";
  32.         var btn = _window.Get<Button>("btnLogOn");
  33.         //Act
  34.         btn.Click();
  35.         _window = _app.GetWindow("Log On");
  36.         //Assert
  37.         (_window.Get<Label>("lblErrorMessage")).Visible.ShouldBeTrue();
  38.     }
  39. }

It’s that easy.  With very little effort you can have a full suite of automated tests for testing your UI.  How cool is that!?

* Download Complete Source Code

posted on Friday, September 10, 2010 4:25:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [6]
# Monday, August 23, 2010

* Download Complete Source Code

In an attempt to be a Pragmatic Programmer I make an effort to learn a new programming language yearly.  This year the language of choice is Ruby, including Rails.  About a month ago I started the Build Your Own Blog :: Rails series at TekPub.  In this series Rob Conery instructs on creating a blog engine using Rails and focusing on Behavior Driven Development.  Rob introduces some amazing tools, such as Cucumber and Pickle, that make BDD on Rails easy and dare I say…fun!

If you have been following along at home with my previous serious of blog posts you know that in my day job I am currently architecting a large WPF MVVM composite application using Prism.  My development methodology for .Net development is TDD and not BDD, because I just don’t feel the tools are there yet in the .Net space for efficient BDD.  I am at the point in the project where I am starting work on the UI and being fresh of learning the wonderful BDD tools available in the Rails stack it was really annoying me that I had no way to TDD my UI.  Grant it, using MVVM I was able to get much closer to the actual UI than I otherwise would, but it still wasn’t the same.  Finally I got to the point where I just had to research the idea of Cucumber style testing in WPF.  What I found out was it is possible using IronRuby.  Don’t be mistaken, it does not offer the same ease and simplicity as it does on the Rails stack but it is certainly a leap in the right direction.

The tool that is going to make this all possible was written by Nathaniel Ritmeyer and is called Bewildr!

Here are the steps to getting your environment setup…

  1. Follow the steps in my previous blog post to get Ruby, IronRuby, and Cucumber installed. 
  2. Install Bewildr.
    image
  3. Install UISpy.

I am going to be testing the UI created in my previous series: Rolling Your Own Module Level Security for a WPF MVVM Composite Application

Detailed information on Cucumber can be found here.  But, basically Cucumber allows you to write plain-text functional descriptions as automated tests.  Cucumber code consists of two main pieces; Features/Scenarios and Step Definitions.  This is not meant to be a Cucumber tutorial so if you are not familiar with Cucumber I would suggest reading up on it prior to continuing.

OK.  So, now that your familiar with Cucumber you are probably asking yourself how is this going to allow me to do automated UI testing?  This is where Bewildr enters the party.  Bewildr is a Ruby GEM that uses the MS UI Automation Framework to gain programmatic access to a WPF UI.  Basically, I can spin up a WPF application and manipulate the UI, click buttons, enter text in text boxes, etc, all via code.

So, let’s start with a simple scenario.  (I apologize for the formatting/highlighting…need to find a good formatter plug-in for Cucumber code.

application.feature
  1. @application
  2. @window
  3.  
  4. Feature: Application Interaction
  5.  
  6.   Scenario: The Log On window should be displayed on application start
  7.     Given I ensure that there are no instances of "CompositeAppPoc.Shell.exe" running
  8.     When I start "C:\\development\\research\\wpf\\CompositeAppPoc\\CompositeAppPoc.Shell\\CompositeAppPoc.Shell\\bin\\Debug\\CompositeAppPoc.Shell.exe"
  9.     Then 1 window is displayed with name "Log On"
  10.       And Terminate the app

If we go ahead and run this feature Cucumber is going to puke on us because we haven’t created our steps yet.  But, when Cucumber pukes…it pukes in a helpful way.  It is going to give us the shell for the steps we need to create in order to execute this feature.

image

As you can see Cucumber lets us know that we need to define 4 steps in order to get our Feature and Scenario running.  So let’s do that.  Since 3 of the steps deal with the application itself and 1 deals specifically with a window I am going to create 2 step files.

application_steps.rb
  1. require 'bewildr'
  2.  
  3. Given /^I ensure that there are no instances of "([^"]*)" running$/ do |app|
  4.   Bewildr::Application.kill_all_processes_with_name(app)
  5. end
  6.  
  7. When /^I start "([^"]*)"$/ do |app|
  8.   @application = Bewildr::Application.start(app)
  9. end
  10.  
  11. When /^Terminate the app$/ do
  12.   @application.kill
  13. end

window_steps.rb
  1. require 'bewildr'
  2.  
  3. Then /^ (\d+) window is displayed with name "([^"]*)"$/ do |count,name|
  4.       @window = @application.wait_for_window(name)
  5.       @application.windows.size.should == count.to_i
  6.       @window.name.should match(name)
  7. end

In the steps coded above you can begin to see what Bewildr allows us to do.  Now if you run this feature you should see the output below as well as the app physically spinning up and closing.

image

And as you can see our scenario passed.

This is really just scratching the surface of what you can do.  I would suggest downloading the code and get an understanding of some of the more advanced scenarios and then start creating your own.

* Download Complete Source Code

posted on Monday, August 23, 2010 6:04:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [137]
# Monday, August 16, 2010

Note: This expands on the code created in my previous post: Requiring Log-On in a WPF MVVM Composite Application

* Download Complete Source Code

Continuing on my WPF MVVM Adventures...  Well, I am still waiting on the business to finalize the requirements so I am going to take a shot at coding it to what I think the final specs will be.  Although this is a very common situation, when you take this slippery slope you need to be careful that you don’t end up creating throw away code.   Make sure you:

  1. Program to Interfaces. (FYI – you should be doing this anyway!)
  2. Add Abstraction layers that will allow you to swap out implementation. (See step 1)
  3. Keep all the possible solutions to the problem in mind when designing/coding.  In my case I am 99% certain the business will want security down to the composite module level, but I am still going to leave paths open that will allow me to implement field level security without too much re-work.

The first thing I need is to define by security roles.  Since the actual roles are TBD I am just going to create a simple Enumeration.

Enumerations.cs
  1. namespace CompositeAppPoc.Infrastructure.Enumerations {
  2.  
  3.     public enum AuthorizationLevel {
  4.         ReadOnly,
  5.         ReadWrite,
  6.         Admin
  7.     }
  8. }

In thinking about what the Authentication method of my yet to be created service will return I decided it was going to need to return multiple things.

  1. Boolean representing whether or not the credentials where able to be authenticated.
  2. Level of authorization granted to credentials.
  3. List of modules that credentials are able to view.

Knowing I was going to need to return multiple values I created a data transfer object (DTO) to handle it.

AuthenticationContext.cs
  1. using System.Collections.Generic;
  2. using CompositeAppPoc.Infrastructure.Enumerations;
  3.  
  4. namespace CompositeAppPoc.Infrastructure.DataTransferObjects {
  5.  
  6.     public class AuthenticationContext {
  7.  
  8.         public bool IsAuthorized { get; set; }
  9.  
  10.         public AuthorizationLevel AuthLevel { get; set; }
  11.  
  12.         public IList<string> AllowedModules { get; set; }
  13.  
  14.     }
  15. }

Now I can create my service.  This is going to reside in my Infrastructure project and will allow me to push(abstract) the implementation of the actual authentication farther down the stack.  Sticking to what I recommended at the beginning of this post I am going to create a simple interface for the service.  The interface will declare one signature, Authenticate, that accepts a username and password and returns an AuthenticationContext.

IAuthenticationService
  1. using CompositeAppPoc.Infrastructure.DataTransferObjects;
  2.  
  3. namespace CompositeAppPoc.Infrastructure.Interfaces {
  4.  
  5.     public interface IAuthenticationService {
  6.         AuthenticationContext Authenticate(string userName, string password);
  7.     }
  8. }

Next we need to code the actual implementation of IAuthenticationService.  At this time the implementation of Authenticate will need to perform the actual authentication, which will set the IsAuthorized flag as well as the AuthLevel, and determine what modules are viewable for the AuthLevel.  Because I still have not defined the details of these process I am going to “stub” them out with a trivial implementation.

AuthenticationService.cs
  1. using System.Collections.Generic;
  2. using CompositeAppPoc.Infrastructure.Constants;
  3. using CompositeAppPoc.Infrastructure.DataTransferObjects;
  4. using CompositeAppPoc.Infrastructure.Enumerations;
  5. using CompositeAppPoc.Infrastructure.Interfaces;
  6.  
  7. namespace CompositeAppPoc.Infrastructure.Services {
  8.  
  9.     public class AuthenticationService : IAuthenticationService {
  10.  
  11.         private readonly AuthenticationContext _authenticationContext = new AuthenticationContext();
  12.  
  13.         public AuthenticationContext Authenticate(string userName, string password) {
  14.             Authorize(userName, password);
  15.             if (_authenticationContext.IsAuthorized) {
  16.                 GetApprovedModules();
  17.             }
  18.             return _authenticationContext;
  19.         }
  20.  
  21.         private void Authorize(string userName, string password) {
  22.             if (userName.Equals("admin") && password.Equals("pass")) {
  23.                 _authenticationContext.IsAuthorized = true;
  24.                 _authenticationContext.AuthLevel = AuthorizationLevel.Admin;
  25.             }
  26.             else if (userName.Equals("readwrite") && password.Equals("pass")) {
  27.                 _authenticationContext.IsAuthorized = true;
  28.                 _authenticationContext.AuthLevel = AuthorizationLevel.ReadWrite;
  29.             }
  30.             else if (userName.Equals("readonly") && password.Equals("pass")) {
  31.                 _authenticationContext.IsAuthorized = true;
  32.                 _authenticationContext.AuthLevel = AuthorizationLevel.ReadOnly;
  33.             }
  34.         }
  35.  
  36.         private void GetApprovedModules() {
  37.             IList<string> modules = new List<string>();
  38.             switch (_authenticationContext.AuthLevel) {
  39.                 case AuthorizationLevel.Admin:
  40.                     modules.Add(EmployeeConstants.EmployeeEditModuleName);
  41.                     modules.Add(EmployeeConstants.EmployeeCreateModuleName);
  42.                     break;
  43.                 case AuthorizationLevel.ReadWrite:
  44.                     modules.Add(EmployeeConstants.EmployeeCreateModuleName);
  45.                     break;
  46.             }
  47.             _authenticationContext.AllowedModules = modules;
  48.         }
  49.     }
  50. }

Now we need to hop over the Shell project and start making adding in the hooks for our module level security.

This first I am going to do is change how the modules are loaded.  Initially I used the ConfigurationModuleCatalog which loads the modules from a configuration file.  I decided against this approach because I wanted to avoid configuration changes when a module was added or removed.  Luckily Prism provides another option called the DirectoryModuleCatalog.  This allows you to supply a directory path that contains the dll’s for your modules.  So, all that needs to be done in order to add a new module is to drop its dll’s in that directory.  This change needs to implemented in the bootstrapper and while we are in there we need to tell our IOC container how to wire up our AuthenticationService.

Bootstrapper.cs
  1. using System.Windows;
  2. using CompositeAppPoc.Infrastructure.Interfaces;
  3. using CompositeAppPoc.Infrastructure.Services;
  4. using Microsoft.Practices.Composite.Modularity;
  5. using Microsoft.Practices.Composite.UnityExtensions;
  6. using Microsoft.Practices.Unity;
  7.  
  8. namespace CompositeAppPoc.Shell {
  9.  
  10.     public class Bootstrapper : UnityBootstrapper {
  11.  
  12.         protected override DependencyObject CreateShell() {
  13.             Shell shell = new Shell();
  14.             shell.Show();
  15.             return shell;
  16.         }
  17.  
  18.         protected override IModuleCatalog GetModuleCatalog() {
  19.             return new DirectoryModuleCatalog() {ModulePath=Infrastructure.Constants.GeneralConstants.ModulePath};
  20.         }
  21.  
  22.         protected override void ConfigureContainer() {
  23.             base.ConfigureContainer();
  24.             Container.RegisterType<IAuthenticationService, AuthenticationService>(new ContainerControlledLifetimeManager());
  25.             Container.RegisterType<IEmployeeDataService, EmployeeDataService>(new ContainerControlledLifetimeManager());
  26.             Container.RegisterType<IModuleManager, ModuleManager>(new ContainerControlledLifetimeManager());
  27.         }
  28.     }
  29. }

So now that we did that we can more easily add new modules but it’s still all or nothing.  We need to tell Prism to not load certain modules until we tell it to…load on demand.  This is accomplished by simply by decorating the modules you want to load on demand with the Module attribute and setting the ModuleName and OnDemand properties.  As you can guess we are going to set the OnDemand property to “True”.  This tells Prism, when it is processing the modules in the directory we tell it, not to load the module just yet.  Prism notes the name of the module and waits for us to tell it when to load it.  We will do this on the EmployeeEditModule, and EmployeeCreateModule which will both require authorization but we will not do this to the EmployeeListModule because that module is viewable by all.

EmployeeEditModule.cs
  1. [Module(ModuleName=EmployeeConstants.EmployeeEditModuleName, OnDemand=true)]
  2. public class EmployeeEditModule : IModule {

EmployeeCreateModule.cs
  1. [Module(ModuleName=EmployeeConstants.EmployeeCreateModuleName, OnDemand=true)]
  2. public class EmployeeCreateModule : IModule {

Now when you run the the shell you won’t be able to edit or create a new employee because those modules are not loaded which means that nothing is registered to the associated commands.

We already have the list of allowed secured modules being returned from the authentication service so we just need to write a method to process the list and load the modules.  This method will be in the Bootstrapper and it will load the allowed secured modules using the Module Manager.

LoadSecuredModules
  1. public void LoadSecuredModules(IList<string> allowedModules) {
  2.     var moduleManager = Container.Resolve<IModuleManager>();
  3.     foreach (string module in allowedModules) {
  4.         moduleManager.LoadModule(module);
  5.     }
  6. }

Lastly we need to call LoadSecuredModules.  We will do this as the last step in the App.xaml’s StartUp method.

StartUp
  1. private static void StartUp(IList<string> allowedModules) {
  2.     Current.MainWindow = null;
  3.     Current.ShutdownMode = ShutdownMode.OnMainWindowClose;
  4.     var bs = new Bootstrapper();
  5.     bs.Run();
  6.     bs.LoadSecuredModules(allowedModules);
  7. }

Now when we log in with a read-only id (readonly,pass) the edit and create new buttons are not enabled because the modules are not loaded.

image

* Download Complete Source Code

posted on Monday, August 16, 2010 5:40:00 PM (Central Daylight Time, UTC-05:00)  #    Comments [39]