F# and Nancy – beyond Hello World

I have been trying to find some examples on how to create a web app using F# with Nancy. Most of the tutorials on the web cover simple “Hello World!” app, only the basics. In this post, I want to go beyond “Hello World” and show real life examples.

F# and Nancy – Where to start ?

Most basic app “Hello World”, is simple.

Nancy will automatically load up the App class. To those familiar with Nancy on C# it looks almost the same. The only noticeable difference is the lambda function declaration, plus different syntax for inheritance. Also there is this weird smile face ‘:>’ at the end. This is just a up-casting operator. For some reason Get function has to return object. In F# you also use different syntax for list / array indexing. Instead of Get["/"], you need to use Get.["/"]

GET Examples

POST

To extract the parameters I had to cast the input param, which is of obj type, to Nancy.DynamicDictonary. It doesn’t look great but there is other way.

How to achieve syntax like that – parameters?name ?

This part of code is creating new “let-bound operator”. It hides the casting logic and makes the code look cleaner.

Error Codes

Views

Syntax is simple and looks basically the same as in C#. There is only one little detail. By default Nancy looks for views in /Views folder. Currently in VS F# project there is no way to create folders from within VS. In order to do this I had to manually, create folder, add file and edit *.fsproj file. Hopefully this will be fixed in the future.

More details

ModelBinding

In C# syntax, you would normally use the base method Bind to perform the binding. This method is an extension method and in order to have an access to it, I had to include ModelBinding.

The type to bind

And the code to bind to the model.

Unfortunately, it won’t work like that. My “TestModel” type is missing default parameter-less constructor and Nancy is throwing “No parameter less constructor defined for this object” Exception.

There is a constructor, no Exception, but the value is not bound and is always empty. To fix this, I had to go and look through Nancy code. By default Nancy is binding to property. My val declaration is not a property.

Syntax for properties is a little different, but nothing serious here. I need to make my value mutable so I can modify the state.

The Application OnError pipeline

To modify the Pipeline I had to add include Nancy.Bootstrapper it has IApplicationStartup interface which can be used to hook into OnError pipeline

Nancy will automatically pick-up this class. The syntax for interface implementation is different, a lot. There is no += operator when working with Events and I had to use ADD method. With this example I got an exception “unable to resolve type AppStartup”. It was a problem of missing parameter less constructor.

The End

Those examples are not really showing the power of F#. This power lays in domain-business logic, not in simple endpoint declaration. It is also the OOP approach with F# syntax. There are other web frameworks that have more functional approach. You can check Fancy which is a nice wrapper around Nancy. In a future, I might do a comparison with some purely functional web framework.

dotnetconf.pl 2014

I feel empowered and motivated, dotnetconf.pl and also Software Architects conf gave me a huge energy boost. Thank you everyone for being with us on dotnetconf.pl. For those of you who don’t know, dotnetconf.pl is an online conference, from Polish speakers to Polish developers. You can watch presentations here.

Last Saturday we have organized 2nd edition of this event and it looks like there will be another one. We don’t know when, I know that ideally, you the viewers, would like it to be sooner than later. As of now the plan is to do them yearly, but we might consider a conference on a 6 month basis plus smaller events per 3 months. It all depends on the demand and the audience. Pawel has also an idea to start audio cast, something like hanselminutes, with speakers discussing various topics from our dev world.

While, I was writing this post someone else was also thinking about audio cast idea and … today Maciej Aniserowicz has started his podcast ( Check it out it’s great ). Due to this we might pursue a different idea, maybe something like pair programming on stream, twitch, we might try it on 15th November doing game of life in Haskell / F# for Global Code Retreat. Would there be any interest in something like that ?

The conference chat was full of discussions. That’s great, really great and there is this small idea, proposed by one of the attendees, to start a conference a week before a live event like DevDay. With such a date, all the topics started online, could be followed in real life. Wouldn’t that be great ? The soo called “Hallway Track” doesn’t fit to the online format. However if you have any ideas on how to do something like that, then PM me :)

Unfortunately you weren’t able to watch Basia’s talk, we had issues with google hangout. We have been testing everything twice and it was ok and the suddenly it stopped being ok. Basia’s talk is going to be recorder and sent to all of you, soon be patient :)

Overall conference was great, I hope that you also enjoyed it. Still there are things that we can change / improve.

  • backup speakers, ready to step up if there is a problem
  • backup option for streaming, that might be hard, any suggestions ?
  • missed opportunities to attract bigger audience
  • Q/A system, some semi automated script
  • implement a way to quickly notify everyone that there are issues
  • some script to notify all the channels that new stream is starting
  • because of SignalR and static pages we weren’t able to update the agenda
  • simple voting system on the site

We might do more, we are open for suggestions. Feel free to send us a message with anything. Even comment that my thumbs ups and down on camera are childish, is a helpful one :)

Thank you for all the feedback. You are the best :)
Feel free to comment here and discuss some of the things that i just mentioned.

Game programming with F#, C# and SFML – GameLoop

I am a F# apprentice. The best way to learn new language is to do some project. That’s why I have started to code one game idea that was following me for some time.

Core concept:

  • sci-fi setting
  • roguelike
  • inspired by:
    • dwarf fortress
    • prison architect
    • cataclysm dda

Because I don’t care about the graphics but the game-play, the graphic I am going to use will be an ASCII styles tile set. You know symbols, characters, letters and some simple graphic, just like in old MUD games.

For graphic layer, I am going to use SFML and it’s .NET wrapper. It’s quite good and I know a bit about it. In the past I have been using SDL wrapper which was also fine. At the beginning I am mostly going to focus on 2D tile rendering and some ray casting to calculate field of view. I really like the way it’s done in Cataclysm DDA, so I ll try to emulate it.

Apart from coding the game and its logic, the most difficult part will be to use F#. I am a little worried about its stateless world. I have heard about monads and how you can manage state with them, but still its going to be difficult for apprentice like me.

To start with something, I have decided to do my first simple game loop and render window.

Couple of interesting things in this code.

“:?>” operator

If I have some class that inherits the System.Object ( Default behavior in .NET ).

“:?>” downcast – it will cast Object to Something. This operation is performed on run time.

The “:?>” operator performs a dynamic cast, which means that the success of the cast is determined at run time. A cast that uses the “:?>” operator is not checked at compile time; but at run time, an attempt is made to cast to the specified type.

“:>” upcast – it will cast Something to Object. This operation is performed on compile time.

The “:>” operator performs a static cast, which means that the success of the cast is determined at compile time. If a cast that uses “:>” compiles successfully, it is a valid cast and has no chance of failure at run time.

More about casting in F# world

Pattern matching ( F# switch )

From my understating it’s something like a switch but with more powerful options and possibilities. My example is a simple true, false switch.

() is an empty method just to do nothing and stop recurrence.

|> is a pipe lining operator, concept i know from the unix world, ignore is just information that i want to ignore the value that mainLoop() is returning.

More about pattern matching

Recurrent loop – rec keyword

The Game Loop has to be infinite. In functional approach you don’t use loops, like while(true), instead you have to use recurrence. In C# you can just call function from within the function. In F# you can do the same, however you need to mark function with rec keyword ? Why ? The answer is complex and if you want to know it check this link and this one

Get out of your comfort zone – Vim the social connector

I am a .Net developer, mostly. Sure, I am exploring Python, node.js and other technologies, still my work is mostly related to C# and recently I am having fun with F#. I can say that as of now I am tied to one platform and I mostly attending meetups and conferences slightly related to it.

comfort zone

Recently I have gone to one of the meetups and I had opportunity to chat with awesome PHP programmers. Boy that was fun. MS technology stack for them is considered as an evil one, with evil solutions and evil approach to opensource. Just like my image of PHP is full of ‘script kids’ lack of software engineering etc. Of course that image is far from reality.

I was really surprised how .Net developers are perceived :

  • we don’t know framework details because intelisense is doing everything for us
  • editor is doing everything for us, we are just drag n dropping controlsa
  • MS stack is an evil panda
  • we are using TFS because that’s a technology from MS
  • we are not trying other tools that the MS approved ones

As you can see the gap is huge. Now the problem is how to find a connection with someone from the other platform ? There is always a topic about domain,or other technologically independent stuff like DDD, TDD, BDD. But what about other stuff like tools ? Well we have Visual Studio and I have heard that PHPStorm from JetBrains is quite popular. Ahh there is git, yes git is fun and could be a source of endless discussion. What else … VIM, ha I am using Vim. It is so unusual that a .Net dev is a Vim fanatic that it might be this little cherry on top of the cake. They were really surprised. Even better I used emacs extensively on my university so legendary emacs vs vim discussion started. We shared our thought on vim, emacs tooling, I told them why i prefer Vim than Visual Studio.

What I learned. Hmm, I have to get out of my comfort zone more. One platform approach is a dead end. There are soo many people using different technologies that i might miss them or i wont be able to find a topic to talk to them. I have been also trying to follow rule, “Always say yes!” :) this one is hard to follow.

So whats next ?

  • Swift – I would need a mac … but finally i would have a nice topic to talk with @mihcall
  • Rails and Ruby – this would give me a basis to talk to @andrzejkrzywda and @mpraglowski

A lot of choices, a lot people. In the end no matter what you choose there will always be someone interesting to talk to. So get up and learn some new technology, move out of your comfort zone.
As a follow up to this topic, watch Martin Mazur talk from dev day 2012.

F# where to start

I have started learning F# again, thanks to @isaac_abraham and his great presentation in my company. This time hopefully, I will move past the “WTF”, barrier and move to “AHA” moment. I am ready to finally start serious F# learning with couple of milestones like: project euler, tool, web-app, complex project. I will try to document whole process on the blog.

I want to force myself and learn new functional paradigm. Hopefully it will give me a new way to look at problems and solutions for them. To this day I have spent most of the time in OO world, meh, it gets boring, really. I might also get a chance to do something cool with F# for my company. Me and 3 of my coworkers, we are trying to explore together DDD with F# and find a better way to model our code/

To start somewhere, I was given a link to a great site with a list of advices http://fsharpforfunandprofit.com/learning-fsharp/ Do’s and Don’ts section is very helpful. You can consider this as “House rules” constraining you with a form of “force yourself to think differently”.

Project Eueler 1

As usual, when I don’t know where to start with new language I go to Project Euler site. I am thinking about doing 10 problems just to get a hold on the syntax and features.

If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.

The first problem it’s not that hard. You can do it by a brute force loop. there is also a better solutions that has lower complexity. My solution is just a loop.

I like the syntax, it looks really nice.

1st : I am declaring new function ‘ismultiplier’.
2nd : I am creating a sequence with filter in form of if. From my understating sequence is similar concept to a loop over some elements but its being lazy loaded. The data is created on the fly, while code iterates through it.
3rd : I am using Seq method to sum up the yielded values.

This is a simple algorithm, it won’t be enough to learn F# properly. That’s when some practical project will come in. It’s still planned, I have couple of ideas. It has to be something useful and complex enough project so can I learn how to structure code properly and how to use OOP inside F# world.

Twitter

    @ScottWlaschin – his great presentation convinced me even more that F# is the language I WANT to learn.
    @isaac_abraham – F# MVP, Issac’s presentation create first ripple that forced me to consider F# again.
    @eulerfx

Blogs

Talks

Last Minute

@ScottWlaschin created a nice list of all the talks from NDC Oslo 2014 that are touching the functional programming paradigm. Thanks Scott
NDC Fp Track

Questions

- Have you tried any functional language before ? What do you think about them ?
- I need some advice’s on how to approach this language and paradigm, any tips ?

TDD – commit by commit String Calculator Kata (IV)

Previous part in the series TDD – commit by commit String Calculator Kata (III)

Last time I finished on negative values requirement. This will be the “almost” last part of the series about String Calculator Kata. There was some interest in more practical TDD examples in business context with services, layers, mocks and external dependencies like database. I will start next series to cover scenarios like that. Current kata is quite simple and was just a start.

Step – Ignore numbers greater or equal to 1000

I am expecting 1 here, all the other values are above 1000.

Commit – Test

Based on changes from previous steps, I can just use .Where() clause to filter out the values.

Commit – Implementation

Step – Support for delimiters with any length

Delimiters can be of any length with the following format “//;;;\n”. Based on this input delimiter would be ‘;;;’, of course previous requirements are still supported.

Commit – Test

There are two options. I can either use brute force customised index based parsing, or I can use Regular expression. I know that if you have a problem and solve it with regexp, you suddenly have two problems :) Still I think that regexp should be fine in here.

This regexp matches two groups ‘delimiter’ and ‘value’. I need ‘value’ to extract the string with all the values.

As an examples, given “//;;;\n1;;;2;;;3;;;4″
delimiter – ;;;
value -1;;;2;;;3;;;4

With this solution I will remove substring based extraction which was not that good.

Commit – Implementation

To support delimiter of multiple chars, I changed all of the collections from ‘IEnumerable char’ to ‘IEnumerable string’. You can notice that there is a .Single(), that’s because, based on current format and requirement, I expect only single value and delimiter.

I still don’t like ref keyword in ‘ExtractDelimiters’ method, it’s an anti pattern. The only place I can think positively about ‘ref / out’ usability is ‘.TryParse()’ method. To avoid ‘ref’, ‘ExtractDelimiters’ function must return more than only single string. I can either use Tuple or create new class that would encapsulate both extracted delimiters and value. To make this simple, I decided to use ‘Tuple’.

Commit – Ref to Tuple

I also don’t like this line of code. It just too complicated and unreadable.

Much nicer solution would be to hide this logic and extract the method.

Commit – extract regexp matches method

Step – multiple delimiters

Commit – Test

Previous solution supports only one delimiter, now We can have many delimiters separated by brackets. Current regexp in this scenario treats “[*][%]” as single delimiter. i just need to add method / regexp that will extract delimeters from this string.

This Regexp will take [&][*] string and extract both ‘&’ and ‘*’.

Commit – Implementation

It is easy to make a mistake with regexp, I am not sure if all the extractions work fine, that’s why i want to explore more test cases with mutliple delimiters, and multi char delimiters. To do this I ll just convert previous Test to TestCases with variables.

Commit – Test

Some of the delimiters looks werid, but still all the tests pass, thats a good message.

Edge cases mutliple chars.

Wow with this change ale the tests are red. There has to be some problem with regexp. The extraction of single delimiters does only work for single char delimiters. I had to do little change.

Fix for edge cases

That would be all for now. In the last post of this serie, I will do a little cleanup with some summary of whole series.

I need some advice from you dear reader:
- how do you feel about using regexp, any other cool solution to do all the extractions ?
- do you think that usage of Tuple is ok here, or should I create a new container class in this scenario ?

TDD – commit by commit String Calculator Kata (III)

Previous post in the series – TDD – commit by commit String Calculator Kata (II)

In the previous post I did a cleanup phase and added one feature to the String Calculator. The kata is not finished yet.

Step VIII – Different Delimiters

String Calculator should support different delimiters. Previous solution was just a hard-coded hack, still it was good enough solution. There wasn’t any requirement that would suggest a need for something more sophisticated. Now I need to modify my main function so it accepts input – //;\n where the first line char ‘;’ is delimiter.

The test

Commit – Parametrized Delimeter Test

Just an extension to previous tests and simpliest solution below.

Commit – Parametrized Delimeter Implementation

IndexOf just checks if the input string does contains sign of parametrisied delimiter. If that’s true, code tries to extract delimiter in a very crude way. List of default delimiters is provided in case of missing parametrisied delimiter. This is hard-coded code, not a beautiful solution but I don’t have other requirements. I can assume that I don’t have to support anything else. I am assuming that data will be provided in one particular format, that’s why solution is pretty naive Still it does work and all the existing tests are green, I don’t need anything else.

Step IX – Clean up

So now I have a very naive solution. It’s time for my favorite part ‘The Cleanup’. The main method has some complexity, for the first time. It seems that it has two responsibilities: extracting the delimiters and summing up the values. In order to make this cleaner, I am going to extract those two behaviors into separate methods.

Extract Delimeters

Commit: Extract Delimeters

Extract Sum

Commit: Sum Method

It’s not perfect, but this is just one step. I don’t like ‘ref’ keyword, it’s a huge code-smell. This needs to be changed in the ‘future’. Another problem is that the ‘ExtractDelimeters’ function is returning ‘List’ collection. This is also a code smell, especially when I am only using this list to enumerate through its values. Why then provide type of List, if I am not using its functions like Sort, Add ? There is even a better question, shouldn’t I restrict the user of code and communicate to him that this collection should only be used to enumerate ?. I am going to change it to IEnumerable.

Refactor: List to IEnumerable

So that was the final cleanup, no revolutions here. Still, same creepy code that is haunting my eyes. More changes will come naturally with new requirements.

Step X – Negative Values

Next requirement, all the negative values are not supported and I need to throw exception with all the negative values.

Commit – Test negative values

Another iteration of previous tests. In order to keep the test simple, I am not using the parametrisied delimiters.

Commit – negative values implementation

I had to move ‘int.Parse’ step so i could enumerate through the parsed values instead of raw strings. With this I can just collect all the negative values and throw an exception if there are any. Little note, I am using ‘Any()’ instead of ‘Count() > 0′ with IEnumerables. Count needs to enumerate whole list, any will stop on first matching element. It also looks better.

Question:

- Are you a fan of ‘Count() > 0′ or ‘Any()’ ?

TDD – commit by commit String Calculator Kata (II)

Previous post in the series – TDD commit by commit String Calculator (I).

Last part ended with the basic functionality of string calculator. My “class” can parse numbers and sum them up. I have started with an empty project, slowly adding code with features. This post is the 2nd part of the series.

Step VI – Clean up

Before I can start adding new stuff, I need to make a little re-factorization. There are couple of issues in the code.

 

R#, var and other fun

One of the issue, thanks to Pawel Sawicz for pointing this out, is the type of “object” returned by the main function. There is an “object type” instead of “int”. This problem, probably, was caused by R# auto method extraction (that’s one of the reasons why I have disabled R# for a while just to check how it affects my work. Blog post about my observations coming soon). SAdly, This issue wasn’t caught by the unit tests, I am not asserting the expecting “type” just the “value”. This problem is related to the excessive “var” keyword usage. With explicit “int” instead of “var”, there would be an error on compilation. This error is also an assertion, that’s why I think it is beneficial to use explicit types on the expected “object / value”.

Class name + one file

I also noticed that the main class name is “Class1.cs”. Well, what can I say, not a good file-name, when I started implementing features this wasn’t a problem but now when I do know the name of my main class, I don’t see a reason to leave it like this. It’s time to rename the file to match the “class name”. With this change in mind it would be also great to split up the file into multiple files. One big file with code is a big “NO NO”. I don’t want to see the Custom exception or other not-relevant code, especially when I know that it won’t be modified in the foreseeable future. Little note. I am not introducing a new project for tests ‘Yet’.

Test first – first class citizen

Quality of the tests could also be slightly better. Right now each test contains code to create “new StringCalculator()”. It’s not that problematic but it creates an unwanted noise that distorts the readability of code. Unit test has to be clean, readable and easy to follow. I do believe in an idea of treating unit tests as “First Class Citizens”.

“The bottom line of all this is that we should consider our tests as being first. We already know we should write them first; but we should also clean them first, maintain them first, think of them first, and keep them first. We should give our tests the highest priority.
That is what “Test First” really means. The Tests Come First!”

Robert C Martin – http://blog.8thlight.com/uncle-bob/2013/09/23/Test-first.html

This is quite radical, I don’t agree with everything said here, but there is one thought that I do like. Take care of your tests, maintain them, clean and re-factor them. They are the description and the best documentation you have.

After this “brief” introduction time for some code changes.

Commit – test cleanup
I have changed the “expected” value declaration from var to int and automatically compilation error popped up. Now, I can change the “value type” and check if the error is gone and test are passing. Also, I have changed the name of the Test Class, but I am not splitting files yet. I don’t want to create noise and bloat up the commit diff. I introduced the “SetUp” function that is responsible for creating instance of “StringCalcualtor”.

Commit – split file
Finally the split is finished and I am happy ;)

Step VII – Newline character as deli-meter

New requirement, allow the new lines between number (instead of commas). Treat them as deli-meters. Simple example: for input “1\n2,3\n4″, calculator should return “10″.

Commit – Newline character test

Test is pretty straightforward, nothing to explain here. This now throws my custom exception, the input is not correct due to the “\n” characters.

Commit – Newline character test

Implementation is very simple. Do I need to create fancy code with “sparkles”? Not for this requirement. Split function accepts more separators and it’s just “Good Enough”.

Can I refactor the code and tests ? I don’t think so. Code is still quite straightforward.

In this part I just implemented one new feature.

Summary:
- on expected value use explicit “type” instead of “var”, compilation error is your friend
- refactor your code and tests, “Test First” and treat your “Tests as First class citizens”
- create “Good enough” software, don’t overcomplicate solutions.