Showing posts with label F#. Show all posts
Showing posts with label F#. Show all posts

Wednesday, April 23, 2014

Introducing the new Portland F# Meetup Group!

I'm very excited to announce that I, with the help of Mathias Brandewinder, am launching the F# meetup group for Portland. He has agreed to come up and spend some time here with the local .NET community and lead a couple of workshops. The first one will be an F# for C# developers talk through the Portland Area .NET Users Group (PADNUG) and the second will be to kick off our first F# meetup.

You can read more about the F# event here and, please, sign up and help get the word out. I am excited about the potential of getting this group running. I hope to have programmers of all skill level and experience come out.

Our first meetup will be a three hour, hands-on, dojo going over machine learning to recognize hand-written characters. If that sounds at all interesting, even if you're not an F# develop, please come and check it out. Come for the machine learning, stay for the F#! Bring your laptops (or share with a friend) and let's get our fingers dirty on some code.

As I get a feel for how many people will be showing up, we will also be looking for a venue. If you have one and are willing to host us, please let me know! We will need some wifi and a projector and that's about it.

I look forward to seeing you there!

Update!

We now have a venue setup! It is located at the Beaverton Community Center (12350 SW 5th Street, Suite 100) in the Vose room.

Sunday, March 23, 2014

Quick and Dirty Command Handlers, Event Handlers, Wiring it Up

In my last post, I talked about a "quick and dirty" way to create a command bus in F#. In this post, we're going to look at a simple set of command handlers to plug into said bus and some event handlers.

Before I jump right in, let's define what we're looking for. I want to use NEventStore for my event bus (comes with some nice features that make getting up and running much faster). Feel free to plug in whatever event store you might feel like. Creating (an extremely basic) event store isn't too terribly hard, but I am not going to cover it in this post. So, without dragging this out too much more, let's create a function that wraps up the creation of NEventStore.

Serializer

NEventStore needs a serializer. It comes with a few baked in, but I have grown fond of FsPickler. It is really fast and convenient since we're using F#. Here's a quick little helper to create our serializer on demand.

Dispatcher

NEventStore also accepts a dispatcher (the thing that is given the events as they come in). Here is where we're going to accept (for now) our event handlers. If needed, as the documentation suggests, we could fire these events off onto a bus like NServiceBus or Mass Transit. All we're going to do (again, for now) is create a function that will return a dispatcher that passes each event to our event handlers. An event handler is just a function that takes a Guid (the entity's id) and a list (ResizeArray) of events.

Create the Event Store

And, finally, we need to create the event store. There is nothing fancy here, it is pretty much just like the example documentation, just using our serializer and dispatcher. It will also use SQL Server as the backing store along with storing the streams in memory.

So, now that we have an event stream, we can push it into our command handlers and extend our setup function from the last post. We're going to change our command handler function to take in bus. We can simply map the original functions and "apply" the event bus, and then pass the resulting functions into the original "createCommandRouter" function.

A simple little domain

Let's take a look at a silly example of a domain, a counter. The counter can be incremented and decremented and that's about it. Since this is all in F#, we'll use a record to define an entity's state and discriminated union to describe the commands and events. This is a pretty common theme if you go hunting around the internet and it has worked out very well for my projects. Our entities will consist of a state, an apply function, and a handle function. (Lev Gorodinski has a really good write-up on this approach and was the basis for my personal "Ah-ha!" moment.)

Now we just need to wire-up our command handler to use the apply and handle functions. Please keep in mind that this is a "Quick and Dirty" solution to get us going and exploring our domain and wiring things up. You will likely need to a function that the handler can call if it encounters and exception and will probably need to rework the domain to return multiple events from commands and then make the appropriate changes in the command handler to handle that. (Simple, really, but too much noise for this post. I will explore these things in a later post.)

Event handlers are just as simple. They can be used to respond to events from your domain and do things like update projections that feed the application. Our "q 'n d" event handler looks something like this:

The DomainStartup

Putting this together, we now get our new domain startup.

This post is already getting long so I will end it here. Have any feedback or questions, please leave them in the comments or hit me up on Twitter. I'd love to hear how you get started quickly on projects to feel productive without building too much cruft.

Saturday, March 8, 2014

Combining F# and Simple.Web to Break SqlEntityConnection

Before we begin, I want to make it absolutely clear that I believe the problem I ran into this week can be attributed, 100%, to PEBKAC.

So, I am creating a new application that is supposed to "enhance" (replace) an internal application and I want to show off how productive F# has been lately. One of the coolest things I've seen with F# are type providers. To connect to the legacy data in this application, I used the SqlEntityConnection and everything was running along smoothly. (I was basically using the type provider as a read-only view of the legacy data, with a few writes here and there.) I ran into a really weird issue that caused me to lose a little bit of time and just want to document it here so I could maybe save future me (or future you) some headache.

I've pushed up a Git repo with a solution that can be run to demonstrate this issue. So, here we go.

The Symptoms

So, I had about 25 Simple.Web handlers firing on all cylinders and, suddenly, one handler would not work. It continued to return a 500 and I couldn't get a breakpoint to catch. Well, I couldn't even get a breakpoint to set. Every one I'd put in gave me an issue saying that symbols were not loaded for the assembly. No matter how much I did "Rebuild All" it would not change. I finally noticed a weird error that looks like this:

A first chance exception of type 'System.NotSupportedException' occurred in FSharp.Core.dll
System.NotSupportedException: LINQ to Entities does not recognize the method 'BlowingUpSqlEntityConnection.Web.Index CheckThis[Index](BlowingUpSqlEntityConnection.Web.Index)' method, and this method cannot be translated into a store expression.
   at Microsoft.FSharp.Linq.QueryModule.CallGenericStaticMethod@337.Invoke(Tuple`2 tupledArg)
   at Microsoft.FSharp.Linq.QueryModule.clo@1741-1.Microsoft-FSharp-Linq-ForwardDeclarations-IQueryMethods-Execute[a,b](FSharpExpr`1 )
   at BlowingUpSqlEntityConnection.Web.Index.getEntity() in C:\Users\James\documents\visual studio 2013\Projects\BlowingUpSqlEntityConnection.Web\BlowingUpSqlEntityConnection.Web\Home.fs:line 15
   at BlowingUpSqlEntityConnection.Web.Index.Simple-Web-IGet-Get() in C:\Users\James\documents\visual studio 2013\Projects\BlowingUpSqlEntityConnection.Web\BlowingUpSqlEntityConnection.Web\Home.fs:line 29
A first chance exception of type 'System.NullReferenceException' occurred in BlowingUpSqlEntityConnection.Web.dll

It's like Entity Framework is trying to run a stored procedure that matches my handler. Weird. Here's what the handler looks like (taken from the available repo).

With a simple change everything worked just fine. By pulling out the Id and making it an parameter of the getEntity function everything went swimmingly.

And now the application is happy as a clam.

Tuesday, February 25, 2014

Quick and Dirty Command Bus with F#

When developing a new application that could benefit from the Domain Drive Design (DDD), Command Query Responsibility Segregation (CQRS), and Event Sourcing (ES) I like to start out with a "quick and dirty" stack, if you will. It should meet the needs of the application in the beginning with extensibility points baked in so that I can scale out in the areas that make sense. One of the hardest parts about this is worrying about how to serialize commands to command handlers in a way that can be scaled.

One of the interesting pieces of F# (which is not F# specific, of course) is the built-in use of agent-based programming. Using the built-in MailboxProcessor we can easily write a miniature command and event bus. Not having to worry about how to build this specific piece of infrastructure (to start) allows us to focus on building the application and then plug in new pieces as we need. For many applications this approach will probably be "good enough" and might solve our needs.

So, let's take a look at what we want from our buses. Let's ignore, for now, the fact that a command should only every be handled by one command handler. Our application is just starting out, it's small, and we can keep the pieces in our head. We aren't loading up assemblies in some dynamic nature so we can visibly look at a module and see what handlers are registered. (If you can't do this, it might be time to move up a level.) Since we're not going to explicitly determine that a command must only be handled by one handler, we can assume that the two buses (Event and Command, that is) can behave the same way. A "message" comes in and it gets handed off, in a serialized fashion, to the "listeners".

This post will cover the command bus.

Command Router Interface

Let's define a little interface for our command router (the bus).

This simple little thing allows us to create different buses as we need. Of course, to start, we'll just need something to allow us to send commands into the domain. Let's now define the look of our command. We probably want to know who sent in the command, the id of the entity we're targeting, and the command itself.

So here we have a discriminated union that describes who sent the command, a record that describes some "header data" that we might need, and then the "command." The "body" portion of the "Command" record is where we'll tuck away the actual command. (We're using obj instead of a generic to make our life a little easier later. Cheating, yeah.)

Create the darn thing

Let's put our IRouter interface to work. We're only going to have one instance of the bus but we might have multiple buses. We can put together a helper function that takes in our "handlers" and returns us an instance of the bus. A handler is just a function that takes a command and returns unit (void).

Now we can wire it up to our application. Since I am partial to Simple.Web and StructureMap, I'm going to show that here, but it should be fairly obvious how to do this in your preferred framework.

I'm punting for now and putting in some fake "createHandlerN" functions into a list and then passing it into the command router function. In my next post I'll cover what those look like and how to make this play nicely with a simple event bus using NEventStore. Until then, I'm always open for feedback on what I have presented and am interested in how you might have solved this sort of problem yourself! Overall, though, nothing difficult about this and it will help us break apart our applications very nicely.

Sunday, February 23, 2014

Simple.Web F# Project IPathUtility Fix

I just pushed an update the F# Simple.Web Visual Studio extension with a minor (well, pretty major) update. When I removed the Simple.Web.AspNet NuGet package, it also removed a utility that is required by Simple.Web (and is the only real code baked into Simple.Web.AspNet). Since Simple.Web is not reliant upon IIS and is written on top of OWIN, it requires an IPathUtility instance to know where to load the files. The interface is very simple and is found in System.Web.Hosting. I basically lifted the code out of the NuGet package and added it to OwinAppSetup.fs. That way, if you don't want to use IIS, you can easily change the code right there to map virtual paths to the hard disk however you want.

Our OwinAppSetup.fs now contains:

I'm sorry if this caused any headache for anybody!

Friday, January 24, 2014

JSON Web Token (JWT) with Simple.Web - Part 2 (Cleanup)

As I am trying to learn more and more about this F# thing and functional programming, in general, I realized that there was a way to cleanup my code from last post to make it more readable. By taking a hint from Scott Wlaschin's post on Railway Oriented Programming, I realized I could pull a lot of the pattern matching out of my code (where it makes sense) and move it into a bind function. Seeing it in my code reminded me a lot of factoring out common terms in math. In this case, we're factoring out the initial check of Some/None.

(As an aside, Scott's website F# for Fun and Profit is a fountain of knowledge and is worth spending a lot of time studying.)

So, we need a function that will do the Some/None checking for us and, since this is the common name everybody uses, we'll call it bind:

Edit: Thanks to Liam McLennan for pointing out that Option.bind can (should) be used instead of writing our own. (Great to have others reviewing my thoughts and it is much appreciated!)

This function takes a function and an Option<'a> as inputs. If the Option<'a> is Some, we take the value of it and bind it to the function f. If the Option<'a> is None, we just return None and our function f is never called.

I also like the infix operator that Scott uses and decided to use the same one for this version of bind. I'm keeping it all in the same module since it's specific to Option<'a> and fairly trivial to write out where it is needed. I'm sure in a larger project it would make sense to wrap all of these common functions into a helper module, but it is small enough.

Edit: And this is how the infix operator can be written using Option.bind:

So we can compose two functions together and into a third. Our new function takes whatever the input is for f1 and binds the output from f1 to f2, thus returning whatever f2 returns. If f1 returns None, then f2 is never called and None is returned from our new function. As such, that means f2 needs to return Option<'a> to keep the signature legal.

But why?

Why would we introduce this to our code? Like when we factor out terms when solving a math problem, we are (usually) reducing the complexity of the problem. If we take one of our original functions, we see that we have to test Option<'a>.isSome and Option<'a>.isNone. Not only do we have to test this in this function, we have to test it in all of them. When we factor this out, we reduce the complexity of our code and reduce the amount of repetitive tests. So, one of our old function:

becomes

In fact, the more functions we have where we're checking for Some/None, the more valuable our bind function becomes.

Cleaned-up code

So here is the same code as the last post but with the new bind function and operator.

Suggestions?

I am always interested in hearing suggestions on how to make my code even better. Have something I could improve? Let me know!

Minor Update (26 Jan 2014)

I realized, after the fact, that I did not use the Simple.Web extension method to write the header. By forgetting this, the header would never actually get written because a NullReferenceException would be thrown. (The context.Response.Headers is initially null.) So, instead of instantiating the dictionary or anything crazy, we just use the extension method which takes care of everything for us. The good news is, this is actually much cleaner than the previous code.

Friday, January 17, 2014

JSON Web Token (JWT) with Simple.Web

I have been experimenting with Simple.Web and F# and trying to find different ways to exercise aspects of the framework. One of the things that is always annoying to me is writing authentication code. Fortunately, Simple.Web makes a distinction between how we authenticate users and how we track who is authenticated. I am not going to get into the Simple.Web handler that would actually authenticate the user, in this post, but am going to focus on how we can use JSON Web Tokens (JWT) in place of cookies and how we can leverage this within Simple.Web (using F# of course!).

Luckily for us, there are plenty of NuGet packages that implement JWT and so we can start there. I used the JWT package written by John Sheehan. It is open source and simple to use. I do have one nitpick about the package that I'll get to. (Read: I am too lazy at the moment to write my own solution since it's not really that hard.) So, we just need to "Install-Package JWT" to add it to our project.

JWT exposes some static methods wherein we pass our package we want serialized along with a "secret key" and we will receive a token we can pass back to the client. When the call comes back in, we pull the token out of the request headers and then can deserialize it. This is the annoyance with this package. We have two options to deserialize: JWT.JsonWebToken.Decode which returns a JSON string, or JWT.JsonWebToken.DecodeToObject which returns an object. My annoyance is that we get an object in the signature, but looking at the source code, the token we pass in is deserialized as a Dictionary. So, you have to cast to Dictionary to pull the values out. I would rather have this be a generic where I can specify what I want this to be deserialized into, or just make the signature Dictionary. As such, since I also use JSON.NET as my JSON serializer, I opted to have JWT return the JSON string and then delegated the object creation to JSON.NET. JSON.NET can also create our object without a public, default constructor which makes it nice to use with records. Enough of that, though.

Where's the code?

Moving onto the Simple.Web side of the house, we need to provide a Simple.Web.Authentication.IAuthenticationProvider which can be done in any IStartupTask. IAuthenticationProvider only has two methods on it, GetLoggedInUser and SetLoggedInUser. (This is how Simple.Web separates the idea of authenticating versus tracking the authentication.) GetLoggedInUser is given a Simple.Web.Http.IContext which contains references to the request and response objects. SetLoggedInUser also receives the context but also receives the IUser given from your authentication handler.

Since we need something to describe the types of things we're putting into our token, let's create a record to describe it.

So now we can track the user's id, name, and the expiration date of the token. We're using int64 here because it is easier to use DateTime.UtcNow.ToBinary() than it is to serialize the date. (At least this is the case with JWT which relies on JavaScriptSerializer.) I like the decomposition we can achieve with F#, so let's move now to write a little helper function that grabs the "Authorization" header from the request. We'll use Option to signal whether we find something or not.

Next, we need something that will pull the token out of the Authorization header, if it exists:

And then we need to turn that token into the Payload record we created above:

And, finally, let's take that Payload, if it exists, and turn it into an IUser if isn't expired.

Putting it all together

So now we can compose these functions and create our IAuthenticationProvider. One of my favorite things about F# is the ability to instantiate an interface without having to create a class. For such a simple interface, that works well here.

So this function takes in a "secret key" and returns a new IAuthenticationProvider. While I didn't cover it explicitly, the SetLoggedInUser should be simple enough to understand. All we need to do is tell Simple.Web to use it when a request needs to be authenticated. As I mentioned before, this can easily be done from an IStartupTask:

Authentication Module in Entirety

Edit: I have cleaned-up the code a little bit. The changes can be found here.

Conclusion

In under 60 lines of code we can put together a rudimentary JWT solution for our Simple.Web applications. When I get a moment, I will toss this up on GitHub so if you might have some improvements you can share them.

Saturday, January 11, 2014

Simple.Web F# Project Template Updates

F# Runtime Update

Thanks, again, to Dan Mohl for sharing some changes made to the ASP.NET MVC/WebAPI templates that I was able to apply to the Simple.Web F# project template. I had been digging into the template to figure out how to get allow changing the target F# runtime when you use the template to create a project but was unsuccessful. Fortunately, part of what Dan shared was a way to fix this-which I don't think I would have been able to figure out on my own. So, that's the first change made to the template.

Changes for Simple.Web Handlers

When I first started working with Simple.Web and tried using it with F# I ran into issues that made me have to build my handlers like so:

[<UriTemplate("/")>]
type Index() as this =
    member __.Get() = Status 200

    interface IGet with
        member __.Get() = this.Get()

I wasn't too happy about having to have so much duplication and double dispatch back to a handler's own methods, but most everything else worked out nicely that I just kind of accepted it, got used to it, and moved on. Once I had my first pull request into the main repository, Ryan Riley had commented on the pull request and asked why I was doing this. I'm glad he asked because I didn't even think about it. Luckily, I ran a little test and was able to pull out the extra method call!

[<UriTemplate("/")>]
type Index() = // No more aliasing required
    interface IGet with
        member __.Get() = Status 200

That cuts the lines of code, and complexity, in half, which is a huge win for F#. Again, it is nice to have another set of eyes out there actively looking at my work to help make it better.

Changes for Simple.Web NuGet Packages

One of the things I wanted to fix in this template was the fact that a C# file was automatically inserted into the project. This was due to the fact that I took a dependency on the Simple.Web.AspNet package. Fortunately, all this package does is reference Fix and Fix.AspNet. Since I have those packages available, I was able to safely remove the Simple.Web.AspNet package and just reference the other two directly. No more C# file to delete!

Update: Just to be a bit more clear about the Simple.Web.AspNet C# file, it was the OwinSetup file that usually goes with the C# project. The F# version has been with the F# Simple.Web template from the start.

Thanks so much to everybody who has downloaded, used, and provided feedback on this template.

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.

Friday, December 27, 2013

Simple.Web F# Project Template - Part 2

Much thanks to Daniel Mohl for his help in creating this project template. After some cleanup, the issues I ran into were cleared up and I was able to produce a functioning template.

After receiving Daniel's feedback (all in my Twitter feed), this was pretty easy:

  • Install Template Builder 1.0.3.22-beta or higher;
  • Change the Is-TemplateSubFolder value to "Simple.Web";
  • Make the Repository Id in the VSTemplate file match the Product Id in the manifest file;
  • Remove references to Packages.config from the fsproj and vstemplate files;
  • Make all nupkg files have a build action of "Content", and set "Include in VSIX" to true;
  • Set "ReplaceParameters" to "true" in the VSTemplate file for AssemblyInfo.fs.

So, here it is, my first Visual Studio extension, and project template: Simple.Web F#. Please let me know what you think or if you have any issues.

Tuesday, December 24, 2013

Simple.Web F# Project Template - Part 1

After working with the new ASP.NET F# community template with Simple.Web and some chatter on Twitter, I decided to put attempt to put together a Simple.Web F# project template. I wanted to write out the steps I took to get started to see if anybody can point out what I might be doing wrong or how I could probably do it better.

Since the community templates are based on SideWaffle, I started with a video made by Sayed Hashimi on how to create a SideWaffle project:

Based on the video, I created a new project based on the F# Web API project, removed almost all the NuGet packages, and added all of the Simple.Web packages needed for a new site. Next, I forked the GitHub repository, cloned it, and copied the Mvc5 folder into a new Simple.Web folder. I had to delete most of the stuff in the new solution that I copied over and added the extracted template items. (See the video.)

Finally, I cleaned up the project to ensure the right license was included, etc., and wound up at this state. (Update: and like an idiot, I deleted the branch in that link. The changes can still be seen, though, in the repo.) Unfortunately, after building the new solution and installing the VSIX (again, see the video), I can't see the new template in the File->New Project dialog box.

Any ideas? (Pull requests are welcomed!)

Update

With the help of Daniel Mohl, I was able to get this taken care of. Here's part 2.

Friday, December 20, 2013

Pure F# ASP.NET Web Applications and Simple.Web

So, there has been some awesome work done by Daniel Mohl on a pure F# project for ASP.NET. Unfortunately, I have been spoiled by Simple.Web and wondered if I could make the project work with it. It was not as hard as I thought it would be, at all. Fortunately, Mark Rendle and company have given us the Simple.Web.AspNet NuGet package which makes this trivial.

The biggest hurdle of it all is the NuGet package adds a C# file called OwinAppSetup.cs which sets up the OWIN bindings, on top of which Simple.Web runs. It is a really simple file, actually:

using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Simple.Web;

namespace FsWebApp
{
    using UseAction = Action<Func<IDictionary<string, object>, Func<IDictionary<string, object>, Task>, Task>>;

    public class OwinAppSetup
    {
        public static void Setup(UseAction use)
        {
            use(Application.Run);
        }
    }
}

Converting this to F# was fairly straight forward and is easily replaced with:

module OwinAppSetup

open System
open System.Collections.Generic
open System.Threading.Tasks
open Simple.Web

type UseAction = Action<Func<IDictionary<string, obj>, Func<IDictionary<string, obj>, Task>, Task>>

type OwinAppSetup() =
    static member Setup(useMethod:UseAction) =
        let run x y = Application.Run(x, y)
        run |> useMethod.Invoke

It is pretty much like the original version except that F#'s type system doesn't let us pass the run method into the UseMethod directly and call it like a method. Instead you have to manually call the Invoke method. (Easy stuff.) Other than deleting a few of the folders from the project template like the Models folder, everything runs perfectly. I also removed a few of the MVC/Web API specific assemblies from the project but that was all that was needed to get going.

Update

There is now some semblance of a Simple.Web F# project template available.

Sunday, March 24, 2013

Simple.Web and F#

I have become increasingly more interested in F# and hope, someday, to transition over from C# to F# in my day-to-day work. (More on that later.)

I have also become increasingly more interested in Simple.Web by Mark Rendle and hope, someday, to transition over from ASP.NET MVC to Simple.Web in my day-to-day work. (More on that later, as well.)

Given both my fondness of F# and Simple.Web, I decided to try to marry the two. I created the normal ASP.NET Empty Project and added the Simple.Web.Aspnet NuGet package along with the Simple.Web.Razor NuGet package. Then I created a handlers project (F# Class Library), referenced it from the first project, and added the same NuGet package. I created a simple handler for the site's index in the first project.

namespace SimpleTest.Web

open Simple.Web

[<UriTemplate("/")>]
type Class1() =
    interface IGet with
        member this.Get() = Status.OK

I also added a Razor page to handle my get request and then hit F5 to fire it up. Since it was so simple, I was expecting to see my fake homepage and see my little test succeed. Wrong.

Instead, I am greeted with a yellow screen of death telling me "Object reference not set to an instance of an object." Hmmm...

I created the same class in C# and everything worked fine. I was beginning to wonder if this was going to work out at all. Well, after some fiddling, I got it to work. Why it works, I am not really sure about. (I'm far from completely comfortable in F#, let alone an expert.) All I had to do was add a member function that mirrored my interface version of Get().

namespace SimpleTest.Web

open Simple.Web

[<UriTemplate("/")>]
type Class1() =
    member this.Get() = Status.OK

    interface IGet with
        member this.Get() = Status.OK

Of course that means I can just return the result of the member function from the interface implementation. But, that got me to thinking. I decided, in the interface implementation, to throw a NotImplementedException:

namespace SimpleTest.Web

open System
open Simple.Web

[<UriTemplate("/")>]
type Class1() =
    member this.Get() = Status.OK

    interface IGet with
        member this.Get() = raise(new NotImplementedException())

To my amusement, it still loaded my page. I understand that to access an interface-defined method in F# you have to explicitly cast the instance to the interface you're targeting. I just did not know that applied across the language boundaries as well when doing whatever magic Simple.Web is doing to find the applicable method.

Time to hunt that down next.

Thursday, March 21, 2013

Testing an ASP.NET MVC Controller

I am a fan of testing my code and have been using SpecsFor, written by Matt Honeycutt, for a lot of my BDD-style unit testing lately. It makes testing very clear and easy to read, comes baked-in with Moq, StructureMap, and a whole lot more goodness.

One of the pain-points of testing ASP.NET MVC is dealing with the controller context, request, response, server, etc. So, I have extended SpecsFor a little bit for my controllers (in both F# and C#).

C#

namespace SpecsForExtensions
{
    using System;
    using System.Security.Principal;
    using System.Web;
    using System.Web.Mvc;
    using System.Web.Routing;

    public class ControllerSpecsFor<T> : DbSpecsFor<T>
        where T : Controller
    {
        protected override void InitializeClassUnderTest ()
        {
            base.InitializeClassUnderTest ();

            var context = GetMockFor<HttpContextBase> ();
            var session = GetMockFor<HttpSessionStateBase> ();
            var request = GetMockFor<HttpRequestBase> ();
            var response = GetMockFor<HttpResponseBase> ();
            var server = GetMockFor<HttpServerUtilityBase> ();
            var user = GetMockFor<IPrincipal> ();
            var identity = GetMockFor<IIdentity> ();
            var uri = new Uri ("http://localhost:12345");
            var requestContext = new RequestContext (context.Object, new RouteData ());

            context.Setup (x => x.Session).Returns (session.Object);
            context.Setup (x => x.Server).Returns (server.Object);
            context.Setup (x => x.Request).Returns (request.Object);
            context.Setup (x => x.Response).Returns (response.Object);
            context.Setup (x => x.User).Returns (user.Object);
            request.Setup (x => x.Url).Returns (uri);
            user.Setup (x => x.Identity).Returns (identity.Object);

            SUT.ControllerContext = new ControllerContext (context.Object, new RouteData (), SUT);
            SUT.Url = new UrlHelper (requestContext);
        }
    }
}

F#

namespace SpecsForExtensions

open System
open System.Security.Principal
open System.Web
open System.Web.Mvc
open System.Web.Routing
open SpecsFor

type ControllerSpecsFor<'a when 'a : not struct and 'a :> Controller>() =
    inherit SpecsFor<'a>()

    override this.InitializeClassUnderTest() =
        base.InitializeClassUnderTest()

        let context = this.GetMockFor<HttpContextBase>()
        let session = this.GetMockFor<HttpSessionStateBase>()
        let request = this.GetMockFor<HttpRequestBase>()
        let response = this.GetMockFor<HttpResponseBase>()
        let server = this.GetMockFor<HttpServerUtilityBase>()
        let user = this.GetMockFor<IPrincipal>()
        let identity = this.GetMockFor<IIdentity>()
        let uri = new Uri("http://localhost:1234")
        let requestContext = new RequestContext(context.Object, new RouteData())

        context.Setup<_>(fun x -> x.Session).Returns(session.Object) |> ignore
        context.Setup<_>(fun x -> x.Server).Returns(server.Object) |> ignore
        context.Setup<_>(fun x -> x.Request).Returns(request.Object) |> ignore
        context.Setup<_>(fun x -> x.Response).Returns(response.Object) |> ignore
        context.Setup<_>(fun x -> x.User).Returns(user.Object) |> ignore
        request.Setup<_>(fun x -> x.Url).Returns(uri) |> ignore
        user.Setup<_>(fun x -> x.Identity).Returns(identity.Object) |> ignore

        this.SUT.ControllerContext <- new ControllerContext (context.Object, new RouteData(), this.SUT)
        this.SUT.Url <- new UrlHelper(requestContext)