Update MVC4 project to MVC5 within Visual Studio

If you are using VS2012 and start a new ASP.NET MVC4 project, you will be greeted by an enormous list of packages which can be updated when clicking through to the NuGet package managers.

Capture01

 

With the new release of Visual Studio 2013, MVC5, WebAPI2,… a lot of new binaries are ready to be used in your application. So updating the packages in Visual Studio should get you going. After clicking “yes” and “I agree” several times though, you will receive this error message:

broken

If you now close the NuGet package manager and then open it again, only one package needs to be updated at the moment (ANTLRv3). So click update once more.

If you now start the application, instead of receiving a nice MVC start screen you will run into a yellow screen of death:

yellowscreenodeath

 

We are almost there. Navigate to the Web.config inside of the Views directory and change all references from MVC 4.0.0.0 to 5.0.0.0 and the Razor version from 2.0.0.0 to 3.0.0.0. I’ve included the changes in this gist.

You are now ready to go!

UPDATE: Ran into this MSDN article which shows you the steps I mentioned and more!

MetroMvc with dotless

I ran into the MetroMvc GitHub project a week ago. It contains stylesheets to give your web application a Metro look. The only downside being it uses a 3rd party tool to convert the .less files into .css.

In order to address this issue I’ve forked the project and made the necessary changes to make it work with the dotless NuGet package.

You can get it here.

SignalR, Ninject and WebActivator sitting in a tree

On a project I’ve been working on I’ve been having some issues with combining these technologies. We already had an MVC application running using Ninject to wire everything together.

The Ninject MVC package, which you can install via NuGet, uses WebActivator to initialize the kernel. WebActivator enables you to wire up different packages without the need of putting everything in your Global.asax, it’s also more powerfull compared to the default PreApplicationStartMethod attribute which WebActivator actually leverages so you can have multiple startup methods in your assembly.

In SignalR I needed my own ConnectionIdGenerator. The framework has been build to allow an IoC container to manage dependencies so it was trivial to add my custom class. I just added one line to my RegisterServices method in the NinjectMVC3 class which is added in the App_Start folder when you add the Ninject MVC package. By default this code is wired up by the PreApplicationStartMethod of WebActivator.

private static IKernel CreateKernel()
{           
    //more wire up stuff
 
    kernel.Bind<IConnectionIdGenerator>().To<MyConnectionFactory>();
    GlobalHost.DependencyResolver = new SignalR.Ninject.NinjectDependencyResolver(kernel);           
}

Everything was looking good and it worked.

Sometimes.

Occasionally I could see that my own ConnectionIdGenerator was being used and sometimes the default ConnectionIdGenerator that ships with SignalR was still active. I could not really find usefull information on the web and moved code around from WebActivator to the Global.asax file and back again. Even changing the order of steps that were executed to see if that had any effect, but nothing really worked.

I went back to the Signlar Wiki and reread the page on extensibility and especially the part about changing the DependencyResolver.

It clearly states that you need to configure SignalR first and ASP.NET MVC later. A bit more down on the page it’s stated that when you want to use another DependencyResolver and if you are using WebActivator, you need to wire it up in the PostApplicationStart.

Clearly there were more moving pieces than I had thought.

So, working with this new insight, I removed all MVC configuration code that was in the Global.asax file, where it happens by default when you create a new project, and moved it to a method which I decorated with the PostApplicationStartAttribute.

[assembly: WebActivator.PostApplicationStartMethod(typeof(MyNamespace.App_Start.NinjectMVC3), "PostStart")]
 
public static void PostStart()
{
    GlobalHost.DependencyResolver = new SignalR.Ninject.NinjectDependencyResolver(bootstrapper.Kernel);
    RouteTable.Routes.MapHubs();
 
    AreaRegistration.RegisterAllAreas();
 
    RegisterGlobalFilters(GlobalFilters.Filters);
    RegisterRoutes(RouteTable.Routes);
}

Running the application again clearly showed everything was in the right place now. SignalR was now properly configured to use my own Ninject kernel. The kernel itself is still being constructed and configured in the PreApplicationStart phase, SignalR and MVC are configured in the PostApplicationStart phase.

Getting started with node.js tutorials and books

I found these great resources to get me going with node.

Totally new to it? Take a look at this video from the creator of node himself.

If you are unafraid and want a bit more lenghtly tutorial, in which you actually create something following best practices, you should check out nodebeginner.org. I was able to compare a lot of the instructions with my own way of working in .net.

Hands on node.js is an ebook with accompanying exercises, great for a more traditional way of learning. The first part of the book is free and the full version will only set you back a few dollars.

Finally there’s another Manning book under way, you can already grab the MEAP.

There’s plenty more out there but I found these to be the most helpful for me.

Legacy Code Retreat Leuven

On Saturday I spent the day near Leuven on the first publicly published Legacy code retreat. We were given an existing code base which seemed rather small, I guess around 400 lines of code, but after digging a bit deeper my colleagues and I found out that it was quite a monster.

Several techniques were covered. Subclassing to override behaviour, introducing a golden master, moving behaviour in collaborating classes and making “pure” functions.

The golden master is probably best suited if you encounter a black box and need to make a change. The code base had a bunch of console.writelines so if you redirect the output and run the applications a number of times with different kinds of input, 10000 times was suggested as a good number, you end up with a number of test files. With those in place can then make the change and compare the new output with your golden master. Automate this and you have a reasonable case. It all depends on having some kind of instrumentation in place so you can harvest this kind of information.

Creating subclasses to override, or rather get around, methods in order to test which paths the program flow follows is something I had done before. Heck you even do that with “new” code when you’re stubbing/mocking, but we were not allowed to use any sort of framework so we had to hand roll them. This eventually leads to a situation where you’re testing more the subclass rather then the system under test.

The answer to that resulting code base is to abstract the code you have to other new classes which are injected through the constructor. Typical dependency injection and inversion.

The last technique was the most eye opening to me. It was suggested to make “pure functions”, meaning any method you wrote was not allowed to directly change the object state. Somehow I was able to see code duplication and underlying algorithms a lot faster throughout the code base. Probably need to look a bit into functional programming as it was quite interesting.

The last two iterations we were allowed to keep the code we were working on, in sharp contrast to a normal code retreat, wich gave us some more sense of accomplishment by improving the code base.

I really liked my first code retreat, gave me a change to work with people who work in different parts of the industry, embedded programming to name one and from different parts of Europe.

Looking forward to the next one.

Plugging in your own Membership provider

Somebody who followed an ASP.NET course with me couldn’t find the necessary plugs to add your own providers to the .NET infrastructure. Since more will probably benefit I’m sharing with you all the necessary steps.

So you have your users stored somewhere in a database and can’t use the out of the box implementations that ship with the .NET framework. What are the steps that you need to do?

First, create a class that inherits from the abstract MembershipProvider and implement all the functionality you want to support. The more you add the better all the components that rely on it will be able to function. To just get beyond an MVC3 login page or a login with an ASP.NET webcontrol you just need to implement the validate user method.

//other methods omitted for brevity
public override bool ValidateUser(string username, string password)
{
    //here you'll connect with your custom database or service
    using (var context = new MyUserContext())
    {
        var user = context.MyUsers.Where(x => x.Name.Equals(username)).SingleOrDefault();
        return user != null;
    }
}

For this demonstration I’m just checking if I have a user with the same username in my database.

With our class in place we now need to plug it into the provider model, open your web.config navigate to the system.web node and configure your provider. If you added any additional configuration properties in your custom provider you can configure them there as well.

<membership defaultProvider="MyMembershipProvider">
    <providers>
        <clear/>
        <add name="MyMembershipProvider" 
             type="MvcApplication2.MyMembershipProvider" 
             applicationName="/" />
    </providers>
</membership>

Done.

More guidance can be found on MSDN.

Entity Framework 4.1 – One To One Mapping

In the snippet below you can see that a customer has an address property.

    public class Customer
    {
        public Customer()
        {
           Address = new Address();
        }
 
        public Guid Id { get; set; }
        public string Name { get; set; }
        public Address Address { get; set; }
        public Guid AddressId { get; set; }
    }
 
    public class Address
    {
        public Guid Id { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string Street { get; set; }
    }

The database that gets generated though defines this as a one to many relationship.

Which is not what you’re expecting, or is it? I haven’t defined any restrictions on the address class so indeed an address could be shared between multiple customers. Let’s change that.

    public class Customer
    {
        public Customer()
        {
           Address = new Address();
        }
 
        public Guid Id { get; set; }
        public string Name { get; set; }
        public Address Address { get; set; }
 
    }
 
    public class Address
    {
        public Guid Id { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string Street { get; set; }
        [Required]
        public Customer Customer { get; set; }
    }

I’ve added a navigation property from Address to Customer and marked the Customer property as required. This basically is telling EF that there is a one to one mapping between the two and the primary key of the customer should be used in the relationship. The primary key of the customer will also become the primary key of the address. If you did not add the required attribute you’ll get an invalidoperationexception saying that it’s unable to determine the principal end of an association.

You can also use the fluent api.

    public  class  CustomerContext
        : DbContext
    {
        public IDbSet<Customer> Customers { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Address>().HasRequired(x => x.Customer);
            base.OnModelCreating(modelBuilder);
        }
 
    }

They both result in the same database structure.

What if both ends are required? A customer always has an address and an address always has a customer. Marking both ends as required will again result in the same exception as before.

In order to model this you have to use the fluent api and there are two ways to achieve the desired result.

    public  class  CustomerContext
        : DbContext
    {
        public IDbSet<Customer> Customers { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Address>()
                .HasRequired(x => x.Customer)
                .WithRequiredDependent(x => x.Address);
            base.OnModelCreating(modelBuilder);
        }
    }

I’m saying here that the address entity has a required customer property and that the customer class is actually in charge, MSDN reference.

Resulting database structure:

Another way to achieve the same result:

    public  class  CustomerContext
        : DbContext
    {
        public IDbSet<Customer> Customers { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Address>()
                .HasRequired(x => x.Customer)
                .WithRequiredDependent();
            modelBuilder.Entity<Customer>()
                .HasRequired(x => x.Address)
                .WithRequiredPrincipal();
            base.OnModelCreating(modelBuilder);
        }
    }

MSDN link on WithRequiredPrincipal.

You saw that the WithRequiredPrincipal and Depedant actually have one taking a lambda and one with no arguments. This allows you to exclude a navigation property and still get a proper one to one mapping. Which brings me back to my starting point.

public class Customer
    {
        public Customer()
        {
           Address = new Address();
        }
 
        public Guid Id { get; set; }
        public string Name { get; set; }
        public Address Address { get; set; }
    }
 
    public class Address
    {
        public Guid Id { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string Street { get; set; }
 
 
    }
 
    public  class  CustomerContext
        : DbContext
    {
        public IDbSet<Customer> Customers { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Customer>()
                .HasRequired(x => x.Address)
                .WithRequiredPrincipal();
            base.OnModelCreating(modelBuilder);
        }
    }

Entity Framework 4.1 – Component mapping

By default if you add ‘simple’ property types to your class (strings, ints,…), they are all translated into columns in the database. What if you had a group of properties that actually can have some functionality together. You also have this group of properties coming back at several places in your code base. You could introduce a base class in order to improve duplication but if the two entities are not really related you should stay away from overusing the inheritance approach. What you need here is a complextype. It was present in previous releases of the Entity Framework and can be used in 4.1.

We’ll modify the customer class posted below into something a bit more object oriented.

    public class Customer
    {
        public Guid Id { get; set; }
        public string Name { get; set; }
        public string City { get; set; }
        public string Country { get; set; }
        public string Street { get; set; }
    }

Customer could also have a bunch of methods that acted upon the address fields, Employee could have the same properties, the same logic and an invoice probably also has an address. So let’s move the properties, and logic, into a new class called Address. I don’t want a separate table that contains all the addresses though, I want all of the address fields to be present in the customer, employee and invoice table.

In order to achieve that result you need the ComplexType attribute.

    public class Customer
    {
        public Customer()
        {
            Address = new Address();
        }
 
        public Guid Id { get; set; }
        public string Name { get; set; }
        public Address Address { get; set; }
    }
 
    [ComplexType]
    public class Address
    {
        public string City { get; set; }
        public string Country { get; set; }
        public string Street { get; set; }
    }

Using the ComplexType attribute will result in a database table with the correct structure.

You can also use the fluent API to configure a complextype.

    public  class  CustomerContext
        : DbContext
    {
        public IDbSet<Customer> Customers { get; set; }
 
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.ComplexType<Address>();
            base.OnModelCreating(modelBuilder);
        }
 
    }

Entity Framework 4.1 – Change mappings at runtime

In v1 and v4 of EF I’ve been using this little gem, with a small tweak, to change the mappings of the model at runtime.

I was wondering how I could achieve something similar in version 4.1 code first. By design the OnModelCreating method is used to change the mappings of your model but it is only fired once per AppDomain since building it up does incur some performance penalty and normally your database schema does not change magically. In an application I’ve build though every customer gets his own tables, schemas etc. so hooking up some configuration logic in the OnModelCreating was out of the question since it’s only executed once.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //not possible, only executed once
    var tableName = _schemaService.LookupTheTableName(loggedInCustomer);
    modelBuilder.Entity<Customer>().ToTable(tableName);
    base.OnModelCreating(modelBuilder);
}

Useless approach since the model isn’t being build again.

MvcApplication1Context myContext = new MvcApplication1Context(customer1, schemaService);
var csts = context.Customers.ToList();
 
//will go to the same tables as before, because OnModelCreating is only executed once
myContext = new MvcApplication1Context(customer2, schemaService);
var otherCsts = context.Customers.ToList();

There is a constructor though on the DbContext class that takes a compiled model and using that one does allow you to tweak the mappings you are using in your application. This also allows you to work with models that have been generated with a designer from 4.0 to use with the DbContext API.

//build config from scratch
DbModelBuilder builder = new DbModelBuilder(DbModelBuilderVersion.V4_1);
builder.Configurations.Add(new EntityTypeConfiguration<Customer>());
 
//lets change something for each customer
var schemaName = schemaService.LookupTheTableName(loggedInCustomer);
builder.Entity<Customer>().ToTable(schemaName);
 
//use the constructor that takes a compiled model
context = new MvcApplication1Context(builder.Build(context.Database.Connection).Compile());

You could then cache the compiled model for each customer so you don’t need to take that hit every time. Works like a charm. I’ll try to make it a bit easier to use.

Entity Framework 4.1 – Supporting Enums

One of those features you think are so trivial are hard to miss if you use that latest new tool. One of those is enum support in Entity Framework 4.1, just like in all other versions of the framework it just isn’t there.

There is though a way to get around it, unfortunately it does mean changing your model just a tiny bit.

In the sample class model I used for my previous posts on mapping inheritance each movie had an enum value to hold its media type, DVD, Bluray,…

You won’t see it mapped by default in your database if you use Entity Framework 4.1 out of the box. So having the enum property there isn’t enough, you have to explicitly add an int property like below.

[Required]
public virtual EMediaType MediaType { get; set; }
 
public virtual int MediaTypeId
{
    get { return (int)MediaType; }
    set { MediaType = (EMediaType)value; }
}

And change your model mapping a bit inside your DbContext class if needed.

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
     modelBuilder.Entity<Movie>()
        .Property(x => x.MediaTypeId)
        .HasColumnName("MediaType")
        .IsRequired();
 
    base.OnModelCreating(modelBuilder);
}

You can still use the enum property in the rest of your application, which I encourage.