Software Twist – Adrian Tosca Blog

Adding Spark View Engine to ASP.NET MVC: A Step by Step Guide

Posted in Software Development by Adrian Tosca on 2009, March 29

The installation of Spark view engine is not difficult but it is better to know where to start. As currently there is no official installation guide, I put up a little list to help get started:

1. Download the spark view engine release zip archive

The release zip contains all the binaries, a Visual Studio integration msi and samples. The samples contain a lot of examples with the ASP.NET MVC framework.

2. Install SparkVsIntegration-1.0.39890.0-release.msi from the root folder of the zip archive.

The installer is a bit weird in the sense that does not say anything and closes after installation. If you do not receive any error is supposed to be correctly installed. To be  sure there are no problem with the installation, have all instances of Visual Studio closed. The VS integration of the engine is not great at the moment, be sure to check intelisense information on the official site. 

3. Copy the following binary files from Spark\Bin in the extracted zip archive  to a folder in your solution (usually ‘Dependencies’):

Spark.dll
Spark.pdb
Spark.Web.Mvc.dll
Spark.Web.Mvc.pdb

4. Add references in your web mvc project to Spark.dll and Spark.Web.Mvc.dll.

At this point the engine is ready to use, and only needs to be configured. For example configuration, the provided samples in the zip archive are very handy.

5. Open Global.asax.cs in the root folder of your application and add the following method:

        public static void RegisterViewEngine(ViewEngineCollection engines) {
            var settings = new SparkSettings();

            // comment this if you want to use Html helpers with the ${} syntax:
            // otherwise you would need to use the <%= %> syntax with anything that outputs html code
            settings.SetAutomaticEncoding(true); 

            settings
                .AddNamespace("System")
                .AddNamespace("System.Collections.Generic")
                .AddNamespace("System.Linq")
                .AddNamespace("System.Web.Mvc")
                .AddNamespace("System.Web.Mvc.Html")
                .AddNamespace("Microsoft.Web.Mvc");
                // Add here more namespaces to your model classes
                // or whatever classes you need to use in the views

            settings
                .AddAssembly("Microsoft.Web.Mvc")
                .AddAssembly("Spark.Web.Mvc")
                .AddAssembly("System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35")
                .AddAssembly("System.Web.Routing, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35");

            engines.Add(new SparkViewFactory(settings));
        }

The method is called on Application_Start to actually register the spark engine with the ASP.NET MVC view engines.

    protected void Application_Start() {
        RegisterViewEngine(ViewEngines.Engines);
        RegisterRoutes(RouteTable.Routes);
    }

and… done

At this point the engine is configured and ready to use. The simplest way to start using it is to rename one of the aspx views into .spark file and start replacing the code with the spark syntax. The beauty is that the two engines can work with no problem side by side so there is no need to replace all the pages at once with the spark syntax!

For example you could rename Home/Index.aspx to Home/Index.spark and replace the content with:

<h2>${Html.Encode(ViewData["Message"])}</h2>
To learn more about ASP.NET MVC visit
<a title="ASP.NET MVC Website" href="http://asp.net/mvc">http://asp.net/mvc</a>.

To enable the master pages you will need to add an Application.spark file in the Views/Shared folder. To use strongly typed views add the following at the beginning of the .spark file:

    <viewdata model="YourModelViewClass"/>

The samples in the spark binaries contain a lot more examples and more advanced stuff so be sure to check it out.

Advertisements

Combining Explicit Mappings and Conventions in Fluent NHibernate

Posted in Software Development by Adrian Tosca on 2009, March 28

Fluent NHibernate has got a lot of hype recently and for good reasons: the XML configuration is not the funniest part of using Hibernate. The big advantage of the framework is the ability to build up the NHibernate configuration in a type safe manner. But on top of that, the library has a number of features that greatly simplifies the initial work of configuration.

Automapping

The auto mapper mechanism can automatically map all the entities in the domain based on a set of conventions. 

ISessionFactory sessionFactory =
    Fluently.Configure()
        .Database(MsSqlConfiguration.MsSql2005.ConnectionString(
            cs => cs.Is("connection string"))
        .Mappings(m => m.AutoMappings.Add(
            AutoPersistenceModel.MapEntitiesFromAssemblyOf<Location>()))
        .BuildSessionFactory();

And that’s all. In this example the database is configured with SqlServer 2005 but it can be anything else of course. You get a set of of mappings based on a set of standard conventions. The auto-mapper has the possibility to override the default conventions. Unfortunately it is not always easy to both have a set of conventions and make adjustments where needed. In theory this sounds great but in practice there are always exceptions and before you know it you find yourself with a lot of weird ‘conventions’ that are made only to resolve a particular problem. Overriding the conventions only when needed also sound great but it can become a nightmare to maintain.

In practice a compromise between manual mappings and limited a set of conventions might be a better approach most of the time.

Mappings and conventions

The compromise is to build the normal mappings but only with the non repetitive code that is better to stay in conventions. You could have:

    public class Location {
        public virtual Guid Id { get; set; }
        public virtual string Name { get; set; }
        public virtual Country Country { get; set; }
    }

    public class LocationMapping : ClassMap<Location> {
        public LocationMapping() {
            Id(e => e.Id);
            Map(e => e.Name).Unique();
            References(e => e.Country).Not.LazyLoad();
        }
    }

And then have a number of conventions that are general for all the entities. For example we could have all id’s generated with the GuidComb generator:

    public class PrimaryKeyGeneratorConvention : IIdConvention {
        public bool Accept(IIdentityPart id) {
            return true;
        }
        public void Apply(IIdentityPart id) {
            id.GeneratedBy.GuidComb();
        }
    }

And all columns that are named ‘Name’ could have a certain storage column length:

    public class PropertyNameLengthConvention : IPropertyConvention {
        public bool Accept(IProperty property) {
            return property.Property.Name == "Name";
        }
        public void Apply(IProperty property) {
            property.WithLengthOf(255);
        }
    }

The following code will generate a configuration that reads the mappings and apply the conventions:

ISessionFactory sessionFactory =
    Fluently.Configure()
        .Database(MsSqlConfiguration.MsSql2005.ConnectionString(
            cs => cs.Is("connection string"))
        .Mappings(m => m.FluentMappings.AddFromAssemblyOf<LocationMapping>()
        .ConventionDiscovery.AddFromAssemblyOf<PrimaryKeyGeneratorConvention>()
        .BuildSessionFactory();

I found that is better to avoid combining the convention in the same class even if they refer to the same piece of configuration. For example would be better to just make another convention PrimaryKeyNamingConvention if the primary key should be named ‘Id’.