Archive

Monthly Archives: February 2017

My understanding is that the “use” statement guarantees that the Dispose method of IDisposable will get invoked before exiting the function.

Disposable Example:

open System

type SomeDisposable() =

    interface IDisposable with
        member this.Dispose() = ()

    member this.Divide() = 
        try 0/0
        with ex -> raise ex

Test:
I have observed that the Dispose method gets triggered after an exception is thrown.

module xxx =

    open NUnit.Framework
    open FsUnit

    [<Test>]
    let ``Some Test``() =
        use something = new SomeDisposable()
        something.Divide() |> ignore

Intro

In this post, I document my understanding of how an F# client can interface with ASP.Net Web API.

Web API (aka: The Server)

The following is my controller:

namespace FnTrade.Server.Controllers
open System
open System.Collections.Generic
open System.Linq
open System.Net.Http
open System.Web.Http
open FnTrade.Server.Models

type TransactionController() =
    inherit ApiController()

    let values = [| { AccountId = "Bizmonger"; Symbol = "TSLA"; Qty = 5  }
                    { AccountId = "Bizmonger"; Symbol = "MSFT"; Qty = 10 }
                    { AccountId = "Scarface" ; Symbol = "ROK" ; Qty = 2  } |]

    member x.Post (shares:Shares) = x.Ok shares

    member x.Get() = values

    member x.Get (id:string) = 
        values |> Array.filter (fun x -> x.AccountId.ToLower() = id.ToLower())

The following is the entity that my controller will work with:

namespace FnTrade.Server.Models

open Newtonsoft.Json

[<CLIMutable>]
type Shares = { 
    AccountId : string
    Symbol    : string
    Qty       : int 
}

C# Style (Old School)

The following would represent the type that I would need to deserialize to:

type Share = { 
    AccountId : string
    Symbol    : string
    Qty       : int 
}

C# is the old school way of accessing data from a REST service.

The following code demonstrates the legacy technique of a Read All:

[<Test>]
let ``WebAPI call for everything`` () =
    
    let client = new HttpClient()
    client.BaseAddress <- Uri("http://localhost:48213/");
    client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue("application/json"));

    let response = client.GetAsync("api/transaction").Result;
    if response.IsSuccessStatusCode
    then let result = response.Content.ReadAsStringAsync().Result
         let share = JsonConvert.DeserializeObject<seq<Share>>(result);
         ()
    else failwith "Something bad happened"

The following code demonstrates the legacy technique for accessing data using an argument:

[<Test>]
let ``WebAPI call with argument`` () =
    
    let client = new HttpClient()
    client.BaseAddress <- Uri("http://localhost:48213/");
    client.DefaultRequestHeaders.Accept.Add(MediaTypeWithQualityHeaderValue("application/json"));

    let response = client.GetAsync("api/transaction/bizmonger").Result; // Appended argument
    if response.IsSuccessStatusCode
    then let result = response.Content.ReadAsStringAsync().Result
         let share = JsonConvert.DeserializeObject<seq<Share>>(result);
         ()
    else failwith "Something bad happened"

Type Provider (New School)

F#’s Type Provider is the “cool way” to interface with ASP.NET Web API.

The following is the “cool way” to perform a Read-All:

[<Test>]
let ``Type Provider call for everything`` () =

    Repository.Load "http://localhost:48213/api/transaction"
    |> Array.toList
    |> List.map(fun x -> { AccountId= x.AccountId
                           Symbol=    x.Symbol
                           Qty=       x.Qty })

    |> should equal [{ AccountId = "Bizmonger"; Symbol = "TSLA"; Qty = 5  }
                     { AccountId = "Bizmonger"; Symbol = "MSFT"; Qty = 10 }
                     { AccountId = "Scarface" ; Symbol = "ROK" ; Qty = 2  }]

The following is the “cool way” to perform a Read when supplying an argument:

[<Test>]
let ``Type Provider call with argument`` () =

    let accountId = "bizmonger"
    Repository.Load (sprintf "%s%s" "http://localhost:48213/api/transaction/" accountId)
    |> Array.toList
    |> List.map(fun x -> { AccountId= x.AccountId
                           Symbol=    x.Symbol
                           Qty=       x.Qty })

    |> should equal <| [{ AccountId = "Bizmonger"; Symbol = "TSLA"; Qty = 5  }
                        { AccountId = "Bizmonger"; Symbol = "MSFT"; Qty = 10 }]

Unfortunately, I did not find a “cool way” to post data to a REST server

[<Test>]
let ``WebAPI post`` () =

    let entity = { AccountId = "Bizmonger"; Symbol = "TSLA"; Qty = 5 }
    let json = JsonConvert.SerializeObject(entity)
    let content = new StringContent(json)
    content.Headers.ContentType <- new MediaTypeHeaderValue("application/json")
    
    let client = new HttpClient()
    client.BaseAddress <- Uri("http://localhost:48213/api/");
    let response = client.PostAsync("Transaction", content).Result;
    
    response.IsSuccessStatusCode |> should equal true

The following example demonstrates how I can empower my client to decide how to handle sad-path scenarios versus the server.

In this example, I rely on Partial Application to inject my handler for a user not being authenticated.

The following code reflects my client passing in a sad-path handler:

(*Client*)
let onFailure  credentials = printf "Authentication failed: %A" credentials

let result = { UserName= UserName "Bizmonger"
               Password= Password "MyPasswordxxx" } 
             |> authenticate onFailure

The authenticate function requires a sad-path handler as an argument and will invoke that handler using Partial Application.

In this example, I pass in the credentials of the attempted login for the handler to operate on:

let authenticate onFailure credentials = 
    getAuthentication { 
        let!   result = if credentials.UserName = UserName "Bizmonger"  &&
                           credentials.Password = Password "MyPassword"
                
                        then Some { FirstName=FirstName "Scott"
                                    LastName= LastName  "Nimrod"
                                    Balance=  Balance    99.99m }
                        else onFailure credentials
                             None 
        return result }
 

Here’s the entire example below:

(*Types*)
type UserName =  UserName  of string
type Password =  Password  of string
type FirstName = FirstName of string
type LastName =  LastName  of string
type Balance =   Balance   of decimal
 
type Credentials = { UserName:UserName;   Password:Password }
type Account =     { FirstName:FirstName; LastName:LastName; Balance:Balance }
 
type GetAuthenticationBuilder() =
    member this.Bind (account, f) = printf "Logged In: %A\n\n" account; f account
    member this.Return x   = x
 
(*Functions*)
let getAuthentication = GetAuthenticationBuilder()

let authenticate onFailure credentials = 
    getAuthentication { 
        let!   result = if credentials.UserName = UserName "Bizmonger"  &&
                           credentials.Password = Password "MyPassword"
               
                        then Some { FirstName=FirstName "Scott"
                                    LastName= LastName  "Nimrod"
                                    Balance=  Balance    99.99m }
                        else onFailure credentials
                             None 
        return result }

(*Client*)
let onFailure  credentials = printf "Authentication failed: %A" credentials

let result = { UserName= UserName "Bizmonger"
               Password= Password "MyPasswordxxx" } 
             |> authenticate onFailure

I am attempting to learn Akka.NET. As I understand, Akka.NET is a framework that’s meant to ease the orchestration of concurrency.

The following is a minimal example of leveraging Akka.NET for passing messages:

module Main

open System
open Akka.FSharp
open Akka.Actor
open Actors

type Command = 
    | Message of string
    | Start | Exit

let reporterActor message =
     match message |> box :?> Command with
     | Start     -> ()
     | Message v -> printf "Reporting: %s" v
     | Exit      -> failwith "Kill this!"

let generatorActor (reporter:IActorRef) (mailbox:Actor<_>) message =

    let handle input = match input with
                       | "exit" -> mailbox.Context.System.Terminate |> ignore
                       | _      -> reporter <! Message input

    handle (Console.ReadLine().ToLower())

[<EntryPoint>]
let main argv = 
    let system =         System.create "system"         (Configuration.load())
    let reporterActor =  spawn system  "reporterActor"  (actorOf(reporterActor))
    let generatorActor = spawn system  "generatorActor" (actorOf2(generatorActor reporterActor))

    generatorActor <! Start
    system.WhenTerminated |> ignore
    0

I have been avoiding the concept of Monads in my journey to learn F#. However, I know that sooner or later, I’m just going to have to man-up. As a result, I have been trying to qualify the need to leverage F#’s Computation Expression.

My current conclusion is that a Computation Expression within F# can enable a developer to implement cross-cutting concerns all within a unit of code that maintains functional plug & play within a functional domain model.

I implemented a sample Computation Expression below that handles security and logging:

(*Types*)
type UserName =  UserName  of string
type Password =  Password  of string
type FirstName = FirstName of string
type LastName =  LastName  of string
type Balance =   Balance   of decimal
 
type Credentials = { UserName:UserName;   Password:Password }
type Account =     { FirstName:FirstName; LastName:LastName; Balance:Balance }
 
type GetAuthenticationBuilder() =
    member this.Bind (credentials, f) = printf "Logged In: %A\n\n" credentials; f credentials
    member this.Return x   = x
 
(*Functions*) 
let getAuthentication = GetAuthenticationBuilder()
let authenticate credentials = 
    getAuthentication { 
        let! result = if credentials.UserName = UserName "Bizmonger"  &&
                         credentials.Password = Password "MyPassword"

                      then Some { FirstName=FirstName "Scott"
                                  LastName= LastName  "Nimrod"
                                  Balance=  Balance    99.99m }
                      else printf "Authentication failed: %A" credentials
                           None 
        return result }

Here’s the client that fails to authenticate:


(*Client*)
let result = { UserName= UserName "Bizmonger"
               Password= Password "LA LA LA Mutha #$%^!" } |> authenticate

Here’s the output below:

> 
Authentication failed: {UserName = UserName "Bizmonger";
 Password = Password "LA LA LA Mutha #$%^!";}Logged In: <null>


val result : Account option = None

> 

What’s interesting about the results above is that it appears that the Bind method of the GetAuthenticationBuilder gets invoked AFTER the primary expression’s execution.

Here’s a client that DOES authenticate:


(*Client*)
let result = { UserName= UserName "Bizmonger"
               Password= Password "MyPassword" } |> authenticate

Here’s the output:

> 
Logged In: Some {FirstName = FirstName "Scott";
      LastName = LastName "Nimrod";
      Balance = Balance 99.99M;}


val result : Account option = Some {FirstName = FirstName "Scott";
                                    LastName = LastName "Nimrod";
                                    Balance = Balance 99.99M;}

> 

I posted this question.

The link above reflects a question that I had regarding how to enforce reliance on a function to create a value for a client.

The solution is to have the client rely on Active Patterns that’s publicly exposed while maintaining the privacy of the Discriminated Union type. This will prevent a client from creating a value of it explicitly.

Here’s the solution:

namespace Mynamespace

[<AutoOpen>]
module File1 =

    type EmailAddress = 
        private
        | Valid   of string 
        | Invalid of string

    let createEmailAddress (address:string) =
        if   address.Length > 0
        then Valid   address 
        else Invalid address

    let (|Valid|Invalid|) = function
        | Valid   input -> Valid   input
        | Invalid input -> Invalid input

module File2 =

    let result = createEmailAddress "XXX" |> function
                 | Valid    email -> true
                 | Invalid  email -> false

Intro



I have been studying Event Sourcing recently and would like to document my understanding. As I understand, Event Sourcing is a technique used as an alternative to a CRUD (i.e. Create, Read, Update, Delete) model. I would like to think of event sourcing as a ledger for recording code execution that ultimately hydrates an aggregate (aka: business entity) into existence. This is an interesting concept because this technique enables a business to observe each event that contributed to the actual state of an aggregate. The events that influence an aggregate’s state is called an Event Stream. An event stream is a set of ordered events that can be “played” to generate an aggregate’s state.

Domain

As I understand, Event Sourcing is an architecture that is reflected within the domain module of an enterprise system. I have attempted to learn Event Sourcing by building a sample banking account program.

The domain is the following:

namespace Domain

module Account =

    (*Types*)    
    type AccountId = AccountId of string
    type FirstName = FirstName of string
    type LastName =  LastName  of string

    type Credentials = { UserId:string; Password:string }

    type Account = {
         AccountId: AccountId
         FirstName: FirstName
         LastName:  LastName
         Balance:   decimal  }

    and Event = 
        | LoggedIn  of Credentials
        | Deposited of balance: decimal
        | Withdrew  of balance: decimal

    (*Functions*)
    let emptyAccount = {
         AccountId= AccountId ""
         FirstName= FirstName ""
         LastName=  LastName  ""
         Balance=   0.00m }

    let getAccount credentials = {
        AccountId= AccountId "myAccountId"
        FirstName= FirstName "Scott"
        LastName= LastName   "Nimrod"
        Balance=  0.00m                    }

    let update = function
        | account , LoggedIn  credentials ->   getAccount credentials
        | account , Deposited balance     -> { account with Balance = account.Balance + balance }
        | account , Withdrew  balance     -> { account with Balance = account.Balance - balance }

    let nextUpdate account event = update (account , event)

Client

I wrote a client to interact with the domain by supplying the domain with a set of events that influences an aggregate’s state.

The client is the following:

    (*Client*)
    let credentials = { UserId="Bizmonger"; Password="MyPassword" }
    let account =       credentials |> getAccount 
    let events =
        [
            LoggedIn  credentials
            Deposited 1000m
            Deposited 5000m
            Withdrew  500m
        ]

    let hydratedAccount = (emptyAccount , events) 
                          ||> List.fold nextUpdate

Replaying events via a fold of the events (i.e. hydratedAccount) is the following:

let hydratedAccount = (emptyAccount , events) 
                      ||> List.fold nextUpdate
> 

val hydratedAccount : Account = {AccountId = AccountId "myAccountId";
                                 FirstName = FirstName "Scott";
                                 LastName = LastName "Nimrod";
                                 Balance = 5500.00M;}

> 

Conclusion

In conclusion, I attempted to document my understanding of Event Sourcing. The code that I provided is an example of how to hydrate an aggregate via an Event Stream. However, this post does not address how events actually get created within the system. I will attempt to address this in my next post.