Code Contracts

by Danielvg 29. January 2011 16:21

Code contracts is a Microsoft Research project that is set to “..provide a language-agnostic way to express coding assumptions in .NET programs.” What this basically means is that Microsoft Research is creating the next generation of defensive programming into the .Net Framework. Code contracts provides a language based way of specifying and checking for invariants, pre and post-conditions in objects. Everyone has written defensive code like the following:

public void MyMethod(Foo foo, int length)
{
    if (foo == null)
    {
        throw new ArgumentNullException("foo");
    }
    if (length < 10)
    {
        throw new ArgumentOutOfRangeException("length", "Length cannot be less then 10");
    }
}

One of the problems with this code is that there is no comments to the parameters, so if you do not look at the implementation you have no way of knowing that Foo cannot be null and length has to be above 9. In some way this is documented by the code, but you cannot expect that everyone looks at the code. This is one of the issues Code Contracts can help with, following is the same method with Code Contracts:

public void MyMethod(Foo foo, int length)
{
    Contract.Requires<ArgumentNullException>(foo != null, "foo");
    Contract.Requires<ArgumentOutOfRangeException>(length > 9, "Length cannot …");
}

The result is the same, if you invoke MyMethod where Foo is null or length is less then 9 an exception will be throw, but wow anyone that has the Code Contracts plugin installed will be presented with the following warnings inside Visual Studio when they try to invoke MyMethod with parameters that does not follow the contracts:

image_thumb1

image_thumb6

(Some Paint manipulation has been done to show both errors at the same time )

 

What have been shown here is the static analysis (Design time) part of Code Contracts, via project properties in visual studio you can decide what part of the contracts you want at runtime. Since there is some overhead in both pre and post-conditions you can turn both off and Code Contracts will not modify the MSIL to include the contracts, thereby eliminating the overhead. Following are the two basic functions that comes with code contracts:

Requires
Contract.Requires insure preconditions, this can be parameter and object state validation, examples:

Contract.Requires<ArgumentNullException>(foo != null, "foo");
Contract.Requires(length > 9);
Contract.Requires(length > 9, "Length cannot be less then 10");
 

Ensures
Contract.Ensures sets postconditions, this is mainly to ensure object state at the end of a method and validate the return value of a method, examples:

public int MyMethod(Foo foo, int length)
{
    Contract.Ensures(foo.Price == Contract.OldValue<double>(foo.Price));
    Contract.Ensures(Contract.Result<double>() > length);
    …
}

There are a number of other functions in code contracts like: assert, assume, ContractInvariantMethod, ContractClass and ContractClassFor, but I have stuck with the basics here. Following are some snippets that are included in the Code Contract plugin:

cim
[ContractInvariantMethod]
void ObjectInvariant()
{
    Contract.Invariant(false);
}
cr
Contract.Requires(false);
crn
Contract.Requires(arg != null);
crsn
Contract.Requires(!String.IsNullOrEmpty(arg));
ce
Contract.Ensures();
cen
Contract.Ensures(Contract.Result<string>() != null);
cesn
Contract.Ensures(!String.IsNullOrEmpty(
Contract.Result<string>()));
cam
Contract.Assume(false);
cca
Contract.Assert(false);
cintf
[ContractClass(typeof(IFooContract))]
public partial interface IFoo
{
}

[ContractClassFor(typeof(IFoo))]
abstract class IFooContract : IFoo
{
}

For more detailed information on Code Contracts see http://msdn.microsoft.com/en-us/magazine/ee236408.aspx

 

UPDATE:
What I might not have made clear is that Code Contracts will compile and run on any machine, but to get “design time” warnings and the ability to decide if contracts should be included or not, then you will need the plugin .

Host does not support MVC 2

by Danielvg 8. November 2010 23:39

I have been doing a school project in MVC2 and .Net 4 for the last few weeks, and when the time came to deploy the web application to my host (surftown.dk) the fun began…

First Problem: host does not support .Net 4, reason? “The control panel does not support .Net 4”.
Solution: Somewhat easy downgrade to .Net 3.5, the only problem was Entity Framework 4.

Second Problem: MVC2 has not been installed on the host server.
Solution: Thanks to a post by Mr. Haackedthis was an easy fix, since you can deploy the MVC assemblies to the web applications bin folder (Full trust is not needed).

Third Problem: MVC2 routing has not been configured in the host IIS, aka “The website declined to show this webpage”
Solution: Change routing in Global.asax to use “{controller}.Mvc.aspx” instead of “{controller}”, this will trick IIS into routing as expected by MVC2.

Example:
From:

routes.MapRoute("ProfileSearch", "Profile/Search/{query}", new { controller = "Profile"
                action = "Search" });

routes.MapRoute("Default", "{controller}/{action}/{id}"
        new { controller = "Home", action = "Index", id = UrlParameter.Optional });

routes.MapRoute("ProfileView", "Profile/{nickName}", new { controller = "Profile"
               action = "Index" });

To:

routes.Add(new Route("{controller}.mvc.aspx/{action}", new MvcRouteHandler())
{
    Defaults = new RouteValueDictionary(new { controller = "Home" })
});

routes.Add(new Route("{controller}.mvc.aspx/{action}/{query}", new MvcRouteHandler())
{
    Defaults = new RouteValueDictionary(new { controller = "Home", action = "Search" })
});

routes.Add(new Route("Profile.mvc.aspx/{nickName}", new MvcRouteHandler())
{
    Defaults = new RouteValueDictionary(new { controller = "Profile" })
});

The downside is that URLs are ugly ugly ugly.
From “/Profile/MyNickName” to “/Profile.mvc.aspx/MyNickName”

Tags: , ,

Code

First Look: Managed Extensibility Framework (MEF)

by Danielvg 14. January 2010 18:36

MEFis a new framework set to simplify the creation of extensible applications, it will ship with the .Net 4 Framework later this year, but there is a preview included in the beta2 version of .Net 4.
I will here try and cover some of the basics by creating a small pointless application, if you want more advanced information and more code examples then the standard documentation is very nice!

MEF pretty much works as an IoC Container, you put everything into a mixing bowl and the rest is just magic. With MEF, attributes are used to mark what properties are dependencies and what objects can be used for injection. These attributes are [Import] for dependencies and [Export] for injectable objects.

The first example is a basic logger function for a WPF app, the logger is injected by MEF, notice the use of Import and Export attributes:


using System.Collections.ObjectModel;
using System.ComponentModel.Composition;

namespace Demo.Mef
{
    public interface ILogger
    {
        ObservableCollection<string> Logs { get; }
        void Log(string message);
    }

    // We set the Logger class to be exported as ILogger
    [Export(typeof(ILogger))]
    public class Logger : ILogger
    {
        private ObservableCollection<string> logs = new ObservableCollection<string>();

        public void Log(string message)
        {
            Logs.Add(message);
        }

        public ObservableCollection<string> Logs
        {
            get { return logs; }
        }
    }

    public partial class MainWindow : Window
    {
         // Mark the Logger to be imported by MEF
         [Import]
         public ILogger Logger { get; set; }

      }
}

Having defined exports and imports the only thing left to do it create the container and mix everything. MEF uses a CompositionContainer as its mixing bowl, the container is able to take catalogs and look through them for known attributes.

using System.ComponentModel.Composition;

namespace Demo.Mef
{
    public partial class MainWindow : Window
    {
        // Mark the Logger to be imported by MEF
        [Import]
        public ILogger Logger { get; set; }

        public MainWindow()
        { 
            InitializeComponent(); 
            Compose(); 
        }

        private void Compose()
        {
            // AssemblyCatalog takes an assembly and  looks for all Imports and Exports within it
            var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
            // Create the container with the above catalog 
            var container = new CompositionContainer(catalog); 
            // Here we tell the container to mix everything up
            container.ComposeParts(this);
        } 
    }
}

And that is about it, when you run the above code MEF will look through the running assembly for import and export attributes and try to make everything match.
If you want to make sure that all Imports are filled before doing anything else then the interface IPartImportsSatisfiedNotification will help you. If your object implements the interface the method OnImportsSatisfied() will be called.

 

Nothing fancy there, most of the above could be done with Unity, so on to the next example that builds on top of the previous example.

In the following example MEF looks for buttons with the Export contract “Demo.Mef.MenuItems” in all assemblies found in the PlugIns directory.  Then when the form has loaded and MEF is done, all the buttons found are added to a stackpanel.

The following is located in a separate assembly that builds to /PlugIns/, it is simply a button with some behavior and most importantly two attributes.

namespace Demo.Mef.Extra
{
    // Mark the class as export with the contract Demo.Mef.MenuItems
    // so it can be matched with the contract in the main app(),
    // this could be used as a filter
    [Export("Demo.Mef.MenuItems", typeof(Button))]
    // This attribute makes MEF create a new instance each time the button is requested
    [PartCreationPolicy(CreationPolicy.NonShared)]
    public class MessageBoxButton : Button
    {
        public MessageBoxButton()
        {
            this.Content = "PresssMeee";
            this.Click += new System.Windows.RoutedEventHandler(MessageBoxButton_Click);
        }

        void MessageBoxButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            MessageBox.Show("Yes this demo also has Hello world!");
        }
    }
}

Since we want more then just one button in the menu we use the Import attribute ImportMany which fills the property with all the Export buttons MEF was able to find with the specified contract

[ImportMany("Demo.Mef.MenuItems")]
public IEnumerable<Button> MenuItems { get; set; }

To make MEF look in the PlugIns directory a few changes has to be made to the Compose method in the main application:


private void Compose()
{
    // AssemblyCatalog takes an assembly and  looks for Imports/Exports within it
    var assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
    // DirectoryCatalog takes all assemblies within a given dir and looks for Imports/Exports
    var directoryCatalog = new DirectoryCatalog("PlugIns");

    // AggregateCatalog holds multiple  ComposablePartCatalogs
    var aggregator = new AggregateCatalog();
    aggregator.Catalogs.Add(assemblyCatalog);
    aggregator.Catalogs.Add(directoryCatalog);

    var container = new CompositionContainer(aggregator);
    container.ComposeParts(this);
}

Only thing left to do now is add the buttons to the stackpanel, as said we can use the IPartImportsSatisfiedNotification interface to make sure MEF is done.

public void OnImportsSatisfied()
{
    foreach (var menuItem in MenuItems)
    {
        stackPanelMenu.Children.Add(menuItem);
    }
}

That is about it, should I want to add a new button to the menu all it takes is a button with the export attribute, no need to recompile the main application just drop the dll in the PlugIns directory and the button is added next time the application is started! While all of this has been possible before it is very nice to get an easy integrated way of creating extensible applications.

The result of the above code:

 image

Source code can be found here Demo.Mef.zip (39,03 kb)

 

On a side note, I am somewhat confused about MEF vs Unity vs PRISM and will try to make a post about it soon.

Tags: , , ,

Code

Tuples in .Net 4 (System.Tuple)

by Danielvg 2. January 2010 15:16

.Net 4 brings with it the Tuple type! I have never worked with tuples in programming before and have a hard time seeing their purpose but here is an example of a tuple in C#:


var tupleOne = new Tuple<int, string>(1, "Hello World");
Console.WriteLine("Tuple contains: " + tupleOne.Item1 + " and " + tupleOne.Item2);

There are also some factory methods for creating tuples:


var tupleTwo = Tuple.Create("Hello World", 2010);
var tupleThree = Tuple.Create("Hello World", 2010, new SomeClass());
Console.WriteLine("Tuple contains: " + tupleThree.Item1 + ", " + tupleThree.Item2 + " and " + tupleThree.Item3.MyProperty);

Tuple facts:

  • Tuples are immutable
  • Tuples are reference types
  • Located in System.Tuple
  • Can take up to 8 generic parameters, but can contain an infinite number of elements.
  • Elements are always named Item1, Item2… Item7, Rest

See msdn for more information.

Tags: , ,

Code