Some stuff about Web and .NET development
RSS icon Email icon Home icon
  • Microsoft WebCamps Brussels - Summary

    Posted on January 30th, 2011 Thibaut 5 comments

    WebCamps

    Last Monday was organized the Microsoft WebCamps event in Brussels. Dedicated to Web developers and UX designers, this one day event enables you to stay up-to-date with the latest stuff. Topics covered included HTML5, jQuery, ASP.NET MVC 3, … And I’m going to share some of my notes here.

    Opening keynote

    By Scott Hanselman

    • Presentation of WebMatrix and the Razor syntax. For “get it done” developers who want, for example, to install and configure a website powered by a CMS for some customer in only a few minutes
    • jQuery adoption is so big that Microsoft continues to invest into this library : jQuery UI will also be part of the .NET framework
    • Presentation of the new features of ASP.NET MVC 3. ScottGu has written some very interesting articles on the subject, be sure to check them out if you’re interested in MVC 3
    • NuGet is a very powerful package installer. With just a few commands, install nInject, Entity Framework, … Time to learn PowerShell has come ;)

    How about HTML5 today ?

    By Katrien De Graeve

    • Slides of the presentation
    • Use shims to use HTML5 today (the JS script to make IE recognize the new HTML5 tags)

      <!–[if lt IE 9]>

      <script src=”http://html5shim.googlecode.com/svn/trunk/html5.js”></script>

      <![endif]–>

    • Use a reset CSS (typically to make some of the new elements display as blocks
    • Download HTML5 instellisense for Visual Studio
    • Use Ray Bango’s templates for Visual Studio
    • CSS3 : more control over color (RGBA, …), borders and shadows, fonts (use FontSquirrel to integrate custom fonts on your website)
    • Use IE9 developer tools (F12) to change the document mode (to IE8, IE7) to test against previous versions of browsers
    • Modernizr : great JS library enabling you to target specific browser functionality in your stylesheet, so you can take advantage of HTML5 and CSS3 while having a compatible site for older browsers
    • <video> tag : different codecs supported by browsers. Be sure to create multiple encodings of the same video (by using VLC Media Player for example) or provide a fallback in Flash or Silverlight.

      <video controls>

          <source src="foo.ogg" type="video/ogg">

          <source src="foo.mp4">

          <object/> <!– Silverlight or Flash –>

      </video>

    • Canvas : drawing using JS. Example of application : Pirates love Daisies, a game written using Canvas.
      Pirates love daisies
    • Use Ai to Canvas to convert Adobe Illustrator files to a canvas compliant format
    • Canvas (bitmap) != SVG (vector)
    • General guidelines :
      • Use feature detection VS browser detection. For each new version, browsers implement more and more the HTML5 spec. So browser detection isn’t a good approach at all
      • Start using HTML5 now ! Don’t wait for the spec to be complete (you would still be waiting for the CSS2 spec to be complete then…)

    Come in as a jQuery zero, go out as a jQuery hero

    By Gill Cleeren

    • Intro of jQuery (selectors, plugins, …) : I’m not going to rewrite the complete course here, just google, the web contains loads of tutorials about that hot subject

    OData : open data for the web

    By Scott Hanselman

    And that’s it ! Have fun playing with that exciting stuff ;)

    Share/Save/Bookmark

  • ReMIX10 : summary

    Posted on October 3rd, 2010 Thibaut No comments

    ReMIX10

    Last Tuesday, I assisted to the 2010 edition of the ReMIX, reedition of the popular MIX event. As usual, two tracks were available : web developer and UX. My current focus being Silverlight, I assisted exclusively to the UX track. Below, you’ll find my notes about the sessions.

    Opening keynote

    IE 9

    Silverlight 4

    Windows Phone 7

    • Silverlight & XNA support
      • Silverlight : for applications
      • XNA : for games
    • Free version of Blend dedicated to Windows Phone development
    • Demos of games on the phone. Companies such as Fishing Cactus presented their games for WP7

    Natural interface

    Session #1 : design venture

    • Prensented by Georg Petschnigg from Microsoft Pioneer Studios
    • Bringing design and business together
    • 2 points :
      • technology knowledge (languages, tools, …)
      • open vision on the world, cultures, etc to be creative and to innovate
    • Innovation process :
      Innovation process
    • From insight to core idea :
      • What’s unique about you
      • What does the world need
    • Observe people, their habits : find new ideas and ways to improve
    • From core idea to product : the three reads in industrial design
      • Eye : what you see
      • Touch : material, feeling
      • Use : does it suits my needs ?
    • Translate them in software :
      • Form (eye) : look & feel
      • Touch : controls
      • Use : features
    • Three reads of industrial design are from top to bottom (first attracted by what you see, then you touch it and use it if you like it)
    • Three reads of software design are from bottom to top
    • Importance of visual designers now : with all new rich web technologies (HTML 5, Silverlight, …), your product can be beautiful, more simple, and visual designers can add “life” to it
    • Passion is key to outstanding quality work. Nothing great in the world has ever been accomplished without passion (Georg Wilhelm Friedrich Hegel). You must have a “soul” in your work, enjoy people you’re working with to be great at creating and innovating

    Session #2 : UX Superpowers with Expression Blend 4

    • Presented by Arturo Toledo (Microsoft)
    • MVVM support
    • New pixel shader effects
    • New shapes (clouds, comics bubble, …)
    • Path layout : items added and layed on a path (one of the best features of Expression Blend 4, see example below). Items automatically arranged as they are added/removed, can be animated along the path, …
      Path layout
    • Examples of applications using path layout : organic menu, etc
    • Lots of demos of the new stuff

    Session #3 : Windows Phone 7 design principles

    WP7

    • Presented by kat Holmes and Karen Davis (from Microsoft WP7 team)
    • Design principles for WP7 : colors, information architecture : remain consistent with Microsoft guidelines, use of Blend for WP7 is strongly suggested so you work on the base of these guidelines
    • Presentation of the two main screen layouts for WP7 :
      • Panorama : when your content is not best suited to be redueced to fit screen size : keep it large
      • Pivot : more traditional layout, where all information can be on one page
    • 3 key points for WP7 development :
      • Personal : familiar and thus easy to use
      • Relevant : don’t overdo, focus on content
      • Connected : compliment, don’t duplicate existing features or applications

    Session #4 : a website life, from sketch to publishing

    • Presented by Arturo Toledo (Microsoft)
    • WebMatrix : 3 tools :
      • IIS Express (instead of Cassini : no more bad surprises because Cassini was different than IIS)
      • SQL Server Compact : local, file-based DB
      • ASP.NET Web Pages (new script syntax : Razor)
    • Concept of code helpers. Eg : @Twitter.Profile(”ThibautVS”) displays a list of my tweets
    • Can run SEO reports, giving you hints on how to improve your search engines friendliness
    • Most of the presentation consisted of coding examples using the new, powerful Razor syntax.
    • More information in this MSDN article : How WebMatrix, Razor, ASP.NET Web Pages and MVC fit together

    Conclusion

    It’s always nice to participate to such events because it enables you to maintain a vision of the Microsoft technologies landscape. Then you can pick up what you’re interested in and start a deep dive into it. That’s exactly what I’m doing with Silverlight 4, Expression Blend 4 and HTML 5. See you next year ;)

    Share/Save/Bookmark

  • Ordina Azure Training

    Posted on September 29th, 2010 Thibaut No comments

    Windows Azure

    Ordina, my employer, is organizing training sessions every week ’til end of the year on various topics such as Azure, Scrum, TFS etc. Below, you’ll find my notes of the 1st session of the Azure training track, given by Kurt Claeys.

    Current pain points

    • Managing IT hardware & infrastructure has an important cost
    • High complexity in provisioning and administration (ex : order new service, configure it, migrate data, …)
    • Increasing competition drives needs for reduced time to market (which traditional model does not allow, eg : ordering new servers might take several weeks, then have to configure them, etc)
    • New business needs of mobile devices requires access to ubiquitous data

    Cloud computing

    • Infrastructure, platform and software as a service
      • IAAS : Infrastructure as a service (hardware)
      • PAAS : platform as a service (developers) = AZURE : OS for cloud enabled apps, service hosting, relational data storage (SQL Azure)
      • SAAS : software as a service (end users) = BPOS : exchange, sharepoint, …
    • No more licencing model : pay as you grow, renting on a monthly basis. Don’t pay for licences but for what you use (processing power, disk storage, …)
    • Service fully managed by the provider
    • Elastic scalability : need to grow ? Just ask for more
    • Standardized access (HTTP, SOAP)
    • Cloud materialized as containers in data centers, containing a lot of servers : Europe : Dublin with backup in Amsterdam, some in the US and Asia

    Azure containers

    • Very flexible. Traditional scenario : you buy a server, it’s ok for some time then, as load increases, you need to buy another one (wasting resources because load is 50%, for example). Then load exceeds servers capacity, you buy another server and then maybe load will decrease, wasting resources again. In cloud : resources follow the load, you pay for what you use. Enables to grow very quickly : if more load needed, it’s automatically taken in charge by cloud (don’t need to wait for a new server to be delivered etc). Automatic load balancing (performed by fabric controllers : they monitor machines in a container, control their load, if they are crashed, etc)
    • Data stored on 3 physical machines. For SQL Azure, a commit only returns success code if data has been committed to at least 2 different databases
    • Scale model : not automatic, you define the limit. So you won’t have unpredictable, incredibly high bills. Developers must write tools to add instances, monitor performance matrix (typically CPU and memory use). Scaling up = matter of changing configuration files
    • What makes up the bill :
      • CPU usage/hour (0.12$)
      • Storage / Gb / Month (average on the month)
      • REST Transactions (updating table, reading data, …) : 0,01$ for 10 000 transactions
      • Bandwidth : Gb/month
    • Storage and processing power decoupled
    • ASP.NET websites not supported, need to migrate to web app (not a long process says Kurt Claeys)

    Future of the sys admin job

    With Azure, the sys admin stuff is now performed by Microsoft, who hires Indian guys to cut the bills. When a company adopts Azure, they then fire some/all sys admins. So, what are your predictions for the next years ?

    Share/Save/Bookmark

  • Techdays 2010 - Day 2 (1 april) : my notes

    Posted on April 22nd, 2010 Thibaut No comments

    And here’s the second and last part of my notes taken at Techdays 2010.

    Session 1 - Unkeynote
    By Scott Hanselman

    • A quick recap of ASP.NET 4.0 new features, such as :
      • Clean HTML : specify client IDs (better for JS and CSS)
      • ViewState improvements (enable it just for some controls, …)
      • Charts
      • Cache extensibility : HDD based caching
      • Customized Web.Config (staging, prod, …)
      • Clean URLs for WebForms (REST)
      • Client-side binding in JS
    • MEF : Managed Extensibility Framework (design applications as components able to interact with others)
    • Parallel Computing : “threading for the masses”, so developers can focus on the business and not on concurrency problems

    Session 2 - Introducing MVVM
    By Laurent Bugnion

    • MVVM stands for “Model - View - ViewModel”
    • Advantages :
      • More testable
      • More maintainable
      • Blendability (ability to be edited in Microsoft Blend)
    • A lot of code examples
    • Laurent Bugnion has created the MVVM Light Toolkit, intended to accelerate the creation and development of MVVM applications in WPF, Silverlight and in the Windows Phone 7.

    Session 3 - Visual Studio Tips
    By Sara Ford

    • Sara is author of a book about Visual Studio Tips, such as shortcuts, productivity enhancement tips, … And the session was a sample from this book
    • You can find the tips she’s given on her dedicated blog entry

    Session 4 - What’s new in ASP.NET 4.0
    By Fritz Onion

    • Javascript intellisense + snippets
    • Routing (ASP.NET MVC URLs style)
    • ViewState improvements (ability to enable/disable it for a particular control, disable it application wide, …)
    • Ability to specify a ClientID (which is better for Javascript and CSS, no more need to use “ends-with” selectors
    • SessionState : store the session of the user in DB
    • Meta tags : ability to specify them code behind
    • Charts : a large collection of charts (including some based on Dudas charts)
    • QueryExtender : create filters for data that is retrieved from a data source, without using an explicit Where clause in the data source

    Session 5 - Software testing with Visual Studio 2010
    By Brian Keller

    • Software bugs cost billions of $ each year in the U.S
    • Today, still too much manual testing (about 70%)
    • Introducing Testing Center : interface to configure test plan :
      • Type of logs to produce
      • OS or browsers to test with
    • Test recording : user is performing actions being recorded and can be replayed later => about 20x faster than manual testing
    • If a test case fails : video to show what happened
    • Intellitrace : listing all the events and processes done by the app. Very useful to find quickly what went wrong (instead of placing breakpoints, doing some guess work, re-running the app, …)

    Session 6 - ASP.NET AJAX 4.0 : what’s new
    By Fritz Onion

    • Fritz started by announcing that Microsoft decided to make jQuery the primary way to develop AJAX apps using Microsoft technologies (officially announced by ScottGu at MIX in March)
    • As a consequence, no more effort will be put by Microsoft in the MS AJAX library
    • No notes to list here as the session was obsolete following that announcement

    Share/Save/Bookmark

  • Techdays 2010 - Day 1 (31 March) : my notes

    Posted on April 19th, 2010 Thibaut No comments

    I finally take the time to blog my notes about the 2010 edition of the Techdays, after some pretty busy weeks of work dealing with deadlines.

    Session 1 - Developer keynote
    By Anders Hejlsberg, Hans Verbeeck, …

    • Evolution of computer languages (from Turbo Pascal to now) and evolution of hardware (HDD capacity : 100 000 x, RAM : 10 000 x, CPU : 1 000 x)
    • Evolution of tools : debugger, profiler, huge frameworks, …
    • 3 major trends today
      • Dynamic
      • Concurrent
      • Declarative (more on WHAT instead of HOW)
    • Multi-core CPUs : need to develop accordingly (Parallel Linq, Task Parallel Library, …)

    Session 2 - Silverlight 4 & WPF 4
    By Gill Cleeren and Katrien De Graeve

    • Silverlight 4
      • Printing : visual tree to select what to print
      • Drag & drop : even from an external app (eg : drag an image from the explorer to Silverlight). Also works on Mac
      • Right-click support
      • Webcam & microphone support enabling powerful applications : scan barcodes with the webcam, …
      • RichTextBox : rich formatting (fonts, colors, images, …) into a TextBox
      • Out of browser enhancements : notification windows with custom look, complete control over the window (change the size, no borders, …)
      • Trusted out of browser apps : go beyond the sandbox
    • WPF 4
      • Visual Studio 2010 : built onto WPF
      • Better tooling : similar to WebForms design
      • Support for Win7 : multi-touch, ribbon, taskbar manipulation, …
    • When to use Silverlight or WPF ?
      • Tip of Gill Cleeren : “make Silverlight the default choice for business apps unless you require specific WPF features”

    Session 3 - C# 4.0 and beyond
    By Anders Hejlsberg

    • Dynamic keyword : be static as much as you can (compilation checks, performance, refactoring, error checking, …). dynamic should be use to simplify the syntax (replacing invoke, binding flags, etc)
    • Optional & named parameters : avoid multiple overloads, supply default values. Better experience with interop : no more 15 “missing” parameters
    • Co & contra variance : to simplify, developers can now work easier with collection types, and have less problems with linq queries
    • Compiler as a service : API of the compiler (meta programming, language objet model, …). Introduction of the new CSharpEvaluator class

    Session 4 - ORM with entity framework in .NET 4.0
    By Kurt Claeys and Hans Verbeeck

    • ORM : working with relational tables like objects in memory
    • Why use it ?
      • Productivity
      • DB independance
      • Hides complexity, uniform way of working
    • Entity framework is a Microsoft strategic technology (they use it in Reporting Services), which is a sign that they bet a lot on it
    • 2 ways of working
      • Model first : DB doesn’t exist yet, design classes and generate SQL code from it
      • DB first : DB already exists, generate classes from it

    Session 5 - ASP.NET MVC 2 : ninja black belt tips
    By Scott Hanselman

    • First, Scott gives us a tip to avoid repeating the same code : use T4 (text templating) to automate it (related article)
    • Hybrid apps : you don’t have to choose between ASP.NET Webforms & MVC. Ex : codeplex is written with both, some parts being exclusively WebForms or MVC
    • Then, a lot of demos…

    Session 6 - Building Windows Phone apps with Silverlight
    By Giorgio Sardo

    • A lot of demos in this session about what can be done with the phone (layout rotation, custom styling, …)
    • To summarize, a citation from the speaker : if you’re a Silverlight developer, you’re a Windows Phone developer

    And that’s it for the first day ! See you in a next post for my notes about day #2 ;)

    Share/Save/Bookmark

  • [FR] DotNetHub : C# 4.0 et les améliorations à la BCL

    Posted on March 28th, 2010 Thibaut No comments

    Bonjour à tous,

    Ci-dessous, vous trouverez en vidéo la conférence de la précédente édition de DotNetHub. Celle-ci, présentée par Pierre-Emmanuel Dautreppe, abordait C# 4.0 et les améliorations à la BCL.

    Plan de la conférence

    • Co & Contra Variance des types génériques
    • Paramètres nommées et optionnels des méthodes
    • Types dynamiques
    • Simplification pour l’interopérabilité COM
    • Améliorations apportées à la BCL (Base Class Library)

    1ère partie

    2ème partie

    Notez également que DotNetHub aura un stand aux Techdays cette fin de mois, n’hésitez donc pas à passer pour vous renseigner, rencontrer ses membres ou devenir sponsor. A bientôt ;)

    Share/Save/Bookmark

  • [FR] DotNetHub, le UserGroup .NET/Agile francophone

    Posted on January 17th, 2010 Thibaut No comments

    DotNetHub

    DotNetHub, le tout nouveau UserGroup francophone en Belgique, est le résultat du projet initié par 3 de mes collègues (Pierre-Emmanuel Dautreppe, Norman Deschauwer et Thierry Thoua) en association avec d’autres professionnels de l’informatique. Le but de ce dernier est double :

    • Pallier l’absence de UserGroups francophones en Belgique. Le premier UserGroup belge, VISUG, se rapprochant toujours plus de la partie nord du pays, l’initiative est plus que la bienvenue
    • Proposer en plus d’un pôle technologique (.NET) un pôle méthodologique consacré à l’agilité (Scrum, XP, …) par l’organisation de dojos, entre autres

    Pour la première session, DotNetHub aura le plaisir d’accueillir Peli De Halleux, un petit belge travaillant désormais pour Microsoft à Redmond. Il vous présentera Pex, Moles & Stubs, des outils de tests unitaires pour .NET.

    Pour plus d’infos sur la session, c’est par ici. Pour s’inscrire, cela se passe par là.

    Bonne session ;)

    Share/Save/Bookmark

  • Visug summary : Modeling that works with code

    Posted on November 15th, 2009 Thibaut 2 comments

    Visug

    Last Visug edition, animated by Marcel De Vries from InfoSupport, concerned modeling with Visual Studio 2010. Note before we start that all of this is only available in the ultimate edition of VS 2010.

    Overview

    • Why we use models
    • Models first approach
    • Code first approach
    • Conclusion

    1. Why we use models

    • Diagrams for communication
    • Diagram = viewpoint on a model
    • Model use is challenging because :
      • Many interpretations of the same diagram
      • UML available but people uses a few diagrams only (ex : use cases)
    • Models become stale because :
      • Implementation will be different from the model
      • Maintaining diagrams takes time & effort
    • Ultimate goal : run a model (Oslo vision), from a metamodel store (data repository)

    When to create a model ?

    • It’s about communication, so create only models that serve a purpose
    • Create only models that differ from the normal case

    Two approaches

    • Models first
    • Code first

    2. Models first approach

    Scenario : you start a project and need to define the solution you’re going to build

    • Requirements analysts : use activity diagrams & use cases to outline functionality
    • Architects : build logial diagrams to outline required architecture to meet customer demand stated in the requirements
    • Testers : use the diagrams to do its test analysis based on the specified requirements
    • Developers can use the diagrams done previously to materialize the projects

    => Models are used to communicate throughout the team about what we’re going to do

    In Visual Studio 2010 Ultimate Edition :

    • New project type : modeling project
    • Support for UML 2.X diagrams
    • Other new types of diagrams : Layered diagrams & DGML diagrams

    Diagrams can be generated from code. The speaker uses it to generate sequence diagrams for code reviews. Note that those diagrams are plain XML files but it’s recommended to manipulate them via the API (cause in a next version, maybe Microsoft is going to change the format).

    3. Code first approach

    Scenario : maintenance of existing projects.

    • Developer can generate diagrams to gain insights on code dependencies
    • Architect can find architecture patterns
    • Architecture explorer helps discover and understand how a system works

    Layer diagram

    • Used by the architect to define the architecture
    • Classes and namespaces are mapped to layers in the diagram
    • Details the intended design
    • Diagrams are very interesting to verify the architecture and enfoce it.
    • In VS2010, there’s a tool to validate the architecture. Ex : you draw 3 boxes (UI, BLL and DAL), you link (arrow link) the UI to the BLL and the BLL to the DAL, you drag/drop your projects into the correct box. You then click “validate architecture” and you get a report about what’s violating the dependencies defined by the arrows.
    • You can also use these diagrams to validate things such as code coverage in percentage for a given layer.

    DGML

    • Directed Graph Markup Language
    • Nodes
    • Containers
    • Links
    • Styles

    You can also create you own diagrams (Progression API). You code in C# the way you want to generate the diagram. Styles can also be defined. Ex : speaker coded a diagram with nodes that must appear green or red (styles) following the code coverage percentage. Can also be used to annotate existing diagrams.

    4. Conclusion

    • Models & diagrams primarily for communication
    • VS2010 supports both approaches : code 1st and models 1st
    • New innovations in models that work with code (DGML & layered diagrams)

    Also note that ScottGu is going to visit Visug in december so stay tuned ;)

    Share/Save/Bookmark

  • Visug : lightweight stubs & detours for .NET

    Posted on November 11th, 2009 Thibaut 1 comment


    Visug

    Peli De Halleux, a belgian guy now working at Microsoft Research (Redmond) came back in Belgium at the Visug to talk about the project he’s working on. Stubs, Moles and Pex form together a lightweight framework to test .NET applications.

    Stubs

    Stubs is a stubbing framework solely based on delegates. Various examples can be found here.

    Moles

    Here’s an example of what you can accomplish with Moles, allowing you to replace any .NET method :
    Moles

    Pex

    And here, a diagram showing at a high-level view how Pex works :

    Pex

    Pex is an automated whitebox testing tool for .NET. From your code and parameterized unit tests, test code is automatically generated in C# and test results can be seen in the “input/output table”.

    Project-related resources

    I could copy-paste the great description of the project off the official website… But I instead recommend to those of you who are interested in this to take a look at the following resources, explaining you what Stubs, Moles and Pex are all about in the details.

    Pex

    Have a nice reading ;)

    Share/Save/Bookmark

  • Dino Esposito @ Visug : C# 4.0 & testability

    Posted on October 17th, 2009 Thibaut 1 comment

    Visug

    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

    Preconditions

    • 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

    Postconditions

    • 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)

    Invariants

    • 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

    Quantifiers

    • 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

    Summary

    • 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 ;)

    Share/Save/Bookmark