Some stuff about Web and .NET development
RSS icon Email icon Home icon
  • Dino Esposito @ Visug : C# 4.0 & testability

    Posted on October 17th, 2009 Thibaut 1 comment


    This last 8th of October, Dino Esposito, a very well known figure in the .NET world, came to the Visug to talk about C# 4.0 and testability. Here’s a summary about the session :

    Software testability

    Code should ideally guarantee :

    • Visibility of the current state
    • Control degree at which code allows to send input data for testing purposes
    • Simplicity of the code results in more reliable test results

    Introducing the .NET 4.0 code contracts API

    The ecosystem at a glance

    1. Code contracts library
    2. Rewriter
    3. Static checker
    4. Contract reference generator

    1. Code contracts API

    3 basic types of contracts :

    1. Preconditions
    2. Postconditions
    3. Invariants

    Exposed via the contracts class (System.Diagnostics.Contracts)

    2. Rewriter

    • Translates contracts into code
    • Modifies MSIL instructions to place contracts checks where they logically belong
    • Executable is ccrewriter.exe

    3. Static checker

    • Examines code without executing it and tries to prove that all the contracts are satisfied
    • Lists unproven contracts to fix, otherwise you should debug or cover it with unit tests
    • Detects if there’s a possibility of contract violation

    4. Assembly reference generation

    • Extracts contract information from source code and returns an assembly with contract-only information
    • Used by rewriter & static checker
    • Executable is ccrefgen.exe

    Steps of a method

    1. Check validity of parameters & stats
    2. Do real work
    3. Check of existing works
    4. Update state accordingly

    Set up

    1. Add reference to mscorlib
    2. Contract must be specified in the body of the methods
    3. Contracts are not mandatory. You can do without

    Preconditions, postconditions and invariants


    • Requires(bool condition)
    • Requires<TException>(bool condition) throws an exception if condition is not met
    • if-then-throw statements
    • RequiresAlways(bool condition) is like Requires but stripped off in retail builds


    • Ensures(bool condition), condition must be true at the end of the method
    • EnsuresOnThrow<TException>(bool condition), condition must be true if exception is thrown. Allows for checks even if exceptional return arises (network error, stack overflow, …)
    • Helper methods
      • Result<T>()
      • OldValue<T>(T variable)
      • ValueAtReturn<T>(out T variable)


    • Invariant(bool condition), object-wide condition that must hold for the lifetime of the class
    • All invariants for a class are defined in one place

    Best practice :

    • Define invariants before implementing the class
    • Express the conditions under which the object is in good state
    • Could be hard to add them at a later time

    Assert & assume

    • At runtime, fully equivalent to Debug.Assert
    • Static checker attemps to prove any Assert, emitting a warning if it fails
    • Static checker treats Assume as always true, adds the assumption to its collection of facts


    • Used to iterate a check on all elements of a list
    • ForAll(…), true if condition is met by all elements
    • Exists(…)

    Interface contracts

    • Define a separate class for the contract because we can’t add code to interface memebers (no mixins in C#)
    • Link to the interface via attribute

    Contracts & inheritance

    Contracts are inherited by derived classes, regardless wether you invoke base class methods in overrides

    Code contracts & debugging

    • When failure, contract raises
      • ContractFailedException
      • ContractFailedEventArgs
    • No default handler (thrown everytime)
    • Register handler to ContractFailedException at startup (Global.asax for ASP.NET, Main method for WinForms)

    Contract failures & unit tests

    • You don’t want contract exceptions in unit tests
    • Rather want exceptions to be reported as tests failures
    • SetHandled() to let assume exception has been handled and SetUnwind() to clear the stack


    • Code contracts as part of the design effort
    • Adds testability to classes & code
    • New API coming up in C# 4.0

    And one final important quote of Dino Esposito :

    “Testable code means that it exposes every significant part of it in order to check its correct behaviour”

    See you next time ;)


  • Visug : Building better user interfaces

    Posted on June 3rd, 2009 Thibaut 2 comments

    Microsoft Belgium

    The 27th of May was held the latest session of the Visug in the (beautiful) offices of Microsoft Belgium about user experience. Presented by Jason Beres from Infragistics, a company specializing in user interfaces and user experience, the covered topic aimed to introduce people how to build great user experiences. Here is the overview of the presentation that was given :

    • Understanding user experience
    • Using patterns for better user applications
    • Platform issues
    • Problems solved
    • Wrap up

    From the icon a user double clicks, the splash screen and the visual of the application he sees, the user experience is every touch point with the user. It’s the branding and the image of your company you give to people so it’s very important.

    “User experience (UX) is about making great software… for people !”. Think about the user who uses your application every day, maybe full time ! It has a big importance from the user point of view. So making great software is understanding user needs while providing exciting and revolutionary UX.

    One first important concern is “how to build what people want”. This is where you start to make great UX. For this, UX experts interview users to determine what they need (and understanding the difference between what they say and what they really need), study how they interact with software to determine how to architecture your app.

    Understanding user experience

    1. Information architecture

    • It’s about organizing principles. What do you want ? Where are you in the application ?
    • Deliverables : navigation maps, glossaries, keywords, categories, search strategies, …
    • Need to think about it up front because this is what will determine the final result

    2. Interaction design

    • Discover and refine stories : coherent, consistent and effective UX
    • Deliverables : storyboards, usage scenarios, sketches, wireframes and prototypes
    • All of this to determine how the user will be actually using your app

    3. Visual design + user interface

    • Establish visual framework and style, strenghten communication, establish trust
    • Deliverables : themes, styles, palettes, mockups, images, visual guidelines and patterns
    • Patterns : this will be the focus of today’s presentation

    Patterns and user experience

    We’re gonna see patterns about designing interfaces. First, two recommended readings from O’reilly :

    Designing interfaces Designing web interfaces

    A first advice is to avoid to overpattern (eg : “caution : stairs !”) where it’s obvious there are stairs isn’t an added value at all. Let’s now introduce some UX pattern. Each one features a name (eg : “iconic navigation” for the iPhone interface), a problem (when/why/context) and a solution (implementation/examples).


    • Prob : long lists of similar data (ex : search results)
    • Solution : present item grouped accross multiple pages

    Eg : the Flickr paging bar :


    Faceted navigation

    • Prob : multiple elements from different categories to list
    • Solution : present them organized in facets (groups of data)

    Eg : the faceted navigation in the shop section of Amazon

    Faceted navigation

    Clear entry points

    • Prob : need to make very clear to the user what the entry point is
    • Solution : provide a page with minimal design with the emphase of what needs user’s attention

    Eg : the Google homepage :

    Clear entry point

    A tip with clear entry points : it’s difficult to provide some application an entry point when there are many options available. Microsoft Expression Blend uses an interesting trick to cope with that : the first time you start the application, you’ve got a little menu as a clear entry point, with the possibility to check “hide this next time” when you’ll have discovered the application more in details, thanks to the clear entry point.

    Titled sections

    • Prob : you’ve got many sections and want to give the user a preview of each of them
    • Solution : provide clickable section names which redirects to the full section

    Eg : Yahoo news

    Titled sections

    Liquid layout

    • Prob : a lot of information to display so maximizing user’s screen usage is wanted
    • Solution : provide a resizable window enabling the content to adapt to it just like a liquid would do

    Eg : windows explorer

    Two panel selector

    • Prob : two panels containing large information must be displayed at the same time but the width is too small
    • Solution : implement a vertical or horizontal bar enabling to resize both panels when dragged

    Eg : the windows explorer again, allowing you to resize folders hierarchy or folders content

    Overview plus detail

    • Prob : must provide the user an overview of something but there are also plenty of details to show
    • Solution : implement a zoom-in/out functionality allowing to have overview but also details

    Eg : Google Maps

    Overview plus detail

    Alternative views

    • Prob : same information but can be presented in several different ways
    • Implement a view selector to let the user choose how he wants his information to be displayed

    Eg : windows display mode menu (thumbnails, small icons, medium icons, …)


    • Prob : the user can make wrong operations that need to be undone
    • Implement a undo functionality

    Eg : Gmail undo functionality :


    A note about undo : I’ve read from articles on the web (a topic called “human interface”) that undo is way way better than the typical alert/confirmation box. Indeed, you’re so used to click that “ok” button that if you make the wrong decision, you’re done. Following some study, there’s nothing more frustrating for users than loosing their work so being able to prevent that is the best you can do for them. And undo is just the perfect choice for that, completely worth its extra cost in terms of development.


    In addition to the two books listed before, some interesting web resources are :

    And last but not least, Quince, a really great UX Pattern explorer, developed by Infragistics and based on Silverlight.

    Wrap up

    • Build software for people
    • Use a process
    • Learn from patterns
    • Keep your eyes open

    And to finish, a very important information ! I’ve talked before the session with Pieter Gheysens (one of the founders of the Visug) who told me that Dino Esposito will be doing a session in October for the Visug. After Juval Lowy last fall, his colleague from IDesign will be teaching us some good architecture principles. So be sure not to miss him ! I’m currently reading one of his books .NET architecting applications for the enterprise which is really instructive !

    See you there !


  • Visug : Mocking

    Posted on May 9th, 2009 Thibaut 1 comment


    The last session of the Visug, held at RealDolmen and presented by Maarten Balliauw concerned Mocking. Here’s an overview of the presentation that was given :

    • Unit testing
    • Dependencies
    • Mocking

    Part #1 : Unit testing

    Impossible to talk about mocks without mentioning TDD (test driven development). Indeed, mocking is all about unit testing. Unit tests should be :

    • Self validating (validate themselves against some behaviour or return values)
    • Fast (you don’t want too long for them to complete)
    • Focus on a method or functionality (atomicity of testing)
    • Isolated (from one another)

    One of the most famous style of unit testing is the AAA. Below some code example illustrating this :

    /// <summary>

    /// Tests a booking when there is no more rooms

    /// </summary>


    public void Restaurant_InsufficiantRoomsTest()


        // Arrange : prepare your variables and everything needed

        Table table = new Table(5);


        // Act : execute code



        // Assert : check the values or behaviour



    After this introduction, Maarten started some live coding, remembering us that writing unit tests is the first step before coding. You place yourself as client of your future code and see what you’d expect from it. Then, you code it. A little productivity hint : use the Generate Method Stub option from Visual Studio on the methods you haven’t implemented yet (as you code the test first, it won’t compile until you actually implement what you’re testing).

    Generate Method Stub

    Note : code samples illustrated here are from me, the speaker is thus not responsible for eventual errors they would contain.

    Part #2 : Dependencies

    Let’s introduce dependencies now. The example that Maarten coded was a bar tender and depending on the weather (web service call), some cheese (sunny) or nuts (rainy) were served with your beer. The problem here is quite evident : how can you test that in the more isolated way possible in order to keep control of your tests ? Indeed, you need to kinda “force” the weather to sunny or rainy to check if your system is implemented properly and delivers the expected behaviour.

    To do this, several “stunt double” solutions are offered to you :

    • Dummy (eg : null, empty list)
    • Fake (a working implementation)
    • Stubs (implementation using canned answers)
    • Mocks (implementation returning expected answers)

    Through some live coding again, Maarten showed us how it’s tedious, time consuming to implement fake objects and how unclean it is (classes need to be duplicated for fakes).

    Part #3 : Mocking

    Mocking frameworks are a convenient interface for setting up fakes/stubs/mocks. They do the job is less code, in AAA style. Some of the more popular mocking frameworks are :

    • One of the most mature and feature complete mocking framework
    • Uses Castle remoting for mocking calls
    • Open source
    • Free
    • This is the framework we’re using at work and we are very satisfied of it

    • Mature and fully featured
    • Isolates IL generation
    • Not free

    • “New kid”, increased popularity
    • Uses castle remoting
    • Not feature complete but in development
    • Open source

    Maarten then continued some live coding to illustrate how to use Moq. First, you gotta mock the object you want to fake functionality :

    var ws = new Mock<IWeatherService>();

    Then, declare what you expect from methods :

    ws.Setup(s => s.WhatsTheWeather()).Returns("sunny");

    Some interesting points (some are general about mocking frameworks) :

    • Expected exceptions throws can be verified
    • Callbacks can be made, instead of returning a particular value
    • Protected members can be mocked
    • Mocking can be recursive (XML tree generation for example). Prevents you from writing giant stubs
    • Verify calls to expectations : ws.VerifyAll();

    When should I mock ?

    • External object (web service, DB, …)
    • Non-deterministic objects (temperature, time, …)
    • Hard to reproduce situations (simulate a network error, HDD out of space, …)
    • Slow execution (simulate long calculations)
    • When some objects are not implemented (”empty shell”)

    And to finish this post, some recommendations :

    • Don’t mock everything ! Use it when needed…
    • Use loosely coupled code, it greatly eases the TDD (test driven development)
    • Tie everything together using IoC

    See you next time ;)

    - Thibaut


  • Visug and Besug groups on LinkedIn

    Posted on April 6th, 2009 Thibaut No comments

    Visug group   

    In a previous post, I talked about the Visug, the belgian Visual Studio user group that organizes very interesting meetings. And as a participant, I thought it could be interesting to create the Visug group on LinkedIn to connect its members and get more easily in touch. Feel free to join the group here !

    And there is also a brand new user group called Besug (BElgian Silverlight User Group) that organizes sessions on everything about Silverlight. I’ve already registered for this group and I’ll assist to future sessions because as a web developer, I’m very interested in Silverlight. You can join this group here.

    See you there ;)


  • Visug : new events

    Posted on March 20th, 2009 Thibaut No comments

    After some time of inactivity, the Visug is back again with a lot of new sessions. They also introduced the very interesting concept of back 2 basics, but unfortunately these sessions are planned during working hours so far… So I won’t be able to assist to them. Other sessions remain organized during the evening just like before. I’ve already registered for the ones listed below :

    According to Gill Cleeren, more sessions are to be announced in the next days to check it regularly ! See you there ;)


  • Visug

    Posted on March 5th, 2009 Thibaut No comments


    If you’re a .NET developer living in Belgium, you may find the Visug (Visual Studio User Group) very interesting ! Indeed, with about 20 events a year and more than 1 000 members, the Visug is a very nice place to be. Quality of the organization is very good (well chosen places, catering almost always included, free goodies, …) and the speakers very interesting (eg Juval Löwy). This being totally free, what more could you ask for ?

    Sessions are held after working hours, usually from 6pm to 8.30pm on Thursday and because rooms are limited, don’t forget to register for a session on the website. I’ll assist to the Visug as much as possible and will post summaries of previous sessions in this section, so be sure to check it out regularly ;)

    See you there,

    - Thibaut