WCF Podcast with me

Saturday, 24 October 2009 01:52:18 UTC

Daniel Frost has published a podcast where he discusses WCF with me. It's about half an hour and in Danish. Hear it here.


Writing a book

Monday, 05 October 2009 18:13:50 UTC

For the last few months I've been writing a book for Manning tentatively titled Dependency Injection in .NET. The page about the book is now live at the Manning web site where you can read more about it and, if you would like, purchase an Early Access edition and read the chapters as they are being written.

If you have ever wanted to learn about Dependency Injection (DI) related to .NET, here's your chance!

At the moment I'm about a third of the way into the book, so there's still some way to go, but I hope to be done with it in 2010.

If you decide to purchase an Early Access edition, I'd love to receive your feedback in the online forum.


Comments

Ohh, I could have used this book weeks ago! I've been trying to wrap my head around DI/IoC for some time, and in fact am working on a blog post on the subject. It seems complex on the surface, but is less so once you really get into it!

Purchased the MEAP, looking forward to the results!
2009-10-07 03:01 UTC
I hope that you get a lot out of it! If parts of the contents strike you as odd or you think that something is missing, please let me know. The Author Online forum is the preferred place, but you can drop me a line in any way you prefer.
2009-10-13 11:00 UTC
Bill Campbell
Hey Mark,

Got the MEAP of your book and am enjoying it. I was wondering if you are going to make any of the sample code from the book available? That would be awesome.

thanks,
Bill
2009-10-21 12:32 UTC
Yes, that is definitely the plan. Manning does have the code, but I don't know when they plan on making it available. It's still a little rough around the edges, but if you would like to get it now, send me an email (use the small envelope icon in the Contact section area) and I'll zip it up for you.
2009-10-21 12:55 UTC
Scott Peterson
Hello Mark,

While your book is now a couple of years old, I purchased an e-version of it and got a lot out of it. I saw immediate uses for interceptors in an application I am evaluating (for a re-write) at a new company, but I ran into some trouble.
In a copy of your ProductManagementClient code, in a MenuItem_Click event, I added code to purposefully throw an InvalidOperationException, one of the exception types listed in the ErrorHandlingInterceptor, just to see the interceptor in action. I then tried to step through the code, but I never got to the Interceptor; I always just see the standard Visual Studio exception dialog in Debug mode.
Am I approaching this incorrectly?

Thanks for all that you do for the .NET community; it has really been a big help to me.

Scott
2013-05-23 18:31 UTC

Scott, thanks for writing. The Visual Studio behaviour you describe fits my own experience: stepping into something Decorated with a dynamic interceptor doesn't really work. While I'm no expert in how the Visual Studio debugger works, I think it's because there's some auto-generated code (the dynamic interceptor(s)) between the call site and your code on the other side. Visual Studio doesn't have the source code for the dynamic interceptor, so it generally gives up when you try to do that.

However, if you set a breakpoint on the other side (behind the interceptors), you will still hit that breakpoint when you press F5. This should enable you to still 'see' the interceptor(s) in action, using the debugger. IIRC, you can also set breakpoints in your own interceptor code, and those should be hit as well.

As I wrote, I'm no expert in the Visual Studio debugger, but I do know that it has lots of options you can tweak. I wouldn't be surprised if there was an option that would enable you to skip over the interceptor code and into the code Decorated by the interceptor, but I don't know how to do that.

2013-05-23 19:07 UTC

SOLID or COLDS?

Tuesday, 29 September 2009 19:38:42 UTC

The SOLID principles of OOD as originally put forth by Robert C. Martin make for such a catchy acronym, although they seem to originally have been spelled SOLDI.

In any case I've lately been thinking a bit about these principles and it seems to me that the Single Responsibility Principle (SRP) and the Interface Segregation Principle (ISP) seem to be very much related. In essence you could say that the ISP is simply SRP applied to interfaces.

The notion underlying both is that a type should deal with only a single concept. Whether that applies to the public API or the internal implementation is less relevant because a corollary to the Liskov Substitution Principle (LSP) and Dependency Inversion Principle (DIP) is that we shouldn't really care about the internals (unless we are actually implementing, that is).

The API is what matters.

Although I do understand the subtle differences between SRP and ISP I think they are so closely related that one of them is really redundant. We can remove the ISP and still have a fairly good acronym: SOLD (although SOLID is still better).

There's one principle that I think is missing from this set: The principle about Command/Query Separation (CQS). In my opinion, this is a very important principle that should be highlighted more than is currently the case.

If we add CQS to SOLD, we are left with some less attractive acronyms:

  • SCOLD
  • COLDS
  • CLODS

Not nearly as confidence-inspiring acronyms as SOLID, but nonetheless, I'm striving to write COLDS code.


Customizing A Type's Builder With AutoFixture

Tuesday, 22 September 2009 14:53:48 UTC

In the previous post on AutoFixture, I demonstrated how it's possible to use a customized Builder to perform complex initialization when requesting an instance of a particular type. To recap, this was the solution I described:

var mc = fixture.CreateAnonymous<MyClass>();
var mvm = fixture.Build<MyViewModel>()
    .Do(x => x.AvailableItems.Add(mc))
    .With(x => x.SelectedItem, mc)
    .CreateAnonymous();

This code first creates an anonymous instance of MyClass that can be added to MyViewModel. It then initializes a Builder for a specific instance of MyViewModel, instructing it to

  1. add the anonymous MyClass instance to the list of AvailableItems
  2. assign the same instance to the SelectedItem property

While this works splendidly, it can get tiresome to write the same customization over and over again if you need to create multiple instances of the same type. It also violate the DRY principle.

When this is the case, you can alternatively register a customized Builder pipeline for the type in question (in this case MyViewModel). This is done with the Customize method:

var mc = fixture.CreateAnonymous<MyClass>();
fixture.Customize<MyViewModel>(ob => ob
    .Do(x => x.AvailableItems.Add(mc))
    .With(x => x.SelectedItem, mc));

The Customize method takes as input a function that provides an initial ObjectBuilder as input, and returns a new, customized ObjectBuilder as output. This function is registered with the type, so that each time an anonymous instance of the type is requested, the customized ObjectBuilder will be used to create the instance.

In the example, I customize the supplied ObjectBuilder (ob) in exactly the same way as before, but instead of invoking CreateAnonymous, I simply return the customized ObjectBuilder to the Fixture instance. It then saves this customized ObjectBuilder for later use.

With this customization, what before failed now succeeds:

var mvm = fixture.CreateAnonymous<MyViewModel>();

The Customize method is the core method for customizing AutoFixture. Most other customization methods (like Register) are simply convenience methods that wraps Customize. It is a very powerful method that can be used to define some very specific Builder algorithms for particular types.


Comments

Scott Peterson

I posted this to CodePlex without properly thinking it through, but am now posting here which should be closer to where it belongs.

I have the following class that I am trying to test:

public class License
    {
        public virtual DateTime DatePurchased { get; set; }
        public virtual int LicenseDuration { get; set; }
        public virtual EnumDatePeriod PeriodType { get; set; }
        public virtual bool InUse { get; set; }

        public DateTime ExpirationDate()
        {
            ILicenseCalculator calculator = CreateLicenseDurationBuilder(PeriodType);

            return calculator.CalculateLicenseDuration(DatePurchased, LicenseDuration);
        }

        public ILicenseCalculator CreateLicenseDurationBuilder(EnumDatePeriod datePeriod)
        {
            Dictionary<EnumDatePeriod, ILicenseCalculator> calculators = new Dictionary<EnumDatePeriod, ILicenseCalculator>();
            calculators.Add(EnumDatePeriod.Year, new YearLicenseCalculator());
            calculators.Add(EnumDatePeriod.Month, new MonthLicenseCalculator());
            calculators.Add(EnumDatePeriod.Week, new WeekLicenseCalculator());
            calculators.Add(EnumDatePeriod.Day, new DayLicenseCalculator());

            return calculators[datePeriod];
        }
    }

Specifically, I want to see if I have a license that was purchased more than X time periods ago, the expiration date calculates properly. For example, I have a test that is set up to use a 6 month license, with a purchase date from seven months ago. I am trying to force a certain date, so I got into customizing, and set up my test as follows:

[Fact]
        public void CanCalculateExpirationDateOnExpiredMonthlyLicense()
        {
            Fixture fixture = new Fixture();
            fixture.Customize<License>(x => x
                .With(b => b.DatePurchased == DateTime.Now.AddMonths(-7)));
            var sut = fixture.Create<License>();
        }

I realize that this isn't a complete test, but I ran it just to see what feedback I'd get, to make certain I was customizing properly. Looks like I'm not, because I get an error:

Result Message:    
System.ArgumentException : The expression's Body is not a MemberExpression. Most likely this is because it does not represent access to a property or field. 
Parameter name: propertyPicker 

Where have I gone wrong?

Thanks for your help.

2015-02-26 21:39 UTC

Scott, thank you for writing. In your expression b.DatePurchased == DateTime.Now.AddMonths(-7), what would you say the == does?

2015-02-27 7:35 UTC
Scott Peterson

Mark, I really must apologize; my post above was not meant to be published. I worked on this a long time ago and I must have committed it to my local repository. I am very aware of the difference between = and ==. This must have been a question I had when I first started looking at AutoFixture (and working with Git). Again, my apologies.

Scott

2015-03-01 19:41 UTC

AutoFixture .8.6 Released

Monday, 21 September 2009 17:37:36 UTC

Yesterday I released version .8.6 of AutoFixture. It is a minor release that simply adds some new features.

There are some minor breaking changes (documented on the release page), but they only affect supporting classes and don't touch on any of the code examples I have so far published. In other words, if you are using AutoFixture's fluent interface, your code should still compile.

Please go ahead and download it and use it. As always, comments and questions are welcome, either here or in the forum.


Self-updating AJAX links with ASP.NET MVC

Monday, 07 September 2009 18:14:39 UTC

How can you make an AJAX link that updates itself in ASP.NET MVC? My colleague Mikkel and I recently had that problem and we couldn't find any guidance on this topic, so now that we have a solution, I thought I'd share it.

The problem is simple: We needed a link that invoked some server side code and updated the text of the link itself based on the result of the operation. Here is a simplified example:

image

Each time you click the link, it should invoke a Controller Action and return a new number that should appear as the link text.

This is pretty simple to implement once you know how. The first thing to realize is that the link and all the AJAX stuff must be placed in a user control. The only thing that needs to go into the containing page is the containing element itself:

<h2>Self-updating AJAX link</h2>
Click the link to update the number:
<span id="thespan">
    <% this.Html.RenderPartial("NumberAjaxUserControl"); %>
</span>

Notice the id of the span element - this same id will be referenced from the user control.

To bootstrap this view, the Controller Action for the page contains code that assigns an initial value to the number (in this case 1):

public ActionResult Index()
{
    this.ViewData["number"] = 1.ToString();
    return this.View();
}

To keep the example simple, I simply add the number to the ViewData dictionary, but in any production implementation, I would opt to use a strongly typed ViewModel instead.

The NumberAjaxUserControl itself only contains the definition of the AJAX link:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="System.Web.Mvc.Ajax" %>
<%= this.Ajax.ActionLink((string)this.ViewData["number"],
    "GetNext",
    new { number = this.ViewData["number"] }, 
    new AjaxOptions { UpdateTargetId = "thespan" })%>

The first parameter to the ActionLink method is simply the current number to render as the link text. Since I'm using the untyped ViewData dictionary for this example, I need to cast it to a string.

The next parameter ("GetNext") indicates the Controller Action to invoke when the link is clicked - I will cover that shortly.

The third parameter is a Route Value that specifies that the parameter number with the correct value will be supplied to the GetNext Controller Action. It uses the number stored in ViewData.

The last parameter indicates the id of the element to update. Recall from before that this name was "thespan".

The only missing piece now is the GetNext Controller Action:

public PartialViewResult GetNext(int number)
{
    this.ViewData["number"] = (number + 1).ToString();
    return this.PartialView("NumberAjaxUserControl");
}

In this example I simply chose to increment the number by one, but I'm sure you can imagine that this method could just as well perform a database lookup or something similar.

Notice that the method returns a PartialViewResult that uses the same user control that I used to bootstrap the thespan element. This means that every time the link is clicked, the GetNext method is updated, and the exact same user control is used to render the content that dynamically replaces the original content of the element.


Comments

anonymous
I kind of prefer the jQuery approach, it is much less intrusive: you render your link as usual and then you use the "live" function:

$("a#some_link").live('click', function(){ $('#thespan').load(this.href); });

This will automatically watch for DOM updates of the anchor tag and if it detects any it will automatically rebind the click function.
2009-09-08 07:00 UTC
Thank you for your comment

It looks pretty simple. The following questions are entirely based on my total (and very deplorable) lack of JQuery knowledge:

Will this allow me to query the server with particular parameter values (the number parameter in my example)?
Will it allow me to update the link with the result from the server?

From your snippet, I can't really see where it is specified which URL is requested, what are the query parameters, how the returned result is used to update the link text, etc.
2009-09-08 08:16 UTC

AutoFixture .8.5 Released

Wednesday, 02 September 2009 20:21:13 UTC

It gives me great pleasure to announce that I have just release version .8.5 of AutoFixture. It is a minor release (hence the numbering) that mainly contains a lot of convenience overloads to already existing methods. There is also a single bug fix.

There are two breaking changes (documented on the release page), but they are minor and I do not expect them to cause problems. Only one of these even remotely affects any part of the API I have already discussed here, and that relates to what kind of exception is being thrown when AutoFixture is unable to create an instance of the requested type.

Please go ahead and download it and use it heavily :) As always, comments and questions are welcome.


Do Redux

Tuesday, 25 August 2009 18:27:39 UTC

Soon after I posted my post on the AutoFixture Custom Builder's Do method, a much better example occurred to me, so let's revisit this feature in light of a more reasonable context.

When I write WPF code, I always use the MVVM pattern. When I need to create a Master/Detail View, I usually model it so that my View Model has a list of available items, and a property that returns the currently selected item. In this way, I can bind the current Detail View to the currently selected item purely through the View Model.

Such a View Model might look like this:

public class MyViewModel
{
    private readonly List<MyClass> availableItems;
    private MyClass selectedItem;
 
    public MyViewModel()
    {
        this.availableItems = new List<MyClass>();
    }
 
    public ICollection<MyClass> AvailableItems
    {
        get { return this.availableItems; }
    }
 
    public MyClass SelectedItem
    {
        get { return this.selectedItem; }
        set 
        {
            if (!this.availableItems.Contains(value))
            {
                throw new ArgumentException("...");
            }
            this.selectedItem = value;
        }
    }
}

The main point of interest is that if you attempt to set SelectedItem to an instance that's not contained in the list of available items, an exception will be thrown. That's reasonable behavior, since we want the user to select only from the available items.

By default, AutoFixture works by assigning an Anonymous Value to all writable properties. Since these values are auto-generated, the value AutoFixture is going to assign to SelectedItem will be a new instance of MyClass, and thus not one of the available items. In other words, this will throw an exception:

var mvm = fixture.CreateAnonymous<MyViewModel>();

There are several solutions to this situation, depending on the scenario. If you need an instance with SelectedItem correctly set to a non-null value, you can use the Do method like this:

var mc = fixture.CreateAnonymous<MyClass>();
var mvm = fixture.Build<MyViewModel>()
    .Do(x => x.AvailableItems.Add(mc))
    .With(x => x.SelectedItem, mc)
    .CreateAnonymous();

This first creates an anonymous instance of MyClass, adds it to AvailableItems as part of a customized Builder pipeline and subsequently assigns it to SelectedItem.

Another option is to skip assigning only the SelectedItem property. This is a good option if you don't need that value in a particular test. You can use the Without method to do that:

var mvm = fixture.Build<MyViewModel>()
    .Without(s => s.SelectedItem)
    .CreateAnonymous();

This will assign a value to all other writable properties of MyViewModel (if it had had any), except the SelectedItem property. In this case, the value of SelectedItem will be null, since it is being ignored.

Finally you can simply choose to omit all AutoProperties using the OmitAutoProperties method:

var mvm = fixture.Build<MyViewModel>()
    .OmitAutoProperties()
    .CreateAnonymous();

In this scenario, only MyViewModel's constructor is being executed, while all writable properties are being ignored.

As you can see, AutoFixture offers great flexibility in providing specialized custom Builders that fit almost any situation.


Comments

Murali
Hi Mark,

Can you please help in creating the class which has an array of other types. With Autofixture , the array size is default to 2 null tems.

For eg:

Here is the my class definition:

class MyClassA
{

public MyClassB[] items;
public MyClassC c;
public MyClassD d;
}

class MyclassB
{
public int x;
public string y;

}
when i use Autofixture for creating MyClass c,d are created and b array with 2 items but with each item null instead of intantiated MyclassB objects. How do i get an Myclass with MyclassB array .
Thanks for your help in advance.

Murali
2009-12-04 22:00 UTC
Hi Murali

Thank you for your question! It prompted me to write a new blog post that provides possible solutions to your question: Building and assigning arrays with AutoFixture.

I hope it answers your question. If not then please write again.
2009-12-05 00:45 UTC
Simple
Hi Mark,

which MVVM Frameworks do you prefer? Or if you dont use Framerworks - which one can you recommend?
2012-05-10 13:22 UTC
FWIW, I've found Knockout.js pretty decent so far, but that's probably not what you had in mind?

For WPF, I don't think an additional framework is warranted for MVVM; for Silverlight, I have no opinion.
2012-05-10 15:02 UTC
Simple
Yes you are right - my question was about MVVM Framework for WPF.. )

2012-05-10 20:16 UTC
Simple
Hello again Mark!

Do you use some kind of GUI-Tests? To simulate users cliks etc..

2012-05-14 07:09 UTC
2012-05-14 08:23 UTC

Omitting Only Certain Properties With AutoFixture

Monday, 17 August 2009 19:33:40 UTC

The default behavior of AutoFixture is to create an Anonymous Variable by assigning a value to all writable properties of the created instance. This is great in many scenarios, but not so much in others. You can disable this behavior by using the OmitAutoProperties method, but sometimes, you would like most of the writable properties set, except one or two.

Consider this simple Person class:

public class Person
{
    private Person spouse;
 
    public DateTime BirthDay { get; set; }
 
    public string Name { get; set; }
 
    public Person Spouse 
    {
        get { return this.spouse; }
        set
        {
            this.spouse = value;
            if (value != null)
            {
                value.spouse = this;
            }
        }
    }
}

The main trouble with this class, seen from AutoFixture's perspective, is the circular reference exposed by the Spouse property. When AutoFixture attempts to create an anonymous instance of Person, it will create anonymous values for all writable properties, and that includes the Spouse property, so it attempts to create a new instance of the Person class and assign values to all public properties, including the Spouse property, etc.

In other words, this line of code throws a StackOverflowException:

var person = fixture.CreateAnonymous<Person>();

If you would still like to have anonymous values assigned to Name and BirthDay, you can use the Without method:

var person = fixture.Build<Person>()
    .Without(p => p.Spouse)
    .CreateAnonymous();

This will give you an anonymous instance of the Person class, but with the Spouse property still with its default value of null.

Several calls to Without can be chained if you want to skip more than one property.


A Fluent Interface For Testing INotifyPropertyChanged

Thursday, 06 August 2009 17:58:36 UTC

If you are doing Rich UI, INotifyPropertyChanged is a pretty important interface. This is as true for WPF as it was for Windows Forms. Consisting solely of an event, it's not any harder to unit test than other events.

You can certainly write each test manually like the following.

[TestMethod]
public void ChangingMyPropertyWillRaiseNotifyEvent_Classic()
{
    // Fixture setup
    bool eventWasRaised = false;
    var sut = new MyClass();
    sut.PropertyChanged += (sender, e) =>
        {
            if (e.PropertyName == "MyProperty")
            {
                eventWasRaised = true;
            }
        };
    // Exercise system
    sut.MyProperty = "Some new value";
    // Verify outcome
    Assert.IsTrue(eventWasRaised, "Event was raised");
    // Teardown
}

Even for a one-off test, this one has a few problems. From an xUnit Test Patterns point of view, there's the issue that the test contains conditional logic, but that aside, the main problem is that if you have a lot of properties, writing all these very similar tests become old hat very soon.

To make testing INotifyPropertyChanged events easier, I created a simple fluent interface that allows me to write the same test like this:

[TestMethod]
public void ChangingMyPropertyWillRaiseNotifyEvent_Fluent()
{
    // Fixture setup
    var sut = new MyClass();
    // Exercise system and verify outcome
    sut.ShouldNotifyOn(s => s.MyProperty)
        .When(s => s.MyProperty = "Some new value");
    // Teardown
}

You simply state for which property you want to verify the event when a certain operation is invoked. This is certainly more concise and intention-revealing than the previous test.

If you have interdependent properties, you can specify than an event was raised when another property was modified.

[TestMethod]
public void ChangingMyPropertyWillRaiseNotifyForDerived()
{
    // Fixture setup
    var sut = new MyClass();
    // Exercise system and verify outcome
    sut.ShouldNotifyOn(s => s.MyDerivedProperty)
        .When(s => s.MyProperty = "Some new value");
    // Teardown
}

The When method takes any Action<T>, so you can also invoke methods, use Closures and what not.

There's also a ShouldNotNotifyOn method to verify that an event was not raised when a particular operation was invoked.

This fluent interface is implemented with an extension method on INotifyPropertyChanged, combined with a custom class that performs the verification. Here are the extension methods:

public static class NotifyPropertyChanged
{
    public static NotifyExpectation<T>
        ShouldNotifyOn<T, TProperty>(this T owner,
        Expression<Func<T, TProperty>> propertyPicker) 
        where T : INotifyPropertyChanged
    {
        return NotifyPropertyChanged.CreateExpectation(owner,
            propertyPicker, true);
    }
 
    public static NotifyExpectation<T> 
        ShouldNotNotifyOn<T, TProperty>(this T owner,
        Expression<Func<T, TProperty>> propertyPicker)
        where T : INotifyPropertyChanged
    {
        return NotifyPropertyChanged.CreateExpectation(owner,
            propertyPicker, false);
    }
 
    private static NotifyExpectation<T>
        CreateExpectation<T, TProperty>(T owner,
        Expression<Func<T, TProperty>> pickProperty,
        bool eventExpected) where T : INotifyPropertyChanged
    {
        string propertyName =
            ((MemberExpression)pickProperty.Body).Member.Name;
        return new NotifyExpectation<T>(owner,
            propertyName, eventExpected);
    }
}

And here's the NotifyExpectation class returned by both extension methods:

public class NotifyExpectation<T>
    where T : INotifyPropertyChanged
{
    private readonly T owner;
    private readonly string propertyName;
    private readonly bool eventExpected;
 
    public NotifyExpectation(T owner,
        string propertyName, bool eventExpected)
    {
        this.owner = owner;
        this.propertyName = propertyName;
        this.eventExpected = eventExpected;
    }
 
    public void When(Action<T> action)
    {
        bool eventWasRaised = false;
        this.owner.PropertyChanged += (sender, e) =>
        {
            if (e.PropertyName == this.propertyName)
            {
                eventWasRaised = true;
            }
        };
        action(this.owner);
 
        Assert.AreEqual<bool>(this.eventExpected,
            eventWasRaised,
            "PropertyChanged on {0}", this.propertyName);
    }
}

You can replace the Assertion with one that matches your test framework of choice (this one was written for MSTest).


Comments

PeteB
I'm never played with modifying/creating a fluent interface; how can this be extended to check for multiple NotifyProperty events (and NOT events)?

e.g.
sut.ShouldNotifyOn(s => s.MyProperty).AndOn(s => s.MyDependentProperty).AndNotOn(s => s.MyIndependentProperty)
.When(s => s.MyProperty = "Some new value");
2012-08-06 11:39 UTC
Would that add more value than three individual tests?
2012-08-06 11:52 UTC

Page 36 of 40

"Our team wholeheartedly endorses Mark. His expert service provides tremendous value."
Hire me!