.Net, Windows Live Writer

WLW Plugin for WordPress.com on CodePlex

There have been some requests to have me publish the WordPress.com sourcecode highlighter plug-in that I created for Windows Live Writer. So I went ahead and created a CodePlex project for it and published the code and the assembly.

You can find it here: WLW WordPress.com Syntax Highlighter Plugin

There is no official release but you can go to the "Downloads" tab and select the alpha release.

Publishing this out on CodePlex was actually fun and nerve racking at the same time. Since this was the first project that I ever published out there I wanted to make sure that everything was in "tip top shape." I can’t tell you how much time I spent just getting the "summary" correct. I must have rewritten it about five or six times. I am sure I made some faux pas but how is a guy suppose to learn?

Then I realized… it is what it is. Either people are going to find it useful or people are going to think its junk. Either way… it is the spirit of it all that I am finding more interesting. I had a need, wrote a little plug-in to satisfy that need, and am now sharing it to those who are interested.

What I think is going to be even more fun is revisiting this code later and seeing what improvements can be made and how to make it better.

So enjoy and let me know your comments and suggestions.

Standard
.Net

NServiceBus – Fifteen Minutes…

After downloading the assemblies I was ready to create my first sample application using NServiceBus. From what I can tell, a lot of time and effort has gone into building the NServiceBus.Host executable so if you plan on using it… you’re in luck, there are plenty of examples out there on how to use it. If you don’t want to use it, however, get ready for some digging (take a guess on which direction I went in). Hopefully this post will serve as a good example of how to handle things when you don’t want to use NServiceBus.Host. Time will tell…

The most basic example is sending a message. Note that this is not publishing a message but simply sending a message. To send a message you will need something that sends the message and something that will receive the message. Go ahead and create two console projects: 1) “Sender” and 2) “Receiver”.

You will need to be able to define a message that both the sender and receiver will be able to understand so go ahead and create library project (name it “Messages” for now to keep things simple).

Again, doing the most simple thing possible, add a reference to “NServiceBus.dll” to the “Messages” project. Create a new class, add the “Serializable”  attribute, and have the class implement the “IMessage” interface. This interface is nothing more than a indication to NServiceBus that it can be used as a message. And since we are going to be passing this class around as a message we need to be able to serialize it across the wire so… don’t forget the “Serializable” attribute.

[Serializable]
public class ExampleMessage : IMessage
{
  public int Id { get; set; }
  public string Message { get; set; }
}

A “message” can be thought of as a Data Transfer Object (DTO) in that the message should only contain data and really shouldn’t contain any methods or logic. There can be some interaction with the data like formatting or structuring but avoid putting any logic. Remember that this is going to be serialized.

From here add the “Messages” project as a reference to the “Sender” and “Receiver” console applications. While we are at it, go ahead and add a reference to “NServiceBus.dll” and “NServiceBus.Core.dll”.

Up to now we have three projects: Messages (contains our message class), Sender (the application that will send the message) and, Receiver (the application that will receive the message). So far so good.

The Sender

So now we want the “Sender” application to send a message out into the world. Prior to being able to send a message we first have to instantiate a service bus (for NServiceBus this is an IBus). NServiceBus has a “fluent interface” class named “Configure” that uses an Inversion of Control (IoC) container to build up, configure, and create an instance of a service bus. By default this is done through Spring.Net which is all nice and good but I prefer to use StructureMap so… that is what I choose to use here. The only difference in this example is the “StructureMapBuilder” call which tells NServiceBus to use StructureMap as the IoC container. If you leave this line out… you will use Spring.Net.

var bus = Configure.With()
  .StructureMapBuilder()
  .XmlSerializer()
  .MsmqTransport()
    .IsTransactional(false)
    .PurgeOnStartup(false)
  .UnicastBus()
    .ImpersonateSender(false)
  .CreateBus()
  .Start();

Now we have a service bus that we can send messages with. In order to send a message all we need to do is new up an instance of our class from the “Messages” project and call the Send method from our service bus instance. For this simple example we do this in a while loop where each time we hit “Enter” we send a message:

while (Console.ReadLine() != null)
{
  var message = new ExampleMessage(1, "My First Example");
  bus.Send(message);
}

Finally it is time to configure our “Sender” application. Here we need to add an Application Configuration File (App.config). Since we are sending a message we need to configure our MSMQ Transport and our Unicast Bus.

NOTE: Unlike other configuration sections you cannot “name” the section something different. The following section “names” must be as they appear or they do not work. Not 100% why this is but… if you don’t then it will not work

  <configSections>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
    <section name="UnicastBusConfig" type="NServiceBus.Config.UnicastBusConfig, NServiceBus.Core" />
  </configSections>
  <MsmqTransportConfig InputQueue="MySenderQueue" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" />
  <UnicastBusConfig DistributorControlAddress="" DistributorDataAddress="" ForwardReceivedMessagesTo="">
    <MessageEndpointMappings>
      <add Messages="MessageTypes" Endpoint="MyReceiverQueue" />
    </MessageEndpointMappings>
  </UnicastBusConfig>

Right now the important pieces to cover in the configuration are: InputQueue, Endpoint, and Messages.

InputQueue defines where this service bus can receive messages. Since the “Sender” is never going to receive a message in this example we can safely put anything we want here. For consistency I put “MySenderQueue”.

Endpoint defines where this service bus will send messages. This is a really important setting. We will be using this value later when we configure the “Receiver”.

Messages defines what type of messages this service bus will send to the Endpoint. Here we can break this up to be type specific but for this example we will simply instruct the service bus to send all of the messages from our “Messages” project to the Endpoint.

The Receiver

Now we want the “Receiver” to receive messages from the world. Prior to being able to receive messages we first have to instantiate another service bus similar to the way we did in our “Sender” project. The only real big difference in configuring this service bus is telling NServiceBus to load in our message handlers.

var bus = Configure.With()
  .StructureMapBuilder()
  .XmlSerializer()
  .MsmqTransport()
    .IsTransactional(false)
    .PurgeOnStartup(false)
  .UnicastBus()
    .ImpersonateSender(false)
    .LoadMessageHandlers()
  .CreateBus()
  .Start();

Since we don’t want our “Receiver” application closing as soon as we bring it up we need to add a little bit of code to make sure it sticks around while we test:

Console.ReadLine();

If you notice the only difference between the “Sender” and the “Receiver” is the LoadMessageHandlers call. So in order for NServiceBus to load our message handlers… we need to have a message handler. To do this simply add a new class and implement the “IHandleMessages<>” interface:

public class ExampleMessageHandler : IHandleMessages<examplemessage>
{
  public void Handle(ExampleMessage message)
  {
    Console.WriteLine("I got an example message... now what?");
  }
}

Finally it is time to configure our “Receiver” application. Here we need to add an Application Configuration File (App.config). Since we are only receiving messages we only need to configure our MSMQ Transport (no need to configure the Unicast Bus).

  <configSections>
    <section name="MsmqTransportConfig" type="NServiceBus.Config.MsmqTransportConfig, NServiceBus.Core" />
  </configSections>
  <MsmqTransportConfig InputQueue="MyReceiverQueue" ErrorQueue="error" NumberOfWorkerThreads="1" MaxRetries="5" />

In order to receive messages properly we need to make sure that the InputQueue value is the same as the Endpoint value from the “Sender” configuration. For this example it is “MyReceiverQueue”.

Done

Now you are ready to go and start sending messages from the “Sender” to the “Receiver”.

To do so simply right click the “Sender” project and click “Start new instance” from the “Debug” submenu. After this console app is up and running right click the “Receiver” project and click “Start new instance” from the “Debug” submenu. With both console applications up and running hit “Enter” from the “Sender” window and watch the message appear in the “Receiver” window.

Summary

All and all I would say that this took about fifteen to twenty minutes to get setup and running. That is pretty impressive especially when you start digging into what is actually happening in the background.

In future posts we can go over Publish and Subscribe, Request and Reply, and talk about the Distributor (which is some really neat stuff).

Standard
Principles, SOLID

SOLID – Liskov Substitution Principle (LSP)

As stated previously… I am getting (or trying to get) back to basics.

It is my belief that developers have to often times refactor the way they think and the way they approach things from time to time to make sure that the basics and principles are still strong.

So let’s take a look at one of the principles in SOLID; Liskov Substitution Principle (LSP)

LSP states:

If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of P is unchanged when o1 is substituted for o2 then S is a subtype of T

Right, to many this is as clear as mud. It took me a while to understand what this principle was really talking about at first. Then after reading a few papers written on the subject it became a little more clear. What I have seen many developers do, however, is paraphrase this principle (or actually rewrite it) to make it easier to understand.

Commonly, LSP is paraphrased to state:

Functions that use pointers or references to base classes must be able to use objects of derived classes without knowing it

So really all we are talking about is making sure our methods use base classes or interfaces as parameters and that the method does not have to know about all of the derived types of the base class or the classes that implement an interface.

Perhaps it is best to use an example to better explain what this principle is talking about.

public class Customer {
  ...
}

public class Vendor : Customer {
  ...
}

public class CustomerValidator {
  public void Validate(Customer customer) {
    if (string.IsNullOrEmpty(customer.Name)) {
      /// indicate that validation has failed
    }
    var vendor = customer as Vendor;
    if (vendor != null) {
      /// we know we are dealing with a Vendor
      /// validate Vendor rules
    }
}

Here we have a Customer class and a Vendor class which inherits from Customer. In the CustomerValidator class we are correctly using the Customer class (which would allow a Customer or Vendor object to be used… good so far) but then the Validate method has to know about the Vendor type and therefore violates LSP. What we can also (hopefully) see here is that we are violating the Open Closed Principle (OCP) due to the fact that any time we create another derived type from Customer we must modify the Validate method to handle the new type (hence it is closed for extension and is open for modification).

So how do we correct the above to remove the LSP violation?

The following is one way (and probably not the best way) to resolve the issues.

public class Validator {
  private readonly IList<string> errors;

  public Validator() {
    this.errors = new List<string>();
  }

  public void Validate(IValidation validation) {
    validation.Validate(errors);
  }
}

public interface IValidation {
  void Validate(IList<string> errors);
}

public CustomerValidation : IValidation {
  private readonly Customer customer;

  public CustomerValidation(Customer customer) {
    this.customer = customer;
  }

  public virtual void Validate(IList<string> errors) {
    /// if we fail validation add an error to the collection
  }
}

public VendorValidation : CustomerValidation {
  private readonly Vendor vendor;

  public VendorValidation(Vendor vendor)
    : base(vendor) {
    this.vendor = vendor;
  }

  public override void Validate(IList<string> errors) {
    /// call the Customer validation routines
    base.Validate(errors);
    /// if we fail validation add an error to the collection
  }
}

Wow. We have changed things up a lot.

If we look at the Validator class we can see that the Validate method takes a parameter which allows us to pass in any class that implements the IValidation interface. This follows LSP because we can substitute any class which implements this interface without changing the behavior. Not only that but the method doesn’t need to know anything about the types which implement the interface. At the same time, we have also solved our OCP violation by making the CustomerValidation class open for extension and closed for modification.

One more important thing that I would like to point out that sometimes get left out when explaining LSP is that exceptions should (or must) follow the same rules. This means that if you are throwing an exception in a method of a base class then any derived type overriding the method should throw the same type of exception. By doing this you can be ensured that your error handling for the base class will be correct for derived types as well. Just something that you should keep in mind.

Standard
Patterns, Principles, SOLID

SOLID – Open Closed Principle (OCP)

As stated previously… I am getting (or trying to get) back to basics.

It is my belief that developers have to often times refactor the way they think and the way they approach things from time to time to make sure that the basics and principles are still strong.

So let’s take a look at one of the principles in SOLID; Open Closed Principle (OCP)

OCP simply states:

Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification

In my mind following this principle is not limited to inheriting from a base class and marking methods and properties as virtual. While I do believe that there is a time and a place for following OCP in this manner I feel that this is sometimes the only solution that developers think of when thinking about OCP.

Take the following example of following OCP through inheritance.

public class OrderService {
  private readonly IRepository<Order> repo;

  public OrderService(IRepository<Order> repo) {
    this.repo = repo;
  }

  public virtual void Save(Order order) {
    repo.Save(order);
  }
}

public class EmailOrderService : OrderService {
  private readonly ISmptService emailService;

  public EmailOrderService(IRepository<Order> repo, ISmptService emailService)
    : base(repo) {
    this.emailService = emailService;
  }

  public override void Save(Order order) {
    base.Save(order);
    emailService.SendNotification(order);
  }
}

Ok so now we have these classes and we are clearly following OCP but I believe that there is an alternative through use of the Strategy pattern which would make this a little cleaner.

public class OrderService {
    private readonly IRepository<Order> repo;

    public OrderService(IRepository<Order> repo) {
        this.repo = repo;
    }

    public void Save(Order order) {
        repo.Save(order);
    }

    public void Save(Order order, IOrderStrategy strategy) {
        this.Save(order);
        strategy.Process(order);
    }
}

public class EmailOrderStrategy : IOrderStrategy {
    private readonly ISmptService emailService;

    public EmailOrderStrategy(ISmptService emailService) {
        this.emailService = emailService;
    }

    public void Process (Order order) {
        emailService.SendNotification(order);
    }
}

Here we can see that OCP is still being followed since the OrderService class is still open for extension via the IOrderStrategy and is closed for modification. We don’t need to mark any methods as virtual and don’t need to inherit from the OrderService class. What is even better is that we could have implemented a Specification pattern along with the Strategy pattern and really get cooking.

public class OrderService {
    ...
    public void Save(Order order, IEnumerable<IOrderStrategy> strategies) {
        this.Save(order);
        foreach (var strategy in strategies) {
            if (strategy.CanProcess(order))
                strategy.Process(order);
        }
    }
}

public class EmailOrderStrategy : IOrderStrategy {
    ...
    public bool CanProcess(Order order) {
        return order.SendEmail;
    }
    ...
}

So I guess all this really means is that OCP shouldn’t only be thought of as marking methods and properties as virtual. OCP should be thought about and reasoned about a little more deeply and carefully.

And granted the examples given here have holes and are more than likely not the best code you have ever seen but it is the ideas these examples show that should be taken.

Standard
Principles, SOLID

SOLID – Single Responsibility Principle (SRP)

As stated previously… I am getting (or trying to get) back to basics.

It is my belief that developers have to often times refactor the way they think and the way they approach things from time to time to make sure that the basics and the principles are still strong.

So let’s take a look at one of the principles in SOLID; Single Responsibility Principle (SRP)

SRP simply states:

There should be one and only one reason for a class to change

Um… yeah! That makes sense… I guess

So what types of change are we really talking about when dealing with SRP?

This is a question that I have always had trouble answering for two reasons: 1) didn’t really understand SRP to begin with and 2) my focus was always in the wrong area. I have always understood SRP through examples of classes that violated SRP in that it would take someone to state that a given class was violating SRP and why. Then I would simply remember that pattern or example and avoid it rather than taking the time to learn what it meant. When I started taking the time to learn it and gain a better understanding I started to take things too literal. (If I needed to change a method in a class was that violating SRP?)

What I started to do was to think about things as a whole. In other words, while “change” is a very important word in the definition of SRP, the word “class” was what I was missing. When I finally took the word “class” into context… I had my “ah ha” moment (it was really like a “duh” moment).

Ah ha…!

Ok, great. So what does that mean?

The word “class” is a little tricky beast that can mean so many things to different people at different times that I feel it losses it’s importance. Case in point, I find my self interchanging the word “object” with “class” as in “new up a StringBuilder class.” While I don’t think that I will ever stop doing that or stop using the word “class” in my everyday vernacular, I think that word “class” in terms of SRP needs to be changed to “concern.”

So I started to take the common (or the one most popularized) definition of SRP and replace “class” with “concern”:

There should be one and only one reason for a concern to change

Wait for it… ah ha! By making this contextual change I started to realize that my classes needed to be responsible for a single concern.

Now I could start looking at classes in terms of their concern. Thinking about a class that dealt with a Customer object and it’s database interactions became a concern. And with that thinking I realized that the class had one responsibility, interacting with the database for the Customer object. So now the only reason for the class to change was to change the way the Customer object interacted with the database.

Standard
.Net, Windows Live Writer

WLW Plugin for WordPress.com – Part 1

As stated in my previous post, I have been looking for a plug-in for WLW that would allow me to take advantage of the built in source code highlighter that is available from WordPress.com (the free on-line version). Not being able to find one I decided to write one for myself.

Not knowing where to begin or how to start, I searched for how to build a plug-in for WLW and came across Rick Strahl’s post about creating a WLW plug-in using WPF and decided to do a similar thing. I was fairly confident in my abilities to write a little WPF app but knew nothing about the WLW plug-in architecture so I started there.

For what I needed to do, writing a plug-in was actually really straight forward. I simply added a reference to the “WindowsLive.Writer.Api” assembly, created a class and inherited from the ContentSource class (which inherits from the WriterPlugin class). Looking at the ContentSource class I found that there were three virtual methods that I could choose from: 1) CreateContent, 2) CreateContentFromLiveClipboard, and 3) CreateContentFromUrl. Not knowing what any of these methods did, I choose to override the CreateContent method.

using System;
using WindowsLive.Writer.Api;
using System.Windows.Forms;

namespace SourceCodePlugin {
  public class Plugin : ContentSource {
    public override DialogResult CreateContent(IWin32Window dialogOwner, ref string content) {
      return DialogResult.OK;
    }
  }
}

Now knowing that I could create a WLW plug-in I thought about what I wanted the plug-in to do and how it was going to act. In really basic terms, I wanted to wrap what ever “code” I wrote with “[ sourcecode language=”csharp” ]<–code–>[ /sourcecode ]” as the WordPress.com site had suggested.

Thinking about it a little more, I wanted to ensure that the “code” appeared exactly the way I entered it so… it was clear that I needed to wrap the whole thing with “<pre></pre>” tags. So I wrote a little method to do just that.

public class Plugin : ContentSource {
  ...
  private string FormatOutput(string language, string code) {
    var builder = new StringBuilder();
    builder.AppendLine("&lt;pre&gt;");
    builder.AppendFormat("[ sourcecode language=\"{0}\" ]{1}[ /sourcecode ]",
      language, code);
    builder.AppendLine();
    builder.AppendLine("&lt;/pre&gt;");
    return builder.ToString();
  }
}

I decided to give that a shot so I built the project, deployed the assembly to my “Plugins” folder and started Windows Live Writer.

Sure enough… it didn’t work. I totally forgot about the two attributes that you need to add to your class in order for WLW to load your plug-in. Referencing back to Rick’s post I also realized that I should create an image to make it look like all of the others.

[WriterPlugin(
  "9EDA38F6-AE13-4003-B74A-83E8474F528D", 
  "Wordpress Sourcecode Plugin",
  Description = "A  plugin for WordPress.com blogs",
  PublisherUrl = "https://meisinger2.wordpress.com/",
  ImagePath = "Images.SourceCode.png",
  HasEditableOptions = false)]
[InsertableContentSource("Wordpress Sourcecode Plugin")]
public class Plugin : ContentSource {
  ...
}

After adding that and building it again, sure enough I had my “Hello World” code getting inserted into WLW through my plug-in

Next steps… integrating WPF

Edit: It appears that WordPress.com “sourcecode” bracket magic is a little too good… I had to edit this post and put a space between the bracket (“[” and “]”) and the word “sourcecode” in order for it to come up propertly

Standard
.Net, Windows Live Writer, WPF

Windows Live Writer Plugin for WordPress.com [sourcecode] Highlighter

Recently been wanting to blog more and more about code and give my posts some more punch by providing some code samples. The one thing that I always notice about other blog posts were the nice little syntax highlight boxes for code. You know the one that has the line numbers and allows you to copy to the clipboard or print.

So I set out to get my hands on a syntax highlight plugin that I could use and found a lot of them out there are really neat and well put together. One of the really important things for me was to also find a plugin for Windows Live Writer (which is simply one of the best tools). So long story short, I found my plugin’s and was ready to go.

One small problem, I am blogging on WordPress.com.

So that means, no pluggin directory, no JavaScript files, nothing. I did some reading on the WordPress.com website and found out that they do have and support a syntax highlighter for code. Wow… this was great. Now the only thing left was to find a plugin for Windows Live Writer that would work with this type of syntax highlighter.

If you try to search the web for “Syntax Highlighter”, “WordPress”, “Windows Live Writer”, and “Plugin” you will be presented with hundreds and hundreds of results. All of them talking about something that I couldn’t use, didn’t have, or didn’t want. I was really sad.

I came across a post by Rick Strahl covering some work he did on an Amazon book plugin for WLW using WPF and decided to rollup my sleeves and write my own. I mean think about it… writing a WLW plugin in WPF for a syntax highlighter that hasn’t been made yet (as far as I know anyway)… how cool is that!

So the next few posts will cover what I did to create the plugin and the issues that I ran into while creating it. And before I forget… I need to show of my plugin… The following code snippet was added using the plugin (of course) and shows one of the classes I created for the plugin. It is simply a name/value pair class that I use for the languages drop down list

public class SourceCodeLanguage
{
  private readonly string name;
  private readonly string value;

  public string Name
  {
    get { return name; }
  }

  public string Value
  {
    get { return value; }
  }

  public SourceCodeLanguage(string name, string value)
  {
    this.name = name;
    this.value = value;
  }
}

How cool is that? Well, maybe it isn’t something to write home about but… nah… it is. Currently the list of features this plugin has is really small. I really wanted to get it up and running and prove to myself that I could do it before getting into too many bells and whistles. Features:

  • Selectable indent size (2, 4, 6)
  • Changing the indent size re-formats the “code” sample
  • Selectable “code” language (e.g. C#, Ruby, Python, etc..)
  • All languages supported by WordPress.com are available
Standard
Unit Testing

Better Unit Testing and TDD

I just got done watching Rob Conery’s latest installment in his Kona series. I have to say that I like the direction that he is going with it and I hope that he continues producing great screen casts.

After watching the video, however, I noticed some of the comments that were made by others and started to get really frustrated over how developers view unit testing and practicing TDD.

I am not saying that I am the end-all-be-all when it comes to unit testing and TDD. Far from it… lord knows that I have worked on projects where I didn’t produce a single unit test and instead relied on firing up a browser and stepping through the application to "test" the code.

I guess the thing that frustrates me the most is when a developer decides to start practicing TDD or they decide that there is enough benefit from writing unit tests only to later throw their hands up in disgust and (understandably) frustration when it is not working the way they thought it would or how some other blogger showed them how easy it was to write unit tests and practice TDD.

It is my belief that most books, articles, screen casts, blog posts, etc… about unit testing and TDD take the wrong approach. Sure, it would be totally awesome if we could all be put on "green field" projects and new code bases where we are starting from scratch. The reality is, however, that most of us are brought on to existing projects and existing code bases where no testing has been done or if it has… it has been abandoned.

So what is a developer to do? The answer is really simple… write unit tests and start practicing TDD.

The one part of Rob’s screen cast that I liked was when he (quickly) covered the unit tests that he wrote for the existing Shopping Cart application. While I wish he would have spent a little more time on it, I think that he really hit on what a developer should be doing when trying to write unit tests and performing TDD on an existing code base.

Start from the Story and Requirements

The point of the matter is that if you start from the story, requirements, or business case then you can start to get a clearer understanding of what it is that needs to be tested and where to start (regardless of if this a green field project or an existing code base).

Some times you might get stuck and not know where to start even after gathering the requirements or reading the stories. This is a clear indication that you don’t know the full story in which case you have a couple of options: 1) assume that you know what is going on or 2) ask. I think where a lot of people get into trouble is when they start assuming things.

Assumptions – How bad Tests start

Let’s watch what happens when you assume (besides the age old saying of making an ass out of you and me).

You receive (or you read) a story which states "the Company [object] must have the ability to add a User [object]" and you go off and write the following code:

[Test]
public void When_Adding_User_UserCount_Is_1() {
var customer = new Customer();
var user = new User();

customer.AddUser(user);

Assert.AreEqual(1, customer.UserCount);
}

 

After you fix the compile errors, etc… you run the test and it fails since you have not implemented the AddUser method yet. So you then start to implement the method and you assume that you are going to store the User in a collection. You then further assume that you are going to want to retrieve the User so you decide to create a Dictionary. You make another assumption that the Id property from the User will be used as the key for the Dictionary. Remembering that you still have to satisfy the test, you change the UserCount property to return the count from the Dictionary. Then finally… you make one last assumption, the GetUser method. You write and implement the GetUser method to take an Integer and return the User object from the Dictionary. Just to be safe, you write a test to prove that after you add the User, you can get the User from the Company object.

Assumptions – So what went wrong?

So what went wrong here? Everything works and all of your tests pass so… what is the deal?

The assumptions are the deal. First you have assumed that you need to store the User in a collection. Nothing about the story or requirement indicated that this needed to be done. After that assumption comes all of the other decisions that were not warranted. Finally the big nasty assumption that the User will need to be retrieved and the API created to accomplish it.

With all of those assumptions made, you have coded and unit tested yourself and every other developer on your team (present and future) into a corner. Not only is there no need to have a GetUser method at this time but you run the risk of the method becoming "supported" because other developers now use it to get User objects.

What is worst of all is that there is code now available that isn’t backed by a story or requirement.

Conclusion

So back to my original point. Writing unit tests and practicing TDD is not as hard as people make it out to be as long as you follow the stories and requirements and don’t make assumptions.

Perhaps that is wrong to state. Assumptions are fine when you are assuming how something will work like how the Customer object will be reconstituted from a database some where. The details aren’t important but it is safe to assume that there will be some data access method some where in the framework or code that will handle the retrieval of the Customer object for you. Other assumptions that are integration assumptions are also fine since the details have more than likely not been ironed out yet.

Assumptions about the test and the functionality needed for the application, however, are bad

Standard
Uncategorized

Nothing lost but time

It has been a while since I last posted anything.

During this hiatus I have been working on several things that have been really interesting. Unfortunately non of which has been in the .Net world. Yup… you guessed it, I have been off working in the Java world for the last year. And while I kept up with the going’s on in the .Net world (or at least tried too), there was never enough time to keep my head wrapped around the Java work while continuing to dive into my beloved .Net world.

Now that my hiatus is coming to a close, I am looking forward to taking deeper dives into some of the newer frameworks and technologies that have been introduced lately.

Standard
.Net, ASP.Net, MVC

Handling Validation Errors in MVC (a different approach)

I just got done reading Scott Guthrie‘s and Phil Haack’s posts on the MVC Preview 4 release and there was one little piece in the “What’s Next” section that really peeked my interest. As it turns out the MVC guys are figuring out how to tackle the problem with handling validation errors and reporting them back to the user. How great is that? I don’t know about you but validation errors are one of the worst things to have to deal with when it comes to a web based application.

As we all know you should never rely on client side validation and you should always validate input (especially user input) prior to calling any business methods or database calls. My problem has always been with trying to get the validation messages back to the client. I am always determined to have my validation routines in my business layer. But then comes time to report validation errors back to the client and I end up sticking them in the code behind. Sure I might (emphasis on might) create a utility or helper class but then the routines become more and more specific and less and less common and I am right back to sticking them in the code behind.

Where else can you put them since you not only have access to the control but you also have all the tools you need to render the output?

While I have been playing with MVC I have found myself once again struggling with sending validation messages back to the user. This time, however, I decided to try a few different techniques and one has proven to work well (for me at least).

I first started off creating a class to store my validation messages. Since my primary focus is capturing form related validation errors I decided to add a PropertyInfo property that will give me some more context later on if I need it.

 image

So now that I have a class that contains a validation message with some extra info layered in I turn my attention to how to store the errors. At first I decided to make a single collection that would be used as the return type of my validation routines but quickly found it to be too restrictive. I decided to leverage the HttpContext.Items collection and the CallContext class instead. The HttpContext.Items collection for web based usage and the CallContext for unit testing. To isolate myself from these details I created a little wrapper class to manage the switching between web usage and unit testing.

 image

This class uses generic methods so I can strongly type the objects being stored.
With that out of the way I created another class specific to my validation storage which does nothing more than make calls to the ThreadContext class.

 image

Finally I create a class that handles the addition and retrieval of the validation messages.
Let’s first take a look at the constructor for this class.

 image

As you can see I first create a new collection to store the validation messages. Next I check to see if a ValidationStorage class already exists and if so I set the existing instance to the Parent property (more on this later). Finally I make the instance the Current object in the ValidationStorage class. I could have easily used a Stack of Validator but rather than popping and pushing I decided to take this approach instead.

Now let’s turn our attention to the Dispose method.

 image

As you can see here when I dispose the Validator object I check to see if the instance has a Parent and if it does I take it’s Details and add them to Parent.Details.

Now on to the properties. Nothing much going on here but in order to understand what the methods are doing you will need to know the properties that are available.

image

The Current and Exists properties make calls to the ValidationStorage class. The Failed property will return “false” if a Validator does not exist in the ValidationStorage. Later on you get a better understand of why these properties are static.

On to the instance methods.

image

The HasMessages method allows me to check to see if I have any ValidationDetail for a given property by name. And if there are messages then I can call GetMessage or GetMessages.

Finally the static methods. These methods are what will be accessed from within the validation routines.

image

Thee methods add the ValidationDetail object to the Details collection. Prior to adding it, however, I check to see if there is an existing Validator available to use and if not I new up a new instance. The Error and Exception methods will also pass in a boolean to the AddDetail method to indicate that validation has failed.

So now let’s take a look at how to use this. For simplicity assume that there is a controller that performs some basic validation routines against a simple model. Let’s first take a look at the model.

image

The controller then needs to have a few validation routines so let’s look at those now.

image

As you can see here when a validation error occurs I simply call the static method Error and that’s it. But how does it convey the messages back to the client? This can bee seen in the following code.

image

After the controller calls the validation routines it makes a call to the static Failed property of the Validator class which will indicate whether or not validation has failed (obviously). If it has failed validation then I simply render the Edit view again. Within the Edit view a check is made to see if a Validator exists using the Exists property and if so the the ValidatioDetail objects can be blindly displayed or a check against per property can be made for a more contextual error messages.

image

One key thing that I think really makes this work well is the ability that this gives to call the Validator from almost anywhere in my code. Validation routines can now reside within the business layer like they should. And since the ThreadContext is in place web services can use and implement the same checks that are done in the controller.

While I think this does the job I also feel that there can be some things improved upon or added to really make it shine. For instance:

  • Adding a severity property which would indicate if the client has entered something really harmful and allow for an exception page to be rendered
  • Changing the Details collection to a Dictionary to easily store multiple validation errors per property or data element
  • Add an Html extension method to deal with the checking and displaying of validation messages

Any ideas or comments are welcomed.

kick it on DotNetKicks.com

Standard