ASP.NET MVC 4 has, REAL EMPTY PROJECT!

June 5th, 2012 Phillip No comments

I installed Visual Studio 2012 over the weekend, and was BLOWN AWAY when I created a brand new MVC 4 project to find:

spacer

See that ‘Empty’ project… It now creates:

spacer

Look at that, nice and clean. It still forces the whole WebApi thing on you, but atleast they cut out 90% of the rubbish that was in it previously.

I’m REALLY happy with the changes after I previously ranted earlier this year:

www.philliphaydon.com/2012/02/mvc-4-project-templates-are-stupid/

Thank you Microsoft!

Categories: MVC Tags: mvc4

Using NHibernate with ServiceStack

June 5th, 2012 Phillip No comments

A few people have asked me how they can use ServiceStack with other persistence technologies like RavenDB and NHibernate, or if you really must… EntityFramework… Rather than ServiceStack.OrmLite or ServiceStack.Redis like many of the examples in SS show.

Note: This isn’t about best practice on using NHibernate or ServiceStack, my services are named just to quickly get something up and running.

Note2: This blog post may not be completely inline with the GitHub repository since I will be updating the repository to include some additional samples in the future.

I’ve created a small sample project which can be found here on GitHub, I plan to flesh it out a little bit from the date this is posted, but it’s purely there as a sample.

No Repositories!

Utilizing other persistence frameworks is really easy with ServiceStack, the thing with ServiceStack Services is that they are doing something concise, it’s a single service implementation, so there’s really no need to use repositories for them, you gain absolutely no benefit from using repositories other than adding an additional layer of abstraction and complexity to your services.

That doesn’t mean you don’t have to use repositories, if you REALLY want to use them. You can, and I’ll add a sample of using a repository with the RestService implementation.

Setting Up SS

Assuming you’ve setup NHibernate and your mappings, all we need to do is setup ServiceStack.

First things first! Install ServiceStack.

PM> Install-Package ServiceStack

Note: You can use ServiceStack.Host.* (replace the * with MVC or ASPNET) which will automatically configure the web.config. Personally I prefer to do it myself.

Using the Package Manager (or GUI) install Service Stack into your project. This should add the required code to the web.config, if not you can double check your web config is setup like shown here.

Next in the global.asax we want to create an AppHost and configure it:

public class Global : HttpApplication
{
    public class SampleServiceAppHost : AppHostBase
    {
        private readonly IContainerAdapter _containerAdapter;

        public SampleServiceAppHost(ISessionFactory sessionFactory)
            : base("Service Stack with Fluent NHibernate Sample", typeof(ProductFindService).Assembly)
        {
            base.Container.Register<ISessionFactory>(sessionFactory);
        }

        public override void Configure(Funq.Container container)
        {
            container.Adapter = _containerAdapter;
        }
    }

    void Application_Start(object sender, EventArgs e)
    {
        var factory = new SessionFactoryManager().CreateSessionFactory();

        (new SampleServiceAppHost(factory)).Init();
    }
}

In our service host we take in our NHibernate Session Factory, and we wire it up to Funq (the default IoC container SS uses), this is so when the Service is resolved, it gets the SessionFactory to create a Session.

If you were using RavenDB, this is where you would inject your DocumentStore, and if you were using EntityFramework, you would inject that DataContext thing it uses.

So when the application is started, we create the SessionFactory, and create an instance of the AppHost, passing in the SessionFactory.

Services

Now that SS is setup, we need to implement our services. This part is just as easy.

In some of the SS samples such as this one, dependencies are injected via the properties. Personally I don’t like this, because the service is absolutely dependent on that dependency. It cannot function without it, so in my opinion this dependency should be done via the constructor.

I’m not going to go over EVERY service implementation, I’m only going to show Insert and Select By Id.

Insert

Besides the model defined for NHibernate, we need our Service Request Model, and we need our implementation.

public class ProductInsert
{
    public string Name { get; set; }
    public string Description { get; set; }
}

This is our Service Request Model, really plain and simple DTO used for doing a Product Insert.

public class ProductInsertService : ServiceBase<ProductInsert>
{
    public ISessionFactory NHSessionFactory { get; set; }

    public ProductInsertService(ISessionFactory sessionFactory)
    {
        NHSessionFactory = sessionFactory;
    }

    protected override object Run(ProductInsert request)
    {
        using (var session = NHSessionFactory.OpenSession())
        using (var tx = session.BeginTransaction())
        {
            var result = request.TranslateTo<Product>();

            session.Save(result);

            tx.Commit();
        }

        return null;
    }
}

This is our Service Implementation, as you can see we have a constructor which takes in the ISessionFactory, this is our NHibernate ISessionFactory, you need to be careful here since ServiceStack has it’s own ISessionFactory:

spacer

We need to make sure this is the NHibernate one:

spacer

You can of course, inject your Unit Of Work, or the NHibernate Session, or what ever you like, if you’re using Repositories you may opt to inject an instance of your desired repository such as IProductRepository. For this example I’m using NHibernates SessionFactory so that the service is responsible for opening a Session and Transaction.

So that’s all there is to it, inject your SessionFactory, or your desired persistence implementation, and do your thing.

The cool thing about ServiceStack is it has built in functionality to do mapping.

var result = request.TranslateTo<Product>();

TranslateTo<T> is functionality built into ServiceStack for mapping 1 object to another.

If you want to update an object, ServiceStack handles that too using PopulateWith.

var existing = session.Get<Product>(request.Id)
                      .PopulateWith(request);

No need to introduce anything like AutoMapper.

Select By Id

This service I’ve called ProductFindService, in the future there will be a ProductSearchService to show selection by criteria.

Like the Insert service, I’ve defined a simple model which only has an Id property for selecting the product out:

public class ProductFind
{
    public Guid Id { get; set; }
}

In addition to the Request Model I have a Response Model:

public class ProductFindResponse : IHasResponseStatus
{
    public class Product
    {
        public Guid Id { get; set; }

        public string Name { get; set; }
        public string Description { get; set; }
    }

    public Product Result { get; set; }
    public ResponseStatus ResponseStatus { get; set; }
}

This has a nested Product class which defines all the properties of a Product. The outer Response object has a Result and Status. (status is for Exception/Error information)

As you can see the Response is the same name as the Request, with Response appended to the end, so that SS can create this object itself.

When I setup these Request/Response objects in Visual Studio, I use an extension called NestIn which allows me to select the two classes and nest the Response under the Request like so:

spacer

The service is similar to the insert, we inject the SessionFactory, open a Session, no transaction (unless you want to use 2nd level caching, but that’s beyond this post) and select out the Product:

public class ProductFindService : ServiceBase<ProductFind>
{
    public ISessionFactory NHSessionFactory { get; set; }

    public ProductFindService(ISessionFactory sessionFactory)
    {
        NHSessionFactory = sessionFactory;
    }

    protected override object Run(ProductFind request)
    {
        using (var session = NHSessionFactory.OpenSession())
        {
            var result = session.Load<Models.Product>(request.Id);

            return new ProductFindResponse
            {
                Result = result.TranslateTo<ProductFindResponse.Product>()
            };
        }
    }
}

Lastly we return a new Response object, and translate the result from NHibernate to the Response result.

Easy peasy spacer

Swapping out NHibernate for anything else like RavenDB or MongoDB is super easy. I hope this helps those few people who have asked me how to use other persistence frameworks get up and running.

I find it amazing how little code you’re required to write to get a ServiceStack Service up and running.

Categories: Fluent NHibernate, Service Stack Tags: Fluent NHibernate, NHibernate, Service Stack

CodeSchool.com is the most awesome way to learn

April 11th, 2012 Phillip 2 comments

On the 1st of April, Glenn Block posted a link that was too good to be true.

www.codeschool.com

spacer

I have a habit of checking out most links that don’t look like they link to a porn site or some look at photo of me and signup to see me naked. This particular link interested me because his tweet mentioned Backbone, something I’ve been wanting to learn for a while and that I’m been hoping Derick Bailey would add to his awesome JavaScript video collection: www.watchmecode.net (his JavaScript series is absolutely brilliant and I’ve learnt SO much from him so go support him so he will make more plz kthxbi)

Anyway CodeSchool allows you to do level 1 of most courses for free, and if you like what you try you can purchase the rest of the course. Buying the courses 1 by 1 is a little bit expensive at $55 USD, but it’s well worth the money.

You’re not getting just a video like you would with sites like Plural Sight, Tekpub, or any of the many other site’s popping up lately.

After each lesson in the course, there’s a series of challenge”s which allow you to utilize your new gained knowledge and put it to the test. The Backbone course challenges you to make a small ToDo list application, starting out really basic and slowly modifying the code to follow best practice, or add new features.

spacer

Each challenge builds on top of the previous, it gives you a story with some helpful information on functions to invoke or events to listen to, and you can dive back into the slides to double check things, should you forget.

If you get stuck you can ask for hints.

Each time you use a hint, the number of points you can gain from the challenge drops, yes that’s right, there’s a points counter to entice you to complete the challenges.

spacer     spacer

To top it all off you get this nifty little public profile with badges to show what you’ve completed:

spacer

This site is just amazing, it really taking learning to a whole new level. You’re not stuck with boring old videos that you forget after you’ve finished watching an hour of content, you spend up to 20 minutes learning a bunch of new stuff which you can use right away in their predefined challenges and get feedback right away. It goes a long way to help you understand what you’re doing.

I highly recommend anyone wanting to learn Backbone, grab this course:

www.codeschool.com/courses/anatomy-of-backbonejs

Or checkout some of the other courses available:

www.codeschool.com/courses

Categories: General Tags: learning

My must have (short) list programs/extensions etc

March 24th, 2012 Phillip 4 comments

We have all seen these lists before, but I’ve decided I’ll make a list of all the software I use or think are a must have, blog it, then this time next year I can do the list again and see how much it’s changed.

Visual Studio 2010

What can I say, I’m a .NET Developer spacer

ReSharper

www.jetbrains.com/resharper/

This should just ship with Visual Studio, without ReSharper I feel so unproductive in VS.

MindScape Web Workbench

www.mindscapehq.com/products/web-workbench

This VS extension just gets better and better, I primarily got it to write LESS and CoffeeScript, but recently they added support for minifying and combining JavaScript and CSS files. Really cool stuff and I highly recommend it.

BugAid

www.bugaidsoftware.com/

This is a relatively new extension, it extends the debugging tools in Visual Studio and gives more information where it can. It was a little annoying at first, but they are listening to the community and fixing issues, adding features, it’s coming along nicely and I recommend it!

MightyMoose / NCrunch

www.continuoustests.com/ / www.ncrunch.net/

These two tools are the same taken from two different approaches with two different goals. As a result I’m really torn between them. I love features from both, and I’ve been using MightyMoose at work and NCrunch at home. NCrunch has code-coverage which Greg Young disagrees with. I guess that’s what’s stopping me from adopting LOLCats and Gary, and other cool features in MM.

PostgreSQL

www.postgresql.org/

One thing I don’t like about SQL Server, is having to install it and have it run all the time… But I’ve always loved PostgreSQL as well, and hated MySQL. (checkout Tekpubs “The Perils of MySQL” for a glimpse of why I don’t like it). Why I think this is a must have is I recently found out you don’t actually need to install it to run. This makes it great for a dev environment where you want to run up an instance on demand when you need it.

RavenDB

ravendb.net/

If you’re a .NET developer and not already looking at, or using RavenDB… I don’t know you… RavenDB makes working with a document database, fun, and easy to learn, and constantly blows my mind.

ILSpy

wiki.sharpdevelop.net/ilspy.ashx

Of all the reflection tools available I prefer ILSpy. No real reason it just works and is fast.

Sublime Text

www.sublimetext.com/

I used to be a massive fan of EditPlus, infact I’ve used it for over 10 years… But recently found Sublime text due to Tuts+ 30 Days to learn jQuery, and haven’t gone back to EditPlus. It has awesome plugin features.

NHProf

nhprof.com/

Since I tend to use NHibernate quite a bit, well not so much now that RavenDB is about, but when using NHibernate I use NHProf to view the generated queries. One really, really, really handy tool.


There’s a lot of other little tools I use, like Fiddler, JSONView, etc. But I just wanted to list the things I use all the time.

Categories: General Tags:

OrmLite Blobbing done with NHibernate and Serialized JSON…

March 19th, 2012 Phillip 1 comment

There seems to be a growing trend now with these Micro ORM’s, at least that is what I see with ServiceStack.OrmLite, which is the ability to persist properties of an object as a JSON, rather than in separate tables.

Usually with a Relational approach you would create a ‘Customer’ table, ‘Address’ table, and most likely shove the Phone Numbers under separate columns of the customer for ‘HomePhone’ and ‘Mobile’.

This means we are limited to two types of phone numbers, and require joining or querying for the addresses.

Do we really need separate columns for phone numbers? Do we really need to persist the addresses in another table?

One problem I see with putting addresses into it’s own table, is the temptation to relate them to an Order (assuming this is some sort of eCommerce system) when really there is no relationship between a customer’s address, and the address on an order.

Really, the order should have it’s own address, otherwise you can never delete or update an address on a customer, and you can’t delete the customer. However I digress and this is a topic for another day.

Example by OrmLite

This post is about how to do it with NHibernate, but I’m going to start by showing the example in OrmLite, then use the same example for NHibernate.

Note: OrmLite by default persists as JSV-format (JSON+CSV) rather than JSON. I’m currently unaware of any way to change it to be JSON.

The customer is the root aggregate, and has his own Addresses and Phone Numbers, and is modelled like so:

public enum PhoneType
{
    Home,
    Work,
    Mobile,
}

public enum AddressType
{
    Home,
    Work,
    Other,
}

public class Address
{
    public string Line1 { get; set; }
    public string Line2 { get; set; }
    public string ZipCode { get; set; }
    public string State { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

public class Customer
{
    public Customer()
    {
        this.PhoneNumbers = new Dictionary<PhoneType, string>();
        this.Addresses = new Dictionary<AddressType, Address>();
    }

    [AutoIncrement] // Creates Auto primary key
    public virtual int Id { get; set; }
               
    public virtual string FirstName { get;

gipoco.com is neither affiliated with the authors of this page nor responsible for its contents. This is a safe-cache copy of the original web site.