# Monday, June 22, 2009

About a year ago, one of my readers asked me about how to make custom tokens work over TPC in WCF. Here's the question again:

"i'm trying to implement the CustomToken over tcp. The original used the SymmetricSecurityBindingElement and the transport http, this works fine, but when i change URI's and and the transport, it gives an error saying:

"Binding 'CustomBinding' doesn't support creating any channel types. This often indicates that the BindingElements in a CustomBinding have been stacked incorrectly or in the wrong order. A Transport is required at the bottom of the stack. The recommended order for BindingElements is: TransactionFlow, ReliableSession, Security, CompositeDuplex, OneWay, StreamSecurity, MessageEncoding, Transport."

As it turns out, this seems to be a general issue with more transports than just TCP – at least, I've seen the exact same behavior for the Named Pipes transport.

When I originally received the question, it seemed that no-one knew the answer, and neither did I. Now, about a year later, I've managed to find a solution, and it's really simple.

If you build up your CustomBinding in code, all you need to do is set the TransferMode property to Streamed:

var pipeTransport = new NamedPipeTransportBindingElement();
pipeTransport.TransferMode = TransferMode.Streamed;

In this example, I'm setting the property on a Named Pipe transport, but you can do exactly the same with a TCP transport.

Although I wasn't able to find any documentation to that effect, experimentation seems to indicate that you can also set the property in a .config file (at least, it works on my computer):

<namedPipeTransport transferMode="Streamed" />

I will not claim that I fully understand this fix/workaround, or that it applies in every situation, but I hope that it might prove helpful to some of my readers some day.

posted on Monday, June 22, 2009 9:48:42 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Saturday, June 20, 2009

It was only earlier this week that I released AutoFixture .8.2, but now I'm releasing version .8.3 – not that there was anything wrong with .8.2 (that I know of), but I had some time to implement new features, and I wanted to properly release those.

In the future I will blog about these new features (along with all the other AutoFixture features I haven't introduced yet).

Get it at the AutoFixture CodePlex site as usual.

posted on Saturday, June 20, 2009 10:34:30 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, June 18, 2009

Yesterday I created a new release (.8.2) of AutoFixture; this time with a new feature that I recently discovered that I needed, and about which I will blog later.

There are no breaking changes and no known bugs.

posted on Thursday, June 18, 2009 9:11:39 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, June 09, 2009

Previously, we saw how you can set property values while building anonymous variables with AutoFixture. While I insinuated that I consider this a somewhat atypical scenario, we can now safely venture forth to the truly exotic :)

Imagine that you want to build an anonymous instance of a type that requires you to call a certain method before you can start assigning properties. It's difficult to come up with a reasonable example of this, but although I consider it quite bad design, I've seen interfaces that include an Initialize method that must be called before any other member. In our example, let's call this interface IBadDesign.

Let's say that we have a class called SomeImp that implements IBadDesign. Here's the relevant part of the class:

#region IBadDesign Members
 
public string Message
{
    get { return this.message; }
    set
    {
        if (this.mc == null)
        {
            throw new InvalidOperationException("...");
        }
 
        this.message = value;
        this.transformedMessage = this.mc.DoStuff(value);
    }
}
 
public void Initialize(MyClass mc)
{
    this.mc = mc;
}
 
#endregion

This is a rather ridiculous example, but I couldn't think of a better one. The main point here is that given a brand-new instance of SomeImp, this usage is invalid:

something.Message = "Ploeh";

While the above code snippet will throw an InvalidOperationException, this will work:

something.Initialize(new MyClass());
something.Message = "Ploeh";

The problem is that by default, AutoFixture ignores methods and only assigns properties, which means that this is also going to throw:

var imp = fixture.CreateAnonymous<SomeImp>();

As we saw with properties, we can use the Build method to customize how the type is being created. Properties can be set with the With method, while methods can be invoked with the Do method, so this is all it takes:

var imp = fixture.Build<SomeImp>()
    .Do(s => s.Initialize(new MyClass()))
    .CreateAnonymous();    

We don't have to explicitly set the Message property, as AutoFixture is going to do this automatically, and all implicit assignments happen after explicit actions defined by With or Do (and in case you were wondering, you can mix With and Do, and ObjectBuilder<T> will preserve the ordering).

In most cases, having to use the Do method probably constitutes a design smell of the SUT, but the method is there if you need it.

posted on Tuesday, June 09, 2009 7:50:54 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Friday, June 05, 2009

Lately, several people have implied to me that I should consider start using Twitter, so here I am, with only a vague idea about what to do with it…

posted on Friday, June 05, 2009 9:12:49 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback

When I talk with people about TDD and unit testing, the discussion often moves into the area of Testability – that is, the software's susceptibility to unit testing. A couple of years back, Roy even discussed the seemingly opposable forces of Object-Oriented Design and Testability.

Lately, it has been occurring to me that there really isn't any conflict. Encapsulation is important because it manifests expert knowledge so that other developers can effectively leverage that knowledge, and it does so in a way that minimizes misuse.

However, too much encapsulation goes against the Open/Closed Principle (that states that objects should be open for extension, but closed for modification). From a Testability perspective, the Open/Closed Principle pulls object-oriented design in the desired direction. Equivalently, done correctly, making your API Testable is simply opening it up for extensibility.

As an example, consider a simple WPF ViewModel class called MainWindowViewModel. This class has an ICommand property that, when invoked, should show a message box. Showing a message box is good example of breaking testability, because if the SUT were to show a message box, it would be very hard to automatically verify and we wouldn't have fully automated tests.

For this reason, we need to introduce an abstraction that basically models an action with a string as input. Although we could define an interface for that, an Action<string> fits the bill perfectly.

To enable that feature, I decide to use Constructor Injection to inject that abstraction into the MainWindowViewModel class:

public MainWindowViewModel(Action<string> notify)
{
    this.ButtonCommand = new RelayCommand(p => 
    { notify("Button was clicked!"); });
}

When I recently did that at a public talk I gave, one member of the audience initially reacted by assuming that I was now introducing test-specific code into my SUT, but that's not the case.

What I'm really doing here is opening the MainWindowViewModel class for extensibility. It can still be used with message boxes:

var vm = new MainWindowViewModel(s => MessageBox.Show(s));

but now we also have the option of notifying by sending off an email; writing to a database; or whatever else we can think of.

It just so happens that one of the things we can do instead of showing a message box, is unit testing by passing in a Test Double.

// Fixture setup
var mockNotify = 
    MockRepository.GenerateMock<Action<string>>();
mockNotify.Expect(a => a("Button was clicked!"));
 
var sut = new MainWindowViewModel(mockNotify);
// Exercise system
sut.ButtonCommand.Execute(new object());
// Verify outcome
mockNotify.VerifyAllExpectations();
// Teardown

Once again, TDD has lead to better design. In this case it prompted me to open the class for extensibility. There really isn't a need for Testability as a specific concept; the Open/Closed Principle should be enough to drive us in the right direction.

Pragmatically, that's not the case, so we use TDD to drive us towards the Open/Closed Principle, but I think it's important to note that we are not only doing this to enable testing: We are creating a better and more flexible API at the same time.

posted on Friday, June 05, 2009 9:56:19 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, June 04, 2009

To make it a bit easier to get started with AutoFixture without having to trawl through all my blog posts, I've added a Cheat Sheet over at the AutoFixture CodePlex site.

As I add more posts on AutoFixture, I'll update the Cheat Sheet with the essentials. Please let me know if you think something's missing.

posted on Thursday, June 04, 2009 11:15:08 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, June 01, 2009

In my previous post I described how the Build method can be used to customize how a single anonymous variable is created.

A common customization is to set a property value during creation. In most cases, this can simply be done after the anonymous variable has been created (so the following is not an AutoFixture customization):

var mc = fixture.CreateAnonymous<MyClass>();
mc.MyText = "Ploeh";

By default, AutoFixture assigns anonymous values to all writable properties, but since they are writable, you can always explicitly give them different values if you care.

However, there are situations when a property is writable, but can't take just any value of its type. Sometimes this is a sign that you should reconsider your API, as I've previously described, but it may also be a legitimate situation.

Consider a Filter class that has Min and Max properties. To be semantically correct, the Min property must be less than or equal to the Max property. Each property is implemented like this:

public int Min
{
    get { return this.min; }
    set
    {
        if (value > this.Max)
        {
            throw new ArgumentOutOfRangeException("value");
        }
        this.min = value;
    }
}

When you ask AutoFixture to create an instance of the Filter class, it will throw an exception because it's attempting to set the Min property after the Max property, and the default algorithm for numbers is to return numbers in an increasing sequence. (In this example, the Min property is being assigned a value after the Max property, but AutoFixture has no contract that states that the order in which properties are assigned is guaranteed.) In other words, this throws an exception:

var f = fixture.CreateAnonymous<Filter>();

To solve this problem, we will have to customize the assignment of the Min and Max properties, before we ask AutoFixture to create an instance of the Filter class. Here's how to do that:

int min = fixture.CreateAnonymous<int>();
int max = min + 1;
var f = fixture.Build<Filter>()
    .With(s => s.Max, max)
    .With(s => s.Min, min)
    .CreateAnonymous();

The With method lets you specify an expression that identifies a property, as well as the value that should be assigned to that property. When you do that, AutoFixture will never attempt to assign an anonymous value to that property, but will instead use the value you specified.

In most cases, just creating a truly anonymous instance and subsequently explicitly assigning any significant values is easier, but using the Build method with one or more calls to the With method gives you the power to override any property assignments before the instance is created.

posted on Monday, June 01, 2009 2:35:18 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback