Eagerness to fail

If your developers are eagerly taking blame for failures on your project they’re either:

a) buying into the concept of collective code ownership and have a commitment to quality
     or
b) are trying to get blamed for everything so that they can be fired and rid of your place of employ.

PostSharp Training

I’ve hooked up with the fine folks over at SharpCrafters to build some training materials for their AOP product PostSharp. Starting in January of 2012 we will be offering training on the use of PostSharp for all your Aspect Oriented Programming needs. I’m currently working on writing the materials and every day I’m finding more interesting little corners of the tool. I’m really looking forward to some of the things that Gael has in store for v3 of it.

If you’re interested in getting some training on PostSharp, shoot me an email at training@igloocoder.com.

Professional Neglect and Clear Text Passwords

For that past few years I’ve been the recipient of a monthly reminder from Emug (Edmonton Microsoft User Group). The contents of that email is where the problems lay. Every month that email comes in and it contains 3 pieces of information (plus a lot of boilerplate):

  1. A link to the Emug mailing list admin site
  2. My username
  3. My password in clear text

It doesn’t take much thought to know that storing clear text password is a prime security issue. Sending those passwords in emails doesn’t make it any better. Emails can be intercepted. Systems can be hacked. It’s happened before. Just read about the hack of PlentyOfFish.com. Or the hack of HB Gary. Two things stand out in these attacks. First, PlentyOfFish stores its passwords in clear text which made it easy to compromise the entire user base once access was achieved. HB Gary (an IT security consulting firm no less) had many users who used the same password between different systems which made it easy to hop from system to system gaining different access.

Most web users don’t heed advice to have a different password for every user account they create. First, it seems unreasonable to try to remember them all. Second, most people believe that using their dogs name combined with their birth date is never going to be hackable. As system designers and operators (which the Emug membership is a professional community of) we should know that we can’t do much of anything to prevent users from choosing bad passwords. We can, however take the steps to ensure that those passwords are adequately protected.

So with all of that in mind I decided to call the Emug people on their password practices. I sent an email of concern to them along with a request that they take the time to do the correct professional thing with regards to their members passwords. The response I received back included…

I know what you're saying about the passwords though, the first one you get is randomly generated and if you ever did go on and change it to a common one then it is there within all the options you can also set it to the option of the password reminder. The option "Get password reminder email for this list?" is a user based control option and you can set that to your liking. It's in with all the digest options.

That’s great. So basically the Emug response was “You don’t have to see that we store your password in clear text if you just go uncheck this one box”. Jeez guys, thanks. So you’re suggesting that I should feel that my password is secure just because I’m not seeing it in an email anymore? Security through naiveté?

Most places / sites/ subscriptions now have an automated email reminder method. It does make you ponder its value but I think the focus on that this is a very low level security setting.

Okay…so because you think “most places/sites/subscription now have an automated email reminder” it’s okay for you to follow the same bad practices? Really? What happened to professionalism? Or integrity? Yah I know, that takes effort and you’re just a volunteer running a community group. Except for one little thing: the members of that community entrusted you with their passwords. There was an implied belief that you would protect those passwords in an acceptable manner. Clearly you’re not.

I also ask you to enumerate “most places / sites / subscriptions” please. I don’t get an email from Google Groups, StackOverflow, etc that contains my password in clear text. I know that those are professional companies and you’re not, but remember that professionalism has nothing to do with the size or revenue of your organization.

The piece of the email that really rubbed me the wrong way was this:

The mailman list serve server and application is maintained centrally not by us for the record. It is more of a self-service model and is intentionally designed for little to no maintenance or requirement to assist an end user.

So you don’t administer the system. That’s fine.  Yes, the current system may have been designed/implemented to require as little end user support as possible. That’s fine too. Here are my beefs. You have the choice to change what tooling you’re using. I’m pretty sure that you’re able to use Google to find replacement options. It will take some time and effort to see the change through, but don’t you think the integrity of your member’s passwords is worth it?

So to Brett, Colin, Ron and Simon: Please show a modicum of professionalism and take care of this issue. Since you chose not to continue the conversation with me via email, I’ve resorted to blogging. I’m submitting your mailing list email to www.plaintextoffenders.com. I’ll be contacting other community members in the hopes that they can get through to you. I suspect they won’t be able to, but I feel that I have a professional obligation to at least try.

Much Ado About Agile 2010 – Aspect Oriented Programming materials

As promised here is the slide deck and the completed code materials that were covered in my session at Agile Vancouver.  I had a great time interacting with the attendees in the session and throughout the rest of the conference.  Kudos to the organizers of Agile Vancouver for having created such a fantastic event.

UI Workflow is business logic

Over my years as a programmer I’ve focussed a lot of attention and energy on business logic.  I’m sure you have too.  Business logic is, after all, a huge part of what our clients/end users want to see as an output from our development efforts.  But what is included in business logic?  Usually we think of all the conditionals, looping, data mangle-ment, reporting and other similar things.  In my past experiences I’ve poured immense effort into ensuring that this business logic was correct (automated and manual testing), documented (ubiquitous language, automated testing and, yes, comments when appropriate) and centralized (DDD).  While I’ve had intense focus on these needs and practices, I’ve usually neglected to recognize the business logic that is buried in the UI workflow within the application.

On my current project I’ve been presented with an opportunity to explore this area a bit more in depth.  We don’t have the volume of what I have traditionally considered business logic.  Instead the application is very UI intensive.  As a result I’ve been spending a lot more time worrying about things like “What happens when the user clicks XYZ?”  It became obvious to us very early on that this was the heart of our application’s business logic.

Once I realized this we were able to focus our attention on the correctness, discoverability, centralization and documentation of the UI workflow.  How did we accomplish this then?  I remember reading somewhere (written by Jeremy Miller I think, although I can’t find a link now) the assertion that “Every application will require the command pattern at some point.” I did some research and found a post by Derick Bailey explaining how he was using an Application Controller to handle both an Event Aggregator and workflow services.  To quote him:

Workflow services are the 1,000 foot view of how things get done. They are the direct modeling of a flowchart diagram in code.

I focused on the first part of his assertion and applied it to the flow of user interfaces.  Basically it has amounted to each user workflow (or sequence of UI concepts) being defined, and executed, in one location.  As an example we have a CreateNewCustomerWorkflowCommand that is executed when the user clicks on the File | Create Customer menu.  It might look something like this:

1: public  class  CreateNewCustomerWorkflowCommand  : ICommand <CreateNewCustomerWorkflow >
2: {
3:     private  readonly  ISaveChangesPresenter  _saveChangesPresenter;
4:     private  readonly  ICustomerService  _customerService;
5:     private  readonly  ICreateNewCustomerPresenter  _createNewCustomerPresenter;
6: 
7:     public  CreateNewCustomerWorkflowCommand(ISaveChangesPresenter  saveChangesPresenter,
8:                                             ICustomerService  customerService,
9:                                             ICreateNewCustomerPresenter  createNewCustomerPresenter)
10:     {
11:         _saveChangesPresenter = saveChangesPresenter;
12:         _customerService = customerService;
13:         _createNewCustomerPresenter = createNewCustomerPresenter;
14:     }
15: 
16:     public  void  Execute(CreateNewCustomerWorkflow  commandParameter)
17:     {
18:         if  (commandParameter.CurrentScreenIsDirty)
19:         {
20:             var  saveChangesResults = _saveChangesPresenter.Run();
21:             if  (saveChangesResults.ResultState == ResultState .Cancelled) return ;
22:             if  (saveChangesResults.ResultState == ResultState .Yes)
23:             {
24:                 _customerService.Save(commandParameter.CurrentScreenCustomerSaveDto);
25:             }
26:         }
27: 
28:         var  newCustomerResults = _createNewCustomerPresenter.Run();
29:         if  (newCustomerResults.ResultState == ResultState .Cancelled) return ;
30:         if  (newCustomerResults.ResultState == ResultState .Save)
31:         {
32:             _customerService.Save(newCustomerResults.Data);
33:         }
34:     }
35: }

As you can see the high level design of the user interaction, and service interaction, is clearly defined here.  Make no mistake, this is business logic.  It answers the question of how does the business expect the creation of a new customer to occur.  We’ve clearly defined this situation in one encapsulated piece of code.  By doing this we have now laid out a pattern whereby any developer looking for a business action can look through these workflows.  They clearly document the expected behaviour during the situation.  Since we’re using Dependency Injection in our situation, we can also write clear tests to continuously validate these expected behaviours.  Those tests, when done in specific ways, can also enhance the documentation surrounding the system.  For example, using BDD style naming and a small utility to retrieve and format the TestFixture and Test names we can generate something like the following:

1: public  class  When_the_current_screen_has_pending_changes
2:  {
3:     public  void  the_user_should_be_prompted_with_the_option_to_save_those_changes(){}
4: }
5: 
6: public  class  When_the_user_chooses_to_cancel_when_asked_to_save_pending_changes
7:  {
8:     public  void  the_pending_changes_should_not_be_saved(){}
9:     public  void  the_create_new_customer_dialog_should_not_be_displayed(){}
10: }
11: 
12: public  class  When_the_user_chooses_not_to_save_pending_changes
13:  {
14:     public  void  the_pending_changes_should_not_be_saved(){}
15:     public  void  the_create_new_customer_dialog_should_be_displayed(){}
16: }
17: 
18: public  class  When_the_user_chooses_to_to_save_pending_changes
19:  {
20:     public  void  the_pending_changes_should_be_saved(){}
21:     public  void  the_create_new_customer_dialog_should_be_displayed(){}
22: }
23: 
24: public  class  When_the_user_chooses_to_cancel_from_creating_a_new_customer
25:  {
26:     public  void  the_new_customer_should_not_be_saved(){}
27: }
28: 
29: public  class  When_the_user_chooses_to_create_a_new_customer
30:  {
31:     public  void  the_new_customer_should_be_saved(){}
32: }

As you can see, this technique allows us to create a rich set of documentation outlining how the application should interact with the user when they are creating a new customer.

Now that we’ve finished implementing this pattern a few times, have I seen any drawbacks?  Not really.  If we didn’t use this technique we’d still have to write the code to coordinate the screen sequencing.  That sequencing would be spread all over the codebase, most likely in the event handlers for buttons on forms (or their associated Presenter/Controller code).  Instead we’ve introduced a couple more classes per workflow and have centralized the sequencing in them.  So the trade off was the addition of a couple of classes per workflow for more discoverability, testability and documentation.  A no brainer if you ask me.

Is this solution the panacea?  Absolutely not.  It works very well for the application that we’re building though.  In the future will I consider using this pattern? Without doubt.  It might morph and change a bit based on the next application’s needs, but I think that the basic idea is strong and has significant benefits.

A big shout out to Derick Bailey for writing a great post on the Application Controller, Event Aggregator and Workflow Services.  Derick even has a sample app available for reference.  I found it to be great for getting started, but it is a little bit trivial as it only implements one simple workflow.  Equally big kudos to Jeremy Miller and his Build Your Own CAB series which touches all around this type of concept.  Reading both of these sources helped to cement that there was a better way.

DateTime formatting for fr-CA

I just stumbled across a nice little hidden “feature” in the .NET framework.  If you’re running on a machine that has the CurrentCulture set to fr-CA the default DateTimeFormatInfo.CurrentInfo.ShortDatePattern is dd-MM-yyyy.  On my current project we wanted to allow the end user to override that value with their own format when a date is displayed on the screen.  The easy way to do this is to do something like DateTime.Now.ToString(“dd/MM/yyyy”).  Unfortunately the result from that will appear as 16-09-2010 still.  As far as I can tell (and there is very little backing this up), this is by design.  I’m not sure why at all.  If the CurrentCulture is set to en-CA both the formats of dd/MM/yyyy and dd-MM-yyyy will cause ToString() to output a value that you would expect, but as soon as you trip over to fr-CA the rules seem to change.

If you’re running into this there is a relatively simple solution.  DateTime.Now.ToString(“dd\/MM\/yyyy”) will output 16/06/2010 as you’d expect.

The more localization that I’m doing on this application, the more I’m finding nice hidden gems of inconsistency like this.

Microsoft.Data.dll and LightSwitch

Microsoft has made some announcements over the last week or so.  The first was Microsoft.Data.dll.  I think that Oren adequately wraps up the feelings that I have towards it.

The second was the announcement of Visual Studio LightSwitch.  I have some strong feelings for this as well.  Microsoft is positioning this as a tool that allows non-professional developers create line of business (LoB) applications.  They suggest that it will allow these non-developers to create applications that can be handed off to IT for maintenance and further enhancement.  Since LightSwitch isn’t really Visual Studio, the IT group will have to upgrade the application codebase.  Does this sound like anything to you’ve ever heard of before?

While Microsoft won’t come out and say it, LightSwitch is positioned to fill the space that MS Access has for more than a decade.  During that decade plus IT departments and programmers world wide have grown to loathe MS Access application created by business.  Invariably those MS Access systems start live as small intra-department apps that service one to a few users.  Over time their feature set grows along with their user base.  At some point these LoB applications hit an invisible wall.  Sometimes it’s that the system has devolved into a mess of macros and VBA.  Other times they have collapsed under the pressures of concurrent users.  Regardless, the developers that take over these applications are met with a brownfield mess.  On top of that, the application has likely grown into a brownfield application that is critical to the business.  We professional developers end up picking up the pieces and, often, re-writing the application from scratch, under huge timeline pressure, so that it can meet the requirements and specifications that it has grown to need.

So back to LightSwitch.  Why is Microsoft pitching what this product is good at to us professional developers?  They say it’s not for us, but instead for non-professional developers.  Market it to them then.  Don’t waste our time with this marketing campaign.  Instead Microsoft, sell us on the part we’re going to have to deal with; the migration and fixing once these “LightSwitch” applications when the business inevitably comes running to us to do this.

To the professional developers that read this blog (most of you I’m guessing), prepare to move your hatred and loathing from MS Access to LightSwitch.

Making the most of Brownfield Application Development – Winnipeg Edition

On Friday July 23rd I’ll be in Winnipeg giving a one day seminar on the nuances of Brownfield Application Development and how to get the most out of it.  More about the day can be found here.  I recently did the seminar at the PrairieDevCon and it was a blast.  The day is filled chocka-block with content and ideas that pertain directly to Brownfield codebases and will work in Greenfield situations.

Registration can be found here and until July 2nd the session is available at a discount.  Hope to see you there!

Visual Studio Project files and coupling

The way that we’re told to use Visual Studio is that we create a solution file and add into it one or more project files.  Each project file then gets filled with different development artefacts.  When you build inside of Visual Studio each project represents a compiled distributable file (exe, dll, etc).  Many people carry this practice over into their build scripts.  You might be one of them.  I’m here to tell you why you’re wrong to be doing this.

Let’s say you’re starting a project.  You open Visual Studio, select File | New Project and get things rolling.  In a few minutes you have a Solution that contains a few Projects.  Maybe you have one for the UI, one for the business logic and one for the data access layer.  All is good.  A few months later, after adding many artefacts to the different projects, something triggers the need to split the artefacts into one assembly from one DLL into two DLLs. 

You set off to make this happen.  Obviously you need to add a new Project to your Solution, modify some references, and shift some files from one Project into another.  Say you’re stuck using an exclusive locking source control system (like VSS…shudder).  You *must* have exclusive access to all the files necessary including:

  • the sln so you can add the new project
  • at least one existing cs/vb/fsproj which you’ll be removing existing code artefacts from
  • any cs/vb/fs files that will be moved
  • any cs/vb/fs files that reference the ones moving (using statements will need updating when you change the namespacing on the files being moved)
  • possibly some resx files that need to be moved
  • possibly config files that need to be changed or moved
  • any automated tests that make use of the moving cs/vb/fs files

It’s a pretty damn big list of files that you will need to exclusively lock during this process.  Chances are you will need to push all of your co-workers out of the development environment so that you can gain access to all of those files.  Essentially you are, at this point, halting the development process so that you can do nothing more than split one DLL into two.  That in quite inefficient in the short term and it’s completely unsustainable in the long term.

I can hear you now, “Well I use <git/mercurial/svn/etc> so we won’t have those issues”.  Really?  Think it through for a second.  Go ahead, I’ll wait.

With the volume of changes that I listed above, you’ll likely want to be working in some kind of isolation, whether that is local or central.  So yes, you can protect yourself from blocking the ongoing development of your co-workers by properly using those version control systems.  But remember, you do have to integrate your changes with their work at some point.  How are you going to do that?  You’ve moved and modified a significant number of files.  You will have to merge your changes into a branch (or the trunk) locally or otherwise.  Trust me, this will be a merge conflict nightmare.  And it won’t be a pain just for you.  What about the co-worker that has local changes outstanding when you commit your merged modification?  They’re going to end up with a massive piece of merge work on their plate as well.  So instead of being blocked while you do the work, you’re actually creating a block for them immediately after you have completed your work.  Again, the easiest way to achieve the changes would be to prevent any other developers from working in the code while modifications are occurring.  Doesn’t that sound an awful lot like exclusive locking?

Now, I know you’re thinking “Pfft..that doesn’t happen often”.  This is where you’re wrong.  When you started that application development cycle (remember File | New Project?) you likely didn’t have all of the information necessary to determine what your deployables requirements were.  Since you didn’t have all of that information, chances were good, right from the outset, that you were going to be doing the wrong thing.  With that being the case, it means that chances were good that you were going to have to make changes like the one described above.  To me that indicates that you are, by deciding to tie your Visual Studio Projects to your deployables, accepting that you will undertake this overhead.

People, possibly you, accept this overhead on every software project they participate in.  This is where you’re wrong.  There is a way to avoid all of this, but people shrug it off as “not mainstream” and “colouring outside the lines”.  The thing is it works, so ignore it at your own peril.

There is a lot of talk in some development circles about decoupling code.  It’s generally accepted that tightly coupled code is harder to modify, extend and maintain.  When you say that a Visual Studio Project is the equivalent of a deployable, you have tightly coupled your deployment and development structures.  Like code, and as the example above shows, it makes it hard to modify, extend and maintain your deployment.  So why not decouple the Visual Studio Project structure from the deployables requirements?

It’s not that hard to do.  You’ll need to write a build script that doesn’t reference the cs/vb/fsproj files at all.  The .NET Framework kindly provides configurable compiler access for us.  The different language command line compilers (vbc.exe/csc.exe/fsc.exe) allow you to pass in code files, references, resources, etc.  By using this capability, you can build any number of assemblies that you want simply by passing a listing of artefacts into the compiler.  To make it even easier, most build scripting tools provide built in capability to do this.  NAnt and MSBuild both provide (for C#) <csc> tasks that can accept wild carded lists of code files.  This means you can end up with something like this coming out of a solution-project structure that has only one project in it:

<csc output="MyApp.DAL.dll" target="library" debug="${debug}">
  <sources>
    <include name="MyApp.Core/DAL/**/*.cs"/>
  </sources>
  <references>
    <include name="log4net.dll"/>
  </references>
</csc>

<csc output="MyApp.Core.dll" target="library" debug="${debug}">
  <sources>
    <include name="MyApp.Core/Business/**/*.cs"/>
  </sources>
  <references>
    <include name="log4net.dll"/>
    <include name="MyApp.DAL.dll"/>
  </references>
</csc>

<csc output="MyApp.UI.exe" target="winexe" debug="${debug}">
  <sources>
    <include name="MyApp.Core/**/*.cs"/>
    <exclude name="MyApp.Core/DAL/*.cs"/>
    <exclude name="MyApp.Core/Business/*.cs"/>
  </sources>
  <references>
    <include name="log4net.dll"/>
    <include name="MyApp.DAL.dll"/>
    <include name="MyApp.Core.dll"/>
  </references>
</csc>

Likewise, we could consolidate code from multiple projects (really file paths is what the build script sees them as) into one deployable.

<csc output="MyApp.UI.exe" target="winexe" debug="${debug}">
  <sources>
    <include name="MyApp.DAL/**/*.cs"/>
    <include name="MyApp.Business/**/*.cs"/>
    <exclude name="MyApp.UI/**/*.cs"/>
  </sources>
  <references>
    <include name="log4net.dll"/>  
  </references>
</csc>

Now, when it comes time to change to meet new deployables needs, you just need to modify your build script.  Modify the inputs for the different compiler calls and/or add new compilations simply by editing one file.  While you’re doing this the rest of your co-workers can continue doing what they need to provide value to the business.  When it comes time for you to commit the changes to how things are getting compiled, you only have to worry about merging one file. Because the build script is far less volatile than the code files in your solution-project structure, that merge should be relatively painless.

Another way to look at this is that we are now able to configure and use Visual Studio and the solution-project structure in a way that is optimal for developers to write and edit code.  And, in turn, we configure and use the build script in a way that allows developers to be efficient and effective at compiling and deploying code.  This is the decoupling that we really should have in our process and ecosystem to allow us to react quickly to change, whether it comes from the business or our own design decisions.

Rotating text using Graphics.DrawString

Recently I needed to create a custom WinForms label-like control that allowed for the text to be displayed in a rotated fashion.  Our needs were only for four rotation locations; 0 degrees (the default label position), 90, 180 and 270 degrees.  There were other complicating factors, but for this post we’ll only concentrate on this component of the control.

To rotate text using the Graphics.DrawString method you only have to do a couple of things.  First you have to use the Graphics.TranslateTransform method, then the Graphics.RotateTransform method, and followed by the Graphics.DrawString.  Here’s what it looks like.

using (var brush = new SolidBrush(ForeColor))
{
    var stringFormat = new StringFormat
                       {
                           Alignment = StringAlignment.Near,
                           LineAlignment = StringAlignment.Near
                       };
    e.Graphics.TranslateTransform(transformCoordinate.X, transformCoordinate.Y);
    e.Graphics.RotateTransform(rotationDegrees);
    e.Graphics.DrawString(Text, Font, brush, DisplayRectangle, stringFormat);
}

What you see are the three steps that I outlined above.  Let’s start at the bottom and work our way up.  The code exists inside of a UserControl’s overridden OnPaint event.  The DrawString method makes use of some of the properties on the control, like Text and Font.  It also uses the DisplayRectangle property to set the boundaries for the drawing to be the same size as the control.  This is one of the keys to making the rotations work.  The other key is to provide the DrawString with the StringFormat settings.  By setting them to be StringAlignment.Near for both the Alignment and LineAlignment, you are declaring that the text’s location should be based in the top left of the DisplayRectangle’s area.

Graphics.RotateTransform is how you set the rotation value.  In the case of our control, we would be putting in a value from the list of 0, 90, 180, and 270.  As you might expect the rotations are clockwise with 0 starting with the text in the ‘normal’ location.

Graphics.TranslateTransform is where the last piece of magic occurs.  It is here that you set where the top right corner of the text drawing area will be located in the DisplayRectangle’s area.  Here are some images that will help clarify the situation.

0degrees

When you need the text to appear the same as “Text Area” does in the above image (rotated 0 degrees), you need to set the TranslateTransform X and Y parameters to be those that are designated by the “X” in the image.  In this case, it’s X=0 and Y = 0.

90degrees

The picture above shows you what you should be displayed when you are rotating the text “Text Area” 90 degrees.  Again, you need to set the TranslateTransform, but this time the values are slightly different.  The Y parameter is still 0, but the X parameter equals the height of the text.  You can get this value by using the following line of code:

var textSize = TextRenderer.MeasureText(Text, Font);
textSize.Height;

180degrees

To render the text upside down we set the rotation to 180 degrees and then, again, determine the location of the TranslateTransform X and Y coordinates.  Like we did for the last rotation, we will need to retrieve the text size to set these values.  For this situation Y will be the text height and X will be the text width.

270degrees

The final step is to make the rotation work for 270 degrees.  Like all the others, we need to set the X and Y coordinates for the TranslateTransform method call.  Here the Y value will be the text width and the X value will be 0.

This is simply the first step of many to making a control that will allow rotation of the text and locating it in one of 9 locations in a 3x3 grid representation of the control’s DisplayRectangle.  More on that in another blog post though.