Code Contracts #4: Modelling implications

Hey guys. It’s me again on Code Contracts. Sorry for not posting something on this exciting topic during the last weeks, I’ve been busy with some other tasks. This day’s post will cover some more technical ascpect of Code Contracts: how can we model implications using Code Contracts?

Code Contracts bring the DbC principle into the .NET world as one feature of the upcoming .NET framework 4.0. It’s providing statements on the code, which can be used to define specifications of how this code should work. Software elements should be understood as implementations which satisfy those specifications – that’s a very systematic approch and the core idea behind DbC. Let’s take a class method. With DbC in general and Code Contracts in particular, you’re able to define a system of obligations and benefits on this method. Obligations for clients of this method can be modelled via pre-conditions (Code Contracts: Contract.Requires(...)) to express, which conditions have to be satisfied by the client to run the method properly. In return the client get’s some benefits from the supplier (the method itself), if it maintains the obligations. Those guaranteed benefits can be defined by post-conditions on the method (Code Contracts: Contract.Ensures(...)). This obligation/benefit-based approach is very similar to contracts between humans. Example: I give you some money (my obligation as client) and you give me in return a Toyota Prius (my benefit from you as supplier), but you’re not bound to give me a Ferrari or Mercedes or something.

Thus in normal contract cases (code or real-life) you say „I give you X and you give me Y in return“. For a code example: „I give you an integer X>0 and you give me some number Y between 0 and X in return“ (e.g. a random number). But other contracts can be imagined, where the benefit depends on what has been delivered by the client. Real-world example: „I give you 40.000 $ and you give me a Toyota Prius. But if I give you 75.000 $, you give me a Mercedes S-class.“ That’s an implication. „If I give you X, you give me Y“ or shortly „X => Y. Cases can be imagined, where this could be useful in contracts on code. For example: „If you give me an empty list or null, I’ll return null. If you give me a non-empty list, I’ll return an element not equal to null.“ In this scenario, it depends if you would use a pre-condition to prohibit empty lists or null’s as parameter or not, but let’s assume those cases are normal and allowed by the method, thus shifting the responsibility to handle those in the supplier (the method) instead of the client.

Such implications are generally post-conditions on methods („I’ll give you something…“), but cannot defined directly through Code Contracts. But that’s no definite issue of Code Contracts. Implications are a special form of boolean expressions and every form of boolean expression can be used as input of a Contract.Ensures(...) call. Rather that’s a limitation of most .NET languages like C#. They don’t have an implication operator for boolean expressions and therefore don’t have direct implication support.

Solution for that is the decomposition of implications to primitive boolean expressions. Consider two boolean expressions a and b. Then the implication „a => b“ is semantically equivalent to „!a || b, which can be used in this form in any program code.

Let’s take the example from above again: „If you give me an empty list or null, I’ll return null. If you give me a non-empty list, I’ll return an element not equal to null.“ This contract can be modelled with three implications: „list==null => null“, „list.Count==0 => null“, „list.Count > 0 => !null“. Using Code Contracts and boolean substitution, we end in the following code:

public string GetSomething(IList<string> list)
{
    Contract.Ensures(!(list == null) || (Contract.Result<string>() == null));
    Contract.Ensures(!((list != null) && (list.Count == 0)) || (Contract.Result<string>() == null));
    Contract.Ensures(!((list != null) && (list.Count != 0)) || (Contract.Result<string>() != null));

    if ((list == null) || (list.Count == 0))
        return null;

    return list[0];
}

Looks a little bit frightening, doesn’t it? Moreover, the static checker will be overwhelmed with that (doesn’t have a contract on the indexer of list and thus doesn’t know, that list[0] will return a value != null). Ok, that’s perhaps not the best example, but it shows one general problem: expressions can become very big and obscure, even in relatively simple cases. That raises the question where and when to use contracts, but that’s another story…

That’s it for the moment. As you can see, implications can be used not directly, but relatively easy by use of boolean expression substitution. One could call for direct support, but that’s a language feature (providing an implication operator) and need not to be considered by the Code Contracts team. More stuff to come as soon as I find some spare time.

kick it on DotNetKicks.com

Released: Silverlight 3 Beta 1, ASP.NET MVC 1.0

Just two little quick announcements: Silverlight 3 Beta 1 and ASP.NET MVC 1.0 have been released. Here are the links:

Code Contracts #3: Contract checking

In my first two posts of this series, I covered some basic information about Code Contracts, their origins and core elements of DbC as well as the basic declarative nature of Code Contracts, the Contract Rewriter and why contracts are defined imperatively and not via attributation or additional keywords. In this blog post, I’ll dig even deeper to show the two main elements, how contracts on your code are checked…

The functionality of checking contracts/conditions on your code comes from two main components of Code Contracts: the dynamic checker (runtime checker) and the static checker. Those can be configured and activated after installation of the Code Contracts package through a new tab inside the project’s Properties window:

Configuring Code Contracts in the project's Properties windowMore information on that can be found e.g. on the Code Contracts User Manual.

The dynamic checker

The first component is the dynamic checker, which is even called runtime checker, what better implies its behavior. This type of contract checking is done at runtime of your program code. Everytime when the program execution hits a point, where contracts are defined, the Contracts runtime checks, if the contracts are fulfilled in the current context, that means with the current class state, current variable and parameter values etc. Thus the dynamic checker is searching for actual broken contracts in just the current context. Its behavior is very similar to a test (under the given context) resp. to a Debug.Assert(), leading to the term of validation of your code. If a contract check fails, then the default behavior is that a ContractException is thrown and the application terminates. This can be easily adopted to your own needs.

The static checker

So, dynamic checking ensures at runtime that no contracts are broken by current calls of your code. But it leads to the same problems as in unit testing: code coverage, choice of input/output pairs etc. Perhaps contract violations are not found during testing, because the checking with a chosen set of parameters fulfills those contracts. Problems occur, when you deliver your code and other developers use parameters that you didn’t consider and then contracts are not fulfilled any more.

The second and more interesting part of Code Contracts checking is the static checker. What’s the difference to dynamic checking? The static checker is able to check defined contracts at compile time of your code. Moreover, the static checker doesn’t only search for actual broken contracts, but for all possibilities where contracts could be broken by the defined code. For example, let’s imagine a method int Predecessor(int x), that returns the value x-1 and a post-condition on that method, that the return value is in every case ">= 0". With dynamic checking, perhaps you input some arguments for x: 1,5,100,13, … it would never lead to a situation, where the contract is broken. With static checking instead, the static checker would analyze the code at compile time and would recognize, that there are situations (every value for x < 1) where the post-condition of the method is not fulfilled. In this case, the static checker would output a warning to inform the developer of the possible contract breach.

With all this, the static checker is doing a formal verification of the defined contracts in contrast to the test-based validation of the dynamic checker. This is done by a complex algorithm that’s based on methods of formal logic and program verification and that’s why the static checker needs some time to perform the verification. The concrete algorithm is using abstract interpretation of the code, thus the code is being inspected, but not executed! By this process and with a basic rule-set on the CLR, facts about the code are generated and those facts are used to find out, if the code fulfills the defined contracts or not. The behavior of Code Contracts is very nice in comparison with the dynamic checking, but the complexity of this process may not be underestimated. Moreover, it’s heavily requiring contracts on most code pieces that you use in your contracted code, for example in the .NET framework. That’s why the Code Contracts team is currently working hard to introduce contracts all over the .NET libraries. Let’s do an example: if you have a string s and call s.Contains(), then you as programmer know that s.Contains() doesn’t change s or any other values. But if there would be no contracts on String.Contains(), then the static checker of Code Contracts could not know that Contains() is free of side effects and isn’t changing the value of s. Thus, it would warn on any post-condition of a method, that makes use of the value of s.

The following example shows a compiler warning, created by the static checker. The method WithDraw() for withdrawing money from an account has been understood and implemented as deposit (using the Deposit() method) with a negative amount. The static checker fails, because on deposit only positive values are allowed and that’s what the pre-condition on Deposit() declares. The warning is shown in the following picture. Furthermore you can see, that Code Contracts is suggesting a pre-condition on WithDraw(), by which the contract could be fulfilled.

Warning of the static checker at compile time

And that’s it again for the moment. In this blog post I’ve introduced the two core checking components of Code Contracts: the static checker and the dynamic checker. Where the dynamic checker is just doing a validation at runtime under the actual values context, the static checker is performing a complex formal verification at compile time, which finds all possible contract breaches. Those are two very different approaches and should be clear before using Code Contracts. Next blog posts will give you more examples on defining contracts and further insights.

kick it on DotNetKicks.com

Code Contracts #2: Code transformation

In my first blog post about Code Contracts, I covered the origins of the project and the elementary pieces of programming by the DbC principle: pre-conditions, post-conditions and invariants. Now let’s dig a little deeper and look at more background information about how contracts on your code are evaluated…

At first, let’s look again at the example of the Deposit-method from the last blog post:

public void Deposit(int amount)
{
    Contract.Requires(amount > 0);
    Contract.Ensures(Balance == Contract.OldValue(Balance) + amount);

    Balance += amount;
}

As you can see, contracts on methods (pre- and post-conditions) are defined imperatively inside the method. But instead of this definition, in fact their behavior is declarative! Thus they are not called at runtime as it is expected through the imperative style. If you debug the method and set a breakpoint on the contract’s position, then the debugger will not break there. In truth there is a component of Code Contracts called Code Rewriter (ccrewrite), which is performing a post-compile process on the IL-code, that’s generated by the compiler. Thus, every Code Contracs definition is set to its correct location in the IL code. For example, pre-conditions are set to the beginning of a method, post-conditions to the end, just before the (every) method exit, regardless to the location, where they have been defined imperatively. A look through the .NET Reflector googles over the created assembly makes this clear, too. The reflected code of the Deposit-method looks as follows:

public void Deposit(int amount)
{
    __ContractsRuntime.Requires(amount > 0, null, "amount > 0");
    int Contract.Old(Balance) = this.Balance;
    
    this.Balance += amount;

    __ContractsRuntime.Ensures(this.Balance == (Contract.Old(Balance)
        + amount), null, "Balance == Contract.OldValue(Balance) + amount");
}

As expected, the pre-condition is evaluated at the beginning, the post-condition at the end of the method. Moreover, at the beginning of the method (after the pre-condition has been evaluated) the old value of Balance is stored into a temporary variable, thus enabling Ensures() to have access on it.

With the existing example of the Deposit-method, there are some questions that come into the programmer’s mind. For example, why are Code Contracts defined (not very intuitively) imperatively inside a method and not as attributes for the method as one would expect through their declarative nature, thus leading to code pollution? The answer is, that attributes are too limited in their expressiveness. To allow full flexibility, conditions would have to be declared as string and you would have no IDE-support (Intellisense, compiler support) any more. Furthermore, the strings would have to be parsed by Code Contracts, what’s error prone at all. If attributes in .NET (C#, VB, …) would be more expressive and allow more aspect oriented programming (AOP) features, then it would be possible to define contracts via attributation, but not until now. Ok, when not using attributes, why aren’t there additional keywords for definition of Code Contracts as in Spec#? For example, why aren’t there requires and ensures keywords that are defined between method head and body and thus making the sense much more clearer and separating contracts from core logic? Please have in mind, that keywords are language-based features! Instead, the Code Contracts library becomes an element of the .NET 4.0 CLR and thereby it covers all .NET based languages, from which it can be used consequently. It would be nice to have such keywords, but it’s not the task of the Code Contracts developer team, but of the C# (and other .NET languages) team. Perhaps we’ll see such keywords in C# 5.0? Who knows…

That’s it again for the moment. In this blog post I covered the topic of code transformation by the Code Rewriter a little bit and made some statements about the declarative nature of Code Contracts. In upcoming blog posts, I want to show you the evaluation elements (checkers) of Code Contracts and give more examples, how contracts on various code elements can be defined…

kick it on DotNetKicks.com

Code Contracts #1: Basic information

During the last days and weeks, I’ve had the chance to make my mind up on Code Contracts, validation vs. verification of code and code quality on the whole. I’ve made some examples with Code Contracts and want to start a basic blog post series here, which should give you some further information on this. Code Contracts as project are not baked, yet. Thus I don’t throw with mud about things, that will definitely work in the future. This makes no sense! I just want to share some knowledge and want to know what you think about this altogether.

„Code Contracts“ is a project from the Microsoft DevLabs (http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx) and can be downloaded and installed in a very early state at the moment. The origin of Code Contracts is the programming language Spec#, which is extending C# at aspects for definition of conditions, that have to be fulfilled by part of a programmer’s code (classes, methods, variables, …). Moreover, the „Code Contracts Library“ has been decoupled from Spec# for Code Contracts and has been modified to work with the .NET framework in general. Thus, Spec# as research project has served its time, but it’s living on with Code Contracts. The impact of Code Contracts is not to underestimate: the component is going to be an element of the .NET 4.0 class library and thus it’s making its way into all .NET based languages.

But what’s hiding behind Code Contracts? The idea is the same as in Spec#: taking your code under contract, that means setting conditions on it. The programmer then has to take care about fulfilling those conditions (contracts) with his code. This idea isn’t new at all, since it comes originally from the Eiffel programming language, which has been introduced in 1985 already. Therefore Eiffel supports the Design by Contract (DbC) principle, whereby the following aspects can be defined in the code:

  • pre-conditions: Those are declared on method level and define conditions, which have to be fulfilled at entrance of a method (that means which contracts have to be kept by the caller). Mainly, these are conditions on method parameters (e.g. prohibition of null-values).
  • post-conditions: Those are declared on method level, too and define conditions, that have to be fulfilled at exit of a method (meaning contracts, that the method’s code has to ensure). For example, one could make conditions on the return value, that callers of the method could rely on.
  • invariants: Those are definitions on class level, depicting conditions, that have to be fulfilled at exit of any method of the class. For example, one could define conditions on the value of fields or properties of the class (be not null, be positive, have a defined value range, etc.).

The following example of a method deposit for a banking account illustrates the use of pre- and post-conditions in their original language Eiffel:

deposit (amount: INTEGER) is
    require
        non_negative: amount > 0
    do
        balance := balance + amount
    ensure
        updated: balance = old balance + amount
end

Pre-conditions can be defined with require, ensure defines post-conditions, that have to be true at exit of the method. Those can also describe the value of class members as shown in this (trivial) example for the member balance. Thereby, Eiffel is checking at runtime if the contracts are fulfilled and if not it’s notifying with an error.

Just those definitions are possible with Code Contracts in .NET, too. With static methods on the newly introduced class Contracts, the programmer gets the possibility to define such contracts. The deposit method from the example above would look in .NET Code Contracts as follows:

public void Deposit(int amount)
{
    Contract.Requires(amount > 0);
    Contract.Ensures(Balance == Contract.OldValue(Balance) + amount);

    Balance += amount;
}

With Contract.Requires() one can define pre-conditions, with Contract.Ensures() post-conditions. Contract.OldValue() can be used in a post-condition and is a placeholder for the value of a variable on class level (property, field) at entrance of the method.

To use Code Contracts in your own projects and get first insights, you have to download the current package from http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx and install it. Then, if you add a reference to the Microsoft.Contracts.dll to your project, you can access the Contract class from the namespace System.Diagnostics.Contracts. But again as reminder: the Code Contracts project is in an early state at the moment, so don’t expect a perfect solution. The team is working hard to improve their code and thus everybody should appreciate their work. Many things have to be done until the rise of .NET 4.0, but I’m sure that they’ll do their job very well.

Those are first basic information about Code Contracts. Next blog posts will involve deeper knowledge about Code Contracts, the components of Code Contracts, more examples and information about why it makes a change and why one should care about.

kick it on DotNetKicks.com

C# covariance and contravariance

Hey guys. Sorry that I was not posting bigger stuff for a long time. I’ve had some personal time-eaters during the last months, but I hope it will get better soon. Today’s topic during this article is covariance and contravariance in general and especially in C#. What is it? Who needs it? How is it supported today? How will it be supported in C# 4.0? Answers have to be found…

So, covariance and contravariance are features of a programming language’s type system (not limited to C# at all). More precisely (and theoretically), they are characteristics of binary operators, which convert one type to another type. Generally if an operator changes the type in some kind, it’s called variant. If it retains the type (the type is fix), then it’s called invariant. Two types of variant operators are contravariant and covariant operators. In fact, there are other types of variance (consider dynamic typing, duck typing etc.), thus covariant/contravariant operators are just two examples for that. If an operator orders types in the way from general to more specific for any type, then it is called to be covariant. If it orders types reversely from specific to more general, then it’s contravariant.

So far the theoretical introduction. It’s pretty much saying nothing about what both terms mean in your practical coding life, isn’t it? Well… in programming languages there are two features where co- and contravariance can make sense: return type covariance and parameter type contravariance.

Return type covariance

Let’s consider the interface IClonable for a moment. It’s declared as:

public interface ICloneable
{
    object Clone();
}

If we want a class Foo to implement this interface, then it has to apply the exact same signature:

public class Foo : ICloneable
{
    public object Clone()
    {
        Foo clone = new Foo();
        // cloning implementation
        // ...

        return clone;
    }
}

Wouldn’t it be nice to have a method public Foo Clone() instead? That’s what return type covariance means. With this, the return type would be narrowed by more specific implementations or derivations. It would give type-safety to all callers of the method. Yes, this would be nice, indeed. But that’s a feature, which is currently not implemented in the C# language. The more general return type in the interface or a base class can not be narrowed on implementing or deriving classes. The same problem arises in a number of cases and on generics, as we will see later on.

Parameter type contravariance

If we got a method on an interface or base class which takes a parameter X, then contravariance is all about wanting a more general parameter in the implementation method of that interface or in a derived class. C# doesn’t support that, yet. For example, the following will not work:

class Fruit { }
class Apple : Fruit { }
class Cherry : Fruit { }
class FlavorComparer : IComparer<Fruit> { ... }

public void SortApples()
{
    List<Apple> apples = GetSomeApples();
    IComparer<Fruit> flavorComparer = new FlavorComparer();
    apples.Sort(flavorComparer);
}

FlavorComparer compares two fruits based on their flavor. Apples are fruits, so why shouldn’t they be sorted with use of the FlavorComparer? This would be nice, but Sort() needs a IComparer<Apple> and not the more general argument IComparer<Fruit>. It should be no problem for using the more general comparer, but C# doesn’t support this at the moment.

Covariance on arrays

Since the first C# (1.0), covariance on arrays is supported. Thus, one could write:

Fruit[] fruits = new Apple[10];
fruits[0] = new Cherry();

An array of a reference type can be viewed as an array of its base type or any implemented interface. That’s no problem for the compiler, it just works. But at runtime, that example would produce an ArrayTypeMismatchException and that’s what one would expect in this example. Creating apples and setting one to a cherry is no good idea.

Well, but why does it compile? That’s a historical problem. In the first version of C#, it has been designed to attract as many developers as possible and since this type of covariance worked in Java, the C# guys applied it to their language as well. Not that good idea, but that’s another story…

Covariance and contravariance on generics

Generics in C# 1.0 to 3.0 are invariant (fix). If we map the array example to generics, then the following code will not work:

List<Fruit> fruits = new List<Apple>();
fruits.Add(new Cherry());

In this case, there’s no exception thrown at runtime, but already the compiler comes up with an error message at the first line. Invariance on generics is a serious limitation of current C# versions, since it doesn’t allow many intuitively correct cases.

For example, if you have a method List<Fruit> GetFruits() on the Fruit class, which gets overridden by the Apple class, then you can’t return an instance of List<Apple>, which should be no problem intuitively. The following code on Apple is not working:

public List<Fruit> GetFruits()
{
    List<Apple> fruits = GetApples();
    return fruits;
}

The same problem arises, if we want to have a list of fruits, which should be a Union of apples and cherries, which are both fruits…

List<Fruit> fruits = new List<Fruit>();
List<Cherry> cherries = GetCherries();
List<Apple> apples = GetApples();

fruits = fruits.Union(cherries).Union(apples);

This or similar code doesn’t work as well.

C# 4.0

Having all that in mind, C# 1.0-3.0 is some kind of nerving limited in terms of covariance and contravariance. It has covariance on arrays of reference types and C# 2.0 introduced covariance and contravariance on delegates (which obviates some really annoying workarounds), but at the whole there should be better language support of those type-system features.

But a knight in shining armour is approaching: C# 4.0 arises on the horizon! But does it hold what it looks like? In fact, with C# 4.0 you have the in and out keywords, which you can define on type arguments of interfaces and delegates.

With the out keyword you can define a type parameter to be covariant. This means, that implementations of methods which return an object of this type can also return a more specific type. The standard example in this case is IEnumerable<out T>:

public interface IEnumerable<out T> : IEnumerable
{
    IEnumerator<T> GetEnumerator();
}

public interface IEnumerator<out T> : IDisposable, IEnumerator
{
    T Current { get; }
}

This allows you to write e.g.:

IEnumerable<object> list = new List<string>();

and

IEnumerable<Fruit> fruits = new List<Apple>();

It allows you to have a base type as type parameter of an IEnumerable instance and a more specific type if you assign something to it. But wait: there’s a limitation on that… out T means: no method in this interface is allowed to use T as parameter! The word „out“ makes this clear and it limits the use of those covariance to just a few interfaces. For example, this cannot be set on the ICollection<T> interface (and furthermore on IList<T>, because of IList<T> : ICollection<T>). ICollection<T> includes a method Add(T item) and since no T is allowed to be used when out T is declared, that wouldn’t work. Now, most of my own generic interfaces and many .NET interfaces as well use type parameters as in- and output, so this new type of covariance seems to be not this influencing. For example, the following code would not work:

IList<object> list = new List<string>();

But why? There’s an important aspect on that and that is the same as on the array example in the paragraph „Covariance on arrays“. Having the Add() method, one could add an instance of type object to the list and that has not to be allowed:

IList<object> list = new List<string>();
list.Add(new object());  // mustn't be allowed

Sure, that’s a big limitation, but it makes sense and is absolutely necessary!

The same comes true for the in keyword. One can define an interface with type parameter in T. With that, T can only be used as type parameter and not as return value. But this brings contravariance on the type parameters to life. Having the FlavorComparer example from above in mind? That will work, if IComparer<in T> is declared by the .NET framework. The limitation of T to be set as method parameter only is necessary due to the same aspect as for the out keyword. If IList<in T> should have been declared and one defines a variable IList<string> list and calls list.Add(new object()), then it would make no sense to iterate through all list elements as string, because the inserted object is no string and would cause problems.

So in the end, the knight’s armour is not that shiny. C# 4.0 comes with some nice covariance and contravariance features, but the out and in parameters are fairly limited (and using them together is (luckily) not allowed). Many people are annoyed about that, but I don’t share their opinion. It’s a good thing to have covariance and contravariance on type parameters separated from each other! Else this would produce heavy problems as we have seen in the examples above and in the array covariance section. My opinion is, that the language designers have done a good job here. I don’t want to have some kind of ArrayTypeMismatchException on generics and thus in/out on type parameters are a good thing.

Links:

kick it on DotNetKicks.com

On ASP.NET MVC

In this article, I want to give you some information about my experiences with the Beta-version of ASP.NET MVC. During December, I had the chance to build up an application for the administration of media elements with ASP.NET MVC and thus I got a good insight in various topics.

What is ASP.NET MVC?

ASP.NET MVC is Microsoft’s interpretation of the well-known MVC architectural pattern, bringing MVC to the ASP.NET world. It is MVC for the presentation layer, not for the whole application (that should be true for most applications). Furthermore, it is not a top part of classic ASP.NET, but it’s a completely new approach for designing/creating web applications. This implies many changes and makes ASP.NET MVC very different from classic ASP.NET in many ways.

Comparison to ASP.NET „classic“

The MVC pattern follows a strict separation of concerns principle. The Model should include the business logic and is being invoked through the Controller, which is responsible for retrieving data, choosing and calling Views with that data and handling user requests. Views include only view logic and are creating/formatting the output for a user.

ASP.NET MVC tries to overcome the disadvantages of web-forms based programming by ASP.NET. Those come mainly through the purpose of ASP.NET to make web application development feel similar to win-forms based development and thus to make the access for Windows application developers more fluent. That’s a good intent, but it brings many problems to life, because we are not in a stateful Windows application, but in a stateless web environment. While classic ASP.NET developers try hard to get a good separation of concerns to work, logic is often put too much in code behind. Furthermore, ASP.NET tries to emulate stateful behavior through saving a client-based ViewState as hidden field, which can become really big and can waste page sizes. Other problems include difficult Ajax handling, missing full control over page rendering (especially when you use web-forms) and a complex page lifecycle, which is difficult to understand and to use sometimes.

I’m thinking of ASP.NET MVC as kind of „back to the roots“. For many things you have to do more handwork, where ASP.NET gives you more comfort respectively didn’t require deep knowledge of web technologies and protocols. The intent is to give you full control of the HTML markup, but it implies that you create this markup at your own. Basically, you don’t have most of the well-known ASP.NET controls. Repeater control in ASP.NET? It’s named „foreach loop“ in ASP.NET MVC 😉 . GridView in ASP.NET? Use a foreach and a HTML table in ASP.NET MVC. That sounds cruel for most developers I spoke with about this topic. In fact it’s not the whole truth. There are some so-called „helper objects“ exposed in the views, which encapsulate basic (e.g. HTML) functionality and can be used instead of the real markup. Everyone can build up his own helper methods by using standard C# extension methods and thus extend their functionality for his own needs. Currently the helper methods cover mainly basic HTML functionality like list boxes, check boxes, buttons, forms etc.. Advanced controls are missing (yet), but it’s only a matter of time when others will provide them. The community project MvcContrib has done first steps in this direction and provides a Grid control, for instance. It’s not perfect, but it’s pretty nice code and shows up how controls can look in ASP.NET MVC. The fact why you can’t use most of the classic ASP.NET controls is that you don’t have ViewState and postbacks anymore. This implies that you can’t use any controls that rely on those principles. It forbids to use event based programming as well. Thus if you want to post form values back to the server, you have to create an HTML form and a controller action which can handle the POST verb. Thankfully there is a nice data binding concept, that gives you some support on dealing with this. If you want some kind of dynamic loading as can be done by event-based programming, use Ajax for that. ASP.NET MVC is introducing many new concepts as well: URL routing, TempData/ViewData, Helper objects, data binding, validation, … these are only some topics which you have to understand, if you are starting with ASP.NET MVC.

Beside those heavy changes and differences there are similarities to ASP.NET, too. Thus you are able to use the standard ASPX markup, which is available as standard view engine in ASP.NET MVC. Anyway, you can use most core ASP.NET features like authentication, role handling, Session, Caching etc..

In the whole, ASP.NET MVC gives you a much lower level of abstraction from basic HTML, which some will like and others not. Scott Hanselman got to the heart of that when he stated:

This is a not just a different tune, but a whole different band playing all new music. Not everyone will like the music, and that’s why the world has more than one band. This is a Good Thing.

I like to think of ASP.NET MVC as the raw, acoustic version of the more heavily produced and multi-layered ASP.NET WebForms we use today.

And to avoid misunderstandings: ASP.NET MVC isn’t there to replace standard ASP.NET. Instead it makes an alternative programming model and both technologies will be developed further by Microsoft in the future.

What music do you like?

To choose either ASP.NET or ASP.NET MVC depends on what you want to do. Nick Berardi developed a nice decision table which guides you on your choice.

Following that and my own experiences you should use ASP.NET MVC, if you want:

  • test-driven development, including your UI,
  • separation of concerns through the MVC principle with all goods, that are implied through this (logic at places where it should be, nicer architecture etc.),
  • improved team development, where different team members are responsible for different parts of the UI (Models, Views and Controllers),
  • RESTful URLs,
  • multiplicity of Views (e.g. for different output devices like PC, mobile, printer, …),
  • full control over your markup, clean and tiny HTML pages.

ASP.NET should be used in case you want to:

  • be productive in a short time (RAD/prototyping),
  • develop data centric applications (ASP.NET MVC is not the best for that due to the missing data-centric controls (at the moment) and missing data source controls),
  • make use of complex web forms (includes existing 3rd party controls),
  • use the event model,
  • get a fast entrance to web application development.

My opinion

Personally I like the development in ASP.NET MVC. It gives me more freedom than classic ASP.NET and I feel more home in there. ASP.NET MVC is in my opinion a step in the right direction. The loosely coupled components give you the flexibility to exchange or extend parts of the framework as well as to fake things out and test parts of your code separately. A main point that Microsoft has done right is to include the community in the development process and to consider their needs. The open source community project MVCContrib shows this direction of actively including the community. Furthermore, ASP.NET MVC comes with jQuery, built-in jQuery support and jQuery intellisense. Microsoft promises to support jQuery and to contribute improvements back into the jQuery development in the future. That’s a huge turnaround for Microsoft, which was fighting Open Source heavily not long ago. I think, other development teams at Microsoft should follow this example. For instance, the ADO.NET team has created so much distrust while developing the Entity Framework at its current state and it’s not much caring about community needs. Guys, time to re-think!

On the other hand, there are many things for you to dislike ASP.NET MVC. Through the lower level of abstraction and the missing ASP.NET controls you could miss some kind of comfort while creating your web applications. Furthermore, there is no direct „upgrade path“ for learning ASP.NET MVC if you have developed ASP.NET so far. For beginners in web-based application development, there is a very steep learning curve, because you have to be aware of the stateless programming model and basic technologies like HTML, CSS, HTTP and so on.

One thing to mention is that ASP.NET MVC is still in development. At this time, the RC has been released and V1 will follow in February 2009. For me and many others, ASP.NET MVC V1 is not a complete framework out-of-the-box, it’s more a basic framing which doesn’t limit developers in most things. It gives them the freedom and possibilities to realize their own opinions and principles. Phil Haack got the point:

In part, you can look at v1 of ASP.NET MVC as a Framework for building ASP.NET MVC Frameworks.

That’s a thing which I can truly sign. And it’s leading the future development. In my opinion there will come developers and build up their own frameworks on top of ASP.NET MVC, making them more narrow and including their own principles. And ASP.NET MVC allows them to do this. Moreover, that is why the ASP.NET MVC developers didn’t make their framework very opinionated. At every point there are many degrees of freedom and some people are frustrated about that, because it allows everyone to create bad code. But it’s a good thing, if others come and make their frameworks on top of ASP.NET MVC really opinionated. It’s easing the way for those people and thus I’m applauding the ASP.NET MVC team. I’m really happy to see this bare framework to come out and I’m interested to see what will have been developed in spproximately one year. For now, I’m really confident of that.

kick it on DotNetKicks.com

ASP.NET MVC RC1 released

Just a short announcement: as ScottGu stated in December last year, the Release Candidate of ASP.NET MVC has been released now and can be downloaded from here.

In the RC, the major bugs have been fixed and many little improvements have found their way to the package. All changes can be viewed in the release notes.

V1 of ASP.NET MVC is planned for February 2009, so stay tuned.

Links:

Silverlight toolkit december released

The first release of the SIlverlight toolkit a few weeks ago brought some interesting new controls, charting and theming to Silverlight. Now they enjoy us with the december release of the toolkit.

Changes in short:

  • AutoCompleteBox and NumericUpDown have made it to the stable branch
  • Charting has been improved and is now easier for you to code against (thanks!!!)
  • better designer integration
  • 3 new themes (Bureau black, Bureau blue, Whistler blue)

I love those guys and their work on the toolkit and I’m interested to see this project moving forward.

http://www.codeplex.com/Silverlight

ASP.NET MVC Tip: Got an Ajax Request?

Job-related I’m diving into this ASP.NET MVC stuff currently and will give you at this point some posts on that in the nearer future. Just for now: I like ASP.NET MVC and how MS implemented the core concepts. It’s clean, testable, flexible and extensible. Many things have changed since beyond standard ASP.NET…

Currently I’m becoming inspired by the Ajax Helpers, which ship with ASP.NET MVC. With Ajax.BeginForm(), Ajax.ActionLink() and Ajax.RouteLink() there currently (ASP.NET MVC Beta 1) exist three extension methods, which one can use after integrating the Microsoft Ajax script libraries in his page and which provide basic Ajax functionality.

At the moment I’m using Ajax.ActionLink() in my project to reload parts of my page, if the user clicks on a link. Especially I’m reloading data asynchronously, which the user changed through his click. That’s working pretty perfect for me, additionally I can serve a Confirm-Message via the AjaxOption „Confirm„, which is presented to the user before executing an action and over which the user can canel an action, too.

There’s one problem for me in this case: with the ActionLink ASP.NET MVC calls an Controller-Action. That’s happening via a special URL, which is mapped by the ASP.NET MVC routing system to an action. This action delivers with PartialView() the data (View), which are injected in the existing page with the aid of Ajax. The problem is: the user can pass this URL directly in his browser too and then he gets only those partial data in response, but not the whole page as in the case when he’s using the Ajax-ActionLink.

Some googling and testing yielded two ways for resolving this problem:

1st) One action with discrimination of the request type

First of all it’s possible to create an action, which can be invoked through both the Ajax ActionLink and the user through an URL in his browser. After including the namespace „System.Web.Mvc.Ajax“ one can use the extension method „Request.IsMvcAjaxRequest()“ in his controller action, with which it’s possible to check if the current request is coming from an ASP.NET MVC Ajax helper. Accordingly you are able to return the PartialView (on an Ajax request) or the complete view of your data (in case there’s no Ajax request). This is looking roughly as follows:

using System.Web.Mvc;
using System.Web.Mvc.Ajax;
...

namespace MyNamespace
{
    public class MyController : Controller 
    {
        ...
        public ActionResult MyAction(...) 
        {
            if(Request.IsMvcAjaxRequest()) 
            {
                ...
                return PartialView("MyPartialView", myPartialModel);
            } 
            else 
            {
                ...
                return View("MyCompleteView", myCompleteModel);
            }
        }
    }
}

Is this solution pretty? Well… Kevin Hoffman is criticizing the additional discrimination of the request type in the controller. Especially it’s coming out that Kevin sees the MVC principle violated, because this discrimination is going beyond the responsibility of a contoller (the following quote refers to an older ASP.NET MVC release, where there was an AjaxController with an IsAjaxRequest property):

MVC is all about proper separation of concerns. There’s one line of code in the sample that I think is violating that, and that’s the IsAjaxRequest property. This all smacks of someone attempting to make the MVC framework feel more like the old Postback world and quite frankly, the old postback world can eat my shorts. The controller, IMHO, is just a controller. It should not ever have to determine if it is rendering Ajax or rendering Regular. Ajax or regular HTML is a view decision not a controller decision. The job of the controller is to fetch the appropriate data required for rendering a view, and then pick the view to render.

Strongly taken I agree with Kevin from the architectural point of view. The view should be responsible to decide how some data is displayed, the controller should only deliver this data. On the other hand side my own individual opinion is that the controller should be able to decide, to which view it’s sending the data it fetches. Many controllers are doing so… e.g. they are calling an error page instead of the actual view if something goes wrong or they are redirecting to other views depending on the count of the received data. The only thing I’m worried about in this case is that the decision „Ajax-call or not“ is design-oriented and does not depend on data, which is fetched in the controller action itself, but which depends on the initial request. Though I’m not worried much about this, I’ve worked out another solution, which I’m coming up with in the following section…

2nd) Two actions with attributation

If you want to avoid a discrimination by „IsMvcAjaxRequest()„, you have to implement a second action. A first action „MyAction“ can then be called by the user via his browser and will return the complete view, where the second action -named e.g. „MyActionAjax„- could return a partial view, which is relevant for the Ajax request. This is looking as follows:

using System.Web.Mvc;
...

namespace MyNamespace 
{
    public class MyController : Controller 
    {
        ...
        public ActionResult MyAction(...) 
        {
            return View("MyCompleteView", myCompleteModel);
        }

        public ActionResult MyActionAjax(...) 
        {
            return PartialView("MyPartialView", myPartialModel);
        }
    }
}

Please identify that the basic problem still persists: the user can call „MyActionAjax“ via his browser. And here comes the trick: we’ll attribute „MyActionAjax()„, thus refusing the access. I’ve written a filter attribute, which is dealing with this:

using System.Web.Mvc;
...

namespace SDX.xMedia.mvc.Presentation.Common
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class MvcAsyncPostAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext != null && filterContext.HttpContext != null)
            {
                if (!IsMvcAsyncPost(filterContext.HttpContext.Request))
                    filterContext.Cancel = true;
            }
        }

        private bool IsMvcAsyncPost(HttpRequestBase request)
        {
            if (request == null)
                return false;

            return request["__MVCASYNCPOST"] == "true";
        }
    }
}

In this case I’m walking by foot. The Ajax helpers from ASP.NET MVC are setting the request parameter „__MVCASYNCPOST“ when performing an Ajax request. Further the extension method „Request.IsMvcAjaxRequest()“ is implemented in a way, which is only querying this value. Here is the current implementation from the ASP.NET MVC project:

public static bool IsMvcAjaxRequest(this HttpRequestBase request)
{
    if (request == null)
    {
        throw new ArgumentNullException("request");
    }
    return (request["__MVCASYNCPOST"] == "true");
}

Thus of course I can use this method for my request:

using System.Web.Mvc;
using System.Web.Mvc.Ajax;
...

namespace SDX.xMedia.mvc.Presentation.Common
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
    public sealed class MvcAsyncPostAttribute : FilterAttribute, IAuthorizationFilter
    {
        public void OnAuthorization(AuthorizationContext filterContext)
        {
            if (filterContext != null && filterContext.HttpContext != null && filterContext.HttpContext.Request != null)
            {
                if (!filterContext.HttpContext.Request.IsMvcAjaxRequest())
                    filterContext.Cancel = true;
            }
        }
    }
}

By the way: IAuthorizationFilter has been implemented, because only in this way I was able to cancel the execution of the action in the first place ( filterContext.Cancel = true; ). Now with this attribute it’s possible to mark the „Ajax-only“ action and this way to prohibit the access through the browser:

using System.Web.Mvc;
...

namespace MyNamespace 
{
    public class MyController : Controller
    {
        ...
        public ActionResult MyAction(...)
        {
            return View("MyCompleteView", myCompleteModel);
        }

        [MvcAsyncPost]
        public ActionResult MyActionAjax(...)
        {
            return PartialView("MyPartialView", myPartialModel);
        }
    }
}

Now which way is prettier? Architecturally I like the second variant with regard to the separation of concerns principle which lets the controller do the stuff it should do. But there is one unaesthetic point in my eyes: the Ajax ActionLink is referencing to the action „MyActionAjax()“ and this link is delivered to the user by his browser. The user could be confused when he wants to share this link with one of his friends and has no direct access to the controller action, which stands behind this url. Thus from a user’s point of view the first solution makes more sense, but there has to be a trade-off as the case arises and I’m agog about your thoughts.

Update for the second solution:

My problem with the second solution was the action-link, which is pointing to MyActionAjax() and thus provided to the user. Now I’ve worked out a quick and dirty work-around for that (and guess what: no I don’t like it). I’m setting up my own RouteHandler in the following way:

class AjaxRouteHandler : MvcRouteHandler
{
    protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
    {
        if (requestContext.HttpContext.Request.IsMvcAjaxRequest())
            requestContext.RouteData.Values["action"] = requestContext.RouteData.Values["action"] + "Ajax";

        return base.GetHttpHandler(requestContext);
    }
}

Now you can set up your routes with this route handler:

RouteTable.Routes.Add(
    new Route("{Controller}/{Action}/{id}",
    new RouteValueDictionary(new { Controller = "MyController", id = (int?)null }),
    new AjaxRouteHandler()));

What’s done: if there is no Ajax request, then the „normal“ action will be invoked (e.g. „MyAction“). On an Ajax-request instead there will be called the action „MyActionAjax“ automatically. Note that the programmer has to be responsible for the availability of this action pair. The benefit of that: you can provide „MyAction“ in your Ajax-ActionLink or call it via your browser and share the url with your friends. The route handler decides whether to invoke MyAction or MyActionAjax. Thus the responsibility for deciding if we’ve got an Ajax request comes out from the controller into the route handler. Please remember that I don’t have anything against having this piece of code in my controller, I’m just here to show some other way for solving this problem…

kick it on DotNetKicks.com