Design by Contract with .NET 4.0

An entry about visual studio | .net 4.0 Publication date 6. November 2008 16:33

Justin van Patten has put together a great list of all the new features that will ship with .NET 4.0 – both new features in the BCL, as well as the new features in the C# language itself. One of the additions to the BCL comes from Microsoft Research, and is called Code Contracts.

Code Contracts is a language independent tool which allows you to embed rules about the inputs, outputs and invariants in your code. When this information is embedded in the code, the Code Contract tools can perform both static and runtime analysis of the code to ensure that it is not breaking any of the rules defined. Sounds a lot like Spec#, doesn't it? Well, Code Contracts is essentially a port of the static and runtime verification concepts from Spec# into an API which will ship as part of the .NET 4.0 Base Class library.

Let´s look at an example: Imagine that we have an API with the following silly method somewhere in it:

public static string GetTypeName(object obj)

{

    if(null == obj) throw new ArgumentNullException("obj");

    return obj.GetType().Name;

}

The problem with this, is that there´s no way for a client of this API to know what happens if they pass a null value to this method. Does it crash? Return a null? Return an empty string? By using the Code Contract API, we can make such details of our implementation explicit:

public static string GetTypeName(object obj)

{

    CodeContract.Requires(null != obj);

    return obj.GetType().Name;

}

If someone writes code that calls this method and passes a value that might be null, and we have static checking of code contracts turned on in our project, we will get the following warnings from the compiler:

image

The first warning tells us that the contract we have defined was violated (not very helpful the messages yet, but it is an early beta after all), and the second warning points us at the code that is violating the contract.

In addition to setting up contracts that constrain the inputs to a method, we can also set up contracts that talk about the outputs. for instance, imagine that our original method looked like this instead:

public static string GetTypeName(object obj)

{

    return null != obj ? obj.GetType().Name : "<null>";

}

This time, our method will happily accept an argument which is null, and it will always return a string. Using code contracts, we can embed this fact into our method:

public static string GetTypeName(object obj)

{

    CodeContract.Ensures(CodeContract.Result<string>() != null);

 

    return null != obj ? obj.GetType().Name : "<null>";

}

These examples are just scratching the surface of what is possible. In addition to defining contracts that talk about the entry and exit points of methods, there´s also invariant contracts that deal with the state of the object as a whole. Contracts can also be defined on interfaces. More tools that take advantage of the contracts will also become available – for instance tools that auto-generate documentation, and of course there are great opportunities for integration with PEX here.

If you want to learn more about the features available and how they all actually work under the covers, then check out the recording of the PDC 2008 session by Mike Barnett and Nikolai Tilmann over at Channel9. I really recommend watching it – they do a great job of explaining the concepts (the first part is about Code Contracts, the second about PEX).

You can also go and download a preview of the framework and tools for Visual Studio 2008 over at the Microsoft Research site.

Currently rated 3.3 by 3 people

  • Currently 3.333333/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

The Official Faculty of The Mind Visual Studio Theme

An entry about visual studio Publication date 27. August 2008 09:13

As some of you may have noticed, I’ve changed the formatting of my code samples here on the blog to match the new design. I actually created a custom fonts&colors theme for Visual Studio 2008 to do this – here’s what it looks like with the Envy Code R font (with the italics hack):

 image

If you want it, you can download it here. You can get the Envy Code R font over at Damien’s blog. Be sure to install the special VS versions of the font which contain the italics hack.

This is my first attempt at a VS theme, and I’ve only themed the C#, ASP.NET and XML items so far, plus made some adjustments to the Resharper items. I’ll probably end up making more adjustments to the theme as I use it, in which case I’ll post an updated version later :)

Currently rated 5.0 by 3 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Deploying Asp.Net Sites to IIS7 from Visual Studio

An entry about asp.net | visual studio Publication date 29. March 2008 12:02

To be able to deploy Asp.Net sites to IIS7 from Visual Studio 2008 when running on Windows Vista, there's a couple of things that needs to be set up first. Aside from the fact that you need to be running Visual Studio as an administrator (either by choosing 'run as Administrator' when launching it, or by disabling the UAC), there are a few IIS6 compatibility features that needs to be installed. These can be found by going to Control Panel > Programs > Turn Windows features on or off, and ensuring that the following are checked:

Windows features

With that in place, you can go to the Web tab on the properties page for your ASP.NET project and select 'Use IIS web server' instead of the built-in development server, just like we're used to:

Asp.Net project server settings

Currently rated 3.7 by 3 people

  • Currently 3.666667/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Conditional Breakpoints are Slow

An entry about visual studio Publication date 20. September 2007 11:08

Today I was dumbfounded by a part of code I was working on slowing down significantly without there really having been made any major changes to it. Turns out that I had left a conditional breakpoint active:

image

The breakpoint above was being evaluated several thousands of times in a tight loop - I just didn't notice because the condition was never true. I really wish the Breakpoints window (Ctrl+Alt+B) had a column showing the number of times a breakpoint had been evaluated.

The moral of the story - know the things that may severely impact performance during debugging.

Be the first to rate this post

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Programatically Breaking Into the Debugger

An entry about visual studio Publication date 4. May 2007 16:31

Lately I've been exploring the System.Diagnostics namespace (previously I've posted about how to get the current stack trace), and one class that I've discovered which is pretty cool is the Debugger class. Essentially, it allows you to communicate with any debugger that is currently attached to the process. Apart form letting you send log messages to the debugger, it allows you to signal a breakpoint aswell - basically you can say:

Debugger.Break();

anywhere in your code, and the debbuger will act as if there was a breakpoint on that line of code, making the application break into it. That's pretty cool - but what's even cooler, is that if no debugger is attached, you will get the following prompt:

Breakpoint prompt

Hit debug, and you will be able to attach a debugger and then break into the code. Now you might not want to do this in production code - so you should probably wrap the Debugger.Break() call in a method decorated with the Conditional attribute and the condition "DEBUG" (which I consider a better practice than #if DEBUG), which will ensure that it wont get called if you're running a release build:

[Conditional("DEBUG")]
public static void BreakIntoDebugger()
{
Debugger.Break();  
}

Currently rated 1.0 by 1 people

  • Currently 1/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Auto-generating Localization in Visual Studio 2005

An entry about asp.net | visual studio Publication date 17. March 2007 00:00

The implicit declarative binding syntax (phew, that's a mouthfull) meta:resourcekey can be used to localize ASP.NET Controls in a much more tidy manner than using it's explicit counterpart. Basically, instead of doing stuff like:

<asp:Button
    ID="_submitBtn"
    runaT="server"
    Text='<%$ resources: Buttons, SubmitButton.Text %>'
    ToolTip='<%$ resources: Buttons, SubmitButton.Tooltip %>'
    OnClick="Submit" />

you can get away with the much more elegant:

<asp:Button
    ID="_submitBtn"
    runaT="server"
    meta:resourcekey='SubmitButton' />

which then will automatically look for SubmitButton.Text and SubmitButton.ToolTip (and any other resource-able properties) in local resource files.

However, the neat trick is that with Visual Studio 2005, you can just forget all about localization when you're writing the markup. Yep, just go ahead and hard-code those literals right in there. Afterwards, simply hit 'Generate Local Resource' on the Tools menu, and VS will do just that, moving all your hard-coded literals into a resource file.

The only downside is that the 'Generate' function is only available in Design Mode. Which, if you're like me and like to hand-type your markup, will probably find a bit annoying. Hopefully this should get sorted in Orcas however :)

Currently rated 5.0 by 1 people

  • Currently 5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.

NDC 2010

The conference to attend this summer happens June 16th-18th in Oslo, Norway. Are you going? Be sure to catch my talk on AOP while you're there!

 

Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS