Browsing:

Tag: C#

Castle Windsor and ASP.NET MVC 3 extremely simple example part 1

Castle Windsor is an Inversion of Control Container which has excellent documentation, written by Krzysztof Koźmic. Krzysztof has written a perfect tutorial on ASP.NET MVC 3, which I thought I would follow. And then I found that Castle Windsor is extremely easy and transparent to use. And it has a cool name at that.

What again is Inversion of Control and why ever would I use it?

Suppose you develop a member administration tool and the customer wants to use an MySQL database. But you coded the app with Linq to SQL. Wouldn’t it be nice if you could just change your ORM from L2S to EF? Or Nhibernate?
Or, what if you coded your app with an object database, and then later you find that the customer has a DBA who is absolutely against NoSQL?
The same goes for the logging framework. Which one? Log4Net or Elmah?

With IOC you can just pick and choose which framework you plug in. When you start with one choice of a product, you are not bound to it.

It’s called Inversion of Control because it’s an inverted API. With an API, you use the methods it exposes. With IOC, you let your application choose which API to use. Huh? Yeah. Because when your app spins up, it uses reflection to get all the dependencies you configured within your container. Now, does that make any sense?

A simple example

Here’s how the principle works.
In an ASP.NET MVC architecture, there is a Model, a View and a Controller. The Controller sits between the Model and the View, so the Controller would be a good place where we can inject some dependencies. How to inject these dependencies? Well, by their constructor.
The default controllerfactory has a parameterless constructor, so we need to override that, by creating a new class. E.g. WindsorControllerFactory. And we let our controllerfactory inherit from DefaultControllerFactory.
We need to override two methods: ReleaseController (so that he Windsor Controller is released) and getControllerInstance (which returns a Windsor Controller). This bit of plumbing code just provides the MVC runtime with new instances of the controller type for each request and when the request ends, it releases the controller.

Next, we need to register the controllers in to the container with an Installer, like this:

This is how we register types in the container, so there will me more of these classes later.

Now we need to bootstrap this in global.asax:

And then we are ready to roll.

In part 2 I will show how to create some interfaces and inject them in the controller.

Here is the complete example.


Nhibernate, ASP.NET MVC 3 and Ninject

In this post I said something about dependency injection and that we all should, well, inject dependencies. Why? To make our applications loosely coupled. In an ASP.NET MVC 3 application, I don’t want my Views to know what is in my persistence layer. Hell, I don’t even want my Controllers to have a notion. And I want to be able to change the Entity Framework with Nhibernate or DB4o.

And since I have this obsession with Nhibernate lately, this post is again about Nhibernate. And Ninject.

Wire up Nhibernate in ASP.NET MVC 3

A Nhibernate Session is very cheap and does not require too many resources. So, we’re setting up a session per web request, in Global.asax. The session opens when the request begins and closes when the request ends. I already blogged about that here. This also how Ayende demonstrates this in the Tekpub series.
Global.asax is also the place where we wire up Ninject. Download Ninject.Web.Mvc and Ninject from here rather than from Github, because strange things happen if you don’t.

Now, take a look at my very bloated Global.asax:

Sorry for that.

So, when we issue a webrequest, a Nhibernate Session is established. A Session in Nhibernate is the same as a Unit of Work. It’s also comparable with the Linq to SQL’s datacontext.
Now let’s create a PersonRepository interface:

[code language=”csharp”]
using System.Web;
using Concepts.Core;

namespace Concepts.Web
{
public interface IPersonRepository
{
IQueryable<Person> GetPersons();
}
}
[/code]

And implement the interface with Nhibernate:

[code language=”csharp”]
using System.Web;
using NHibernate;
using Concepts.Core;

namespace Concepts.Web
{
public class PersonRepository :IPersonRepository
{
private ISession _session;
public PersonRepository(ISession session)
{
_session = session;
}
public IQueryable<Person> GetPersons()
{
return _session.CreateCriteria<Person>().List<Person>().AsQueryable();
}
}
}
[/code]

Now the Dependency Injection trick. We’ll use Ninject to bind the IPersonRepository to our PersonRepository, and to bind the ISession to the method GetCurrentSession from Global.asax:

[code language=”csharp”]
using System.Web;
using Ninject.Modules;
using NHibernate;

namespace Concepts.Web
{
public class ConceptsNinjectModule : NinjectModule
{
public override void Load()
{
this.Bind<IPersonRepository>().To<PersonRepository>();
this.Bind<ISession>().ToMethod(x => MvcApplication.SessionFactory.GetCurrentSession());
}
}
}
[/code]

And now we can inject our HomeController with the IPersonRepository.. ! When we fire up our controller methods, Ninject sees that we implemented the PersonRepository, which uses Nhibernate. And this, ladies and gentlemen, is so cool, it hurts.

You can get the complete source code here.


Nhibernate Many-to-Many Mapping with extra attributes on the relationship

I dropped the Fluent from Nhibernate. I just wanted to experience the whole manual XML mapping thing. Well, it turned out not to be a bad experience at all.

Member registration app

I’m writing a member registration application. There are members and these members live on one or more addresses. Some addresses have more members. And on top of that, the relationship itself has some characteristics. Is it a postal address? Is it a temporary address?
This is the classical many to many relationship. How to map that in Nhibernate?

I decided to create two one-to-many relationships and a special relationship class. Here is the class diagram:

As you can see the PersonAddress class has some extra attributes for the relationship: there are two one to many relationships, from Address to PersonAddress and from Person to PersonAddress.

This is the Person class:

As you can see in line 13 I use the Iesi.Collections.Generic.ISet. It maps to an Nhibernate set (which is an IList). There should be an ISet interface in .NET Framework 4.0, but I need to investigate that further. For now, I’m using the ISet.

The Address class has a similar signature:

And then finally there is the PersonAddress class that maps the Person and the Address in a many-to-many relationship:

Object-relational impedance mismatch

Now we will use Nhibernate to solve the object-relational impedance mismatch which in itself is awesomely cool. Because, what is that thing with a RDBMS? Well, a relationship between two tables is defined in one table by adding a foreign key and then the relationship is bidrectional by default. In OOP, it does not work that way. If I add a collection of addresses as a property from a person, the address does not know anything about the persons that may live there. I have to create a collection of persons to the the address class as well (as I did in the above mentioned code). I have to, because I want to know on which addresses a person lives, but I also want to know which persons live on a certain address.
So here is how we map the Person class to the RDBMS:

Remember the ISet Addresses in the Person class? (virtual public Iesi.Collections.Generic.ISetAddresses { get; set; }). In this mapping file, I defined a set with the name Addresses. And that is how it maps. But the other stuff is also important:

  • inverse=true means, this side is the relationship owner in a bi-directional relationship. If I omitted inverse=true, then Nhibernate would try to execute two different SQL statements.
  • cascading: all-delete-orphan – when an object is saved, updated or deleted, check the associations and save/update/delete all the objects found. When an object is removed from the association and not associated with another object (orphaned), then also delete it. When the person object is deleted, the PersonAddress object will be deleted.
  • The keycolumn is PersonId, in the PersonAddress object. (It is the foreign key).
  • The one-to-many class is the PersonAddress class

This is how I would map the PersonAddress class:

Notice that PersonAddress has a many-to-one relationship with both Person and Address.

Address is, again, similar to Person:

There we go. So, the important things are:

  • inverse=true
  • one-to-many versus many-to-one
  • defining the key column
  • transitive persistence: know the lifecycle of your objects (set by the cascade attribute).

Creating the databasetables

Nhibernate has the possibility to create tables from the mappings.
First you need to create a database and the Nhibernate creates the tables. And the relationships. Which again is pretty cool. This is how you do that:

This is the generated schema:

It looks OK to me! See how it correctly created the relationships!

You can check the whole thing at Github. Be sure to alter your connectionstring in App.Config.
Maybe you see something that is completely wrong or against good practice. I’d be happy to hear it!

Next time I’ll cover Nhibernate, ASP.NET MVC 3 and Dependency Injection.


Fluent Nhibernate and ASP.NET MVC

For those of you who follow our personal tweets (yeah we have to tweet more with our @itsletnl account), you probably noticed how we’re currently involved (or obsessed) by Fluent Nhibernate. Fluent Nhibernate FTW!

Itslet Fluent Nhibernate

Fluent Nhibernate uses poco mappings instead of XML mapping, like its big brother Nhibernate. There is no strong argument to use Fluent Nhibernate instead of Nhibernate, it is just a matter of taste to me. Although, Fluent Nhibernate can automap and autopersist your entities, based on convention, and Nhibernate cannot.

Getting started with Fluent Nhibernate is very simple. Just read their excellent getting started guide. It doesn’t make much sense to repeat that on this website with different entities.

But how do we get started with ASP.NET MVC? How do I connect with the Fluent Nhibernate session gracefully?

Handling sessions

I used the book of Jason Dentler to find out more. The most common pattern in web application is the session-per-request. We open the session when the request begins and close it when it ends.

Nhibernate has a contextual session feature which allows a session to be associated with some application specific scope (unit of work). You need to set the current_session_context_class property in the hibernate-configuration section of web.config. But as we use Fluent Nhibernate, we have to use the ‘ExposeConfiguration’ method.

Here is my Global.asax.cs. Check out line 45: .ExposeConfiguration(c => c.SetProperty(“current_session_context_class”, “thread_static”))’.

Now we can refer to that session in our controller, like this:

In the example the person is fetched from the database. But to make the app more production worthy, we would use dependency injection rather than directly access the current session. Also, we would not have exposed our connectionstring like that.
But that is a completely new blogpost.


Entity Framework Part 5 Model First : Create a database with the Complex Types.

A cool feature we are gonna try out in the model first architecture of the entity framework are “Complex Types” a container for property values who are not entities, but a collection of fields that are in line in a table row, a set of columns or properties and not necessary tables itself, to keep a nice clean application based model and have your attributes grouped together.

Model First and Complex Types add new features and possibilities:

We are going to build a console app with Entityframework 4 and name it MyShoeShoes. First we add a new item and choose the ADO.NET Data Model. We choose the empty model:

We call the Model shoe.edmx and now we are going to add our first new entity called: ‘Shoe’ in the Model Browser

Right click-> add a complex type instead of table rows. With Complex Types you can group together specific collections. In the Model browser you see the Complex type, here we add new lines, Add -> Scaler Property- we add extra shoe properties, in this case a group of ShoeTypes; Heels, Sneakers, Boots etc.

Now we have created Complex Types that do not show up in the design surface, that is for entities only.

Now all we have to do is right click the Shoe entity and choose ‘add Complex Property’ and name it ShoeType and it automatically sets it to the complex type we’ve just created: ShoeType.

Now we are going to add a hierarchy, which inherits from the Shoe entity with some extra details we want to use with the Shoe entity. We create an entity and set the base type to Shoe. Now remember this model is a ConceptualEntityModel and we can always tweak this in the database later!

Next entity we create is the ShoeDescription and add an association to it on Shoe, so it links to the Shoe table.

Our model is ready: We have Shoe with a grouped ShoeType, so we can index our ShoeTypes on Type-a-Shoe, We created a Shoe Colour Hierarchy to Shoe, Since one ShoeType can have many colours and a table ShoeDescription always has a relation in Shoe.

Maybe you’ve noticed that our console app gives an error when you try to built the app: “Error 11007:Entity type ‘EntityName’ is not mapped when Entity is only mapped to function import” No worries! this error will be solved as soon as we build our database, as the database is generated it will create the mappings for you.

We have all the data we need for our application so it’s time to generate a database from this model

The next steps are very easy, we are asked to choose a data connection, don’t get distracted by the Shoe.dbo line, we choose a “New Connection” since we have built a brand new Model to create a database from. The connection string is created here as well.

Set the connection Properties and name the new database, we call it MyShoeShoes:

The next step generates a dll file, but this is not run automatically,  we need to create the tables in our database. The database dll will be generated by a so called T4 template and can be modified.

When we look into the generated DLL, we see that the associations are created and it sets the ID as primary key, We call this Table per type, it creates the hierarchy Shoecolor as it’s own table with a Shoe_ prefix: ‘Shoe_Shoecolor’ in the database.

We have to manually run this query in the SQLServer, since the RTM is not completed in VS2010 EF4, but this is just a matter of time. Now refresh the MySHoeSHoes database and pop the tables are generated:

We have now created a complete database from a Model we built in Visual Studio with EF4, how cool is that!