Monday, December 30, 2013

Simple.Web F# Helpers

If you're using the new Simple.Web F# project template and haven't used Simple.Web, here are some little helpers to get going.

Static Content

Using the current NuGet package for Simple.Web, one has to setup static content like so (comes with the template at the moment):

open Simple.Web

type StaticContentStartupTask() =
    interface IStartupTask with
        member __.Run(config, env) =
            let pf f = config.PublicFolders.Add(PublicFolder f) |> ignore
            ["/Scripts"; "/Content"; "/App"] |> List.iter pf

Unfortunately, the template currently leaves out one line of code to make this useful. Currently (I'm sorry I didn't add this, please forgive me!), you must add a line to the OwinStartupApp class.

type OwinAppSetup() =
    static member Setup(useMethod:UseAction) =
        let run x y = Application.Run(x, y)
        Application.LegacyStaticContentSupport <- true  // This is the line missing
        run |> useMethod.Invoke

Need to add the "Application.LegacyStaticContentSupport" line to tell Simple.Web (well, Fix, really) to use the static content. There will be an OWIN-specific way of doing this in a later release.

Public File Mappings

One of the cool things about Simple.Web is we can map a URI to a static HTML file very easily.

open System.Collections.Generic

type PublicFileMappingStartup() =
    interface IStartupTask with
        member __.Run(config, env) =
            let pf (ep, f) = config.PublicFileMappings.Add(KeyValuePair(ep, PublicFile f))
            [("/", "/Views/index.html");
             ("/account/login", "/Views/Account/login.html");
             ("/account/create", "/Views/Account/create.html")] |> List.iter pf

Overall I really like the F# syntax for setting these sorts of things up over C#. I think it maps cleanly and, at least to me, seems a lot lighter. The only portion that I can't seem to make more F#-ish is the StructureMap setup. If anybody has some tips, I'd love to hear them! I'd love something like:

open Simple.Web.StructureMap
type StructureMapStartup() =
    inherit StructureMapStartupBase()
    override __.Configure(config) =
        let register<'a, 'b>() = config.For<'a>().Use<'b>() |> ignore
        register()

Much Thanks

Much thanks must be given to Mark Rendle and his awesome design of Simple.Web. It has made web programming fun, again.

No comments:

Post a Comment