Rash thoughts about .NET, C#, F# and Dynamics NAV.


"Every solution will only lead to new problems."

Tuesday, 11. December 2012


Testing, proving, checking – How to verify code properties

Filed under: F#,Informatik — Steffen Forkmann at 13:12 Uhr

As programmers we often want to express that a special property holds for a method, e.g. we want to say that the associativity law holds for list concatenation. In F# we could define a concat method like this:

As programmers we could write a couple of unit tests which try to check the associativity law. With NUnit enabled we could write this:

But the question is: did we cover all interesting cases? In computer science we have a method to prove that the property holds for all lists. This methods is called structural induction (see also this video lecture by Martin Odersky) and would look like this:

1) Rewrite the code as equations
concat ([],ys)    = ys                  [CON1]
concat (x::xs,ys) = x :: concat(xs,ys)  [CON2]
2) Rewrite the property as an equation
concat(concat(xs,ys),zs) = concat(xs,concat(ys,zs))
3) Check the base case
concat(concat([],ys),zs) 
= concat ([],zs) // using CON1 = [] // using CON1
concat([],concat(ys,zs))

= concat (ys,zs) // using CON1
= [] // using CON1
3) Show the inductive step
concat(concat(x::xs,ys),zs) 

= concat (x::concat(xs,ys),zs)) // using CON2
= x :: concat(concat(xs,ys),zs) // using CON2
= x :: concat(xs,concat(ys,zs)) // induction hypothesis
= concat(x::xs,concat(ys,zs)) // using CON2

This math is very clean and shows that the associativity law holds for all lists. Unfortunately even with a slightly more complicated sample this gets at least tricky. Try to prove that reverse(reverse(xs)) = xs with reversed defined as:

As you will see the naïve approach with structural induction will fail (for a nice solution see this video lecture).

There is even a bigger problem with the proof: one assumption of induction is referential transparency of the given functions. We can’t always assume this.

So we can’t always (easily) proof code properties and we don’t want to write too many unit tests – then what can we do?

One compromise solution is to use a tool which systematically generates instances for our tests. There are a couple of tools out there, e.g. there is QuickCheck for Haskell or PEX for .NET. In F# we can use a tool called FsCheck:

Of course a test like this doesn’t prove that the property holds for all lists, but at least it verifies all bases cases and probably a lot more cases than one would manually do.

If you introduce a bug you get a nice report, which even shows a counterexample:

fscheck

It’s even possible to add these tests to your test suite and to run them during the CI build. So don’t stop at classical unit test – check code properties!

Tags:

Using Footloose from F# – part I – Setting up the infrastructure

Filed under: F# — Steffen Forkmann at 9:09 Uhr

“Footloose is a fast and scalable asynchronous distributed computing and service library that was designed to be secure, simple to use, unobtrusive and without the need of client side code generation or proxy classes.

It was developed to connect or build distributed applications on the .NET/Mono platform with enterprise features like load-balancing, clustering, encryption, service discovery and single-sign on.

Footloose enables you to easily transmit any kind of data between the components of your application over thread-, process- or physical boundaries. Depending on your needs Footloose uses one if its transport channels, e.g. a Named Pipe or a Unix Socket for Inter Process Communication (IPC), AMQP with one of the available Message Broker implementations (like RabbitMQ) in the local network or even XMPP as a secure and fast realtime messaging protocol that enables you to build cloud services.”

http://www.footloose-project.de

If you don’t like WCF then you should really check out Footloose.
Footloose_IconToday I want to show you how to use Footloose in a very simple sample with F#.

As a first step we create a F# project for the service contracts. Inside this project we need a service definition like this:

This is just a definition of the remote service and the data. Now we create a F# console project for such a service and reference the service contracts project. We start by implementing the service like this:

Now we use nuget to retrieve the latest version of Footloose. At the time of writing we need to install the pre-release of version 3.0 by "install-package Footloose -pre". In the Program.fs we add the service configuration. Here Footloose wants us to specify the endpoint name, transport channel and a serializer. In order to get Footloose working we also have to retrieve a trial license from the website.

Footloose wants us to provide a ServiceLocator in order to resolve the service. Normally you would use a DI container for this, but here it’s sufficient to fake a IServiceLocator like this:

In the next step we create another F# console project for the client, reference the service contracts and install Footloose ("install-package Footloose -pre"). We also need to install FSharpx ("install-package FSharpx.Core") in order to use the "Quotation to Linq Expression" stuff and the new task monad. Now we are ready to build the client:

As you can see we set up the connection and wrap our service call inside a task monad. The most interesting part is calling the service. Footloose wants to us to provide a LINQ expression:

In order to make the client code compile we also need an active pattern which transforms the service result into something we can pattern match:

As the last step we configure the solution to start both projects and run the sample:

startup

The result should look like this:

result

The sample code is now part of the FootlooseExamples project on github.

Tags: ,

Friday, 28. September 2012


NavTechDays 2012 Notizen Teil 2

Filed under: Dynamics NAV 2009,Navision,Veranstaltungen — Steffen Forkmann at 13:21 Uhr

Gestern habe ich schon den ersten Teil meiner Notizen hier auf dem Blog veröffentlicht. Jetzt geht es weiter mit Teil 2.

Scrum

Microsoft hat den internen Prozess auf Scrum umgestellt und ich finde das merkt man wirklich. Es sind zwar nur zwei Tage Konferenz, aber das Produkt fühlt sich tatsächlich “fertig” an. Es ist interessant zu sehen wie eine so konservative Organisation wie NAV auf einen agilen Prozess umstellt. Ich bin gespannt was mit diesen ganzen Wasserfall-Tools wie SureStep und Co. passiert. Hier auf dieser Developer-Konferenz hat jedenfalls keiner davon geredet.

  • 20 Scrum Teams mit zweiwöchigen Sprints
  • Verwaltung der User Stories im TFS (Source Control irgendwo anders)
  • ATDD wird eingesetzt aber kein TDD
  • Umstellung auf Kanban steht jetzt bevor

OData

  • OData Webservices aus NAV + Excel PowerPivot ist eine geniale Kombination für Auswertungen (Low Cost BI) – MSDN Walkthrough
  • OData ist im Moment nur read-only

Dimensionen

  • Völlig überarbeitet.
  • Viel weniger Kopien der Dimensionen – nur noch über einen Schlüssel referenziert

Datenzugriff

  • Neuer Data Access Stack angeblich schneller als Classic Client.
  • FIND und FINDSET sind gleich schnell
  • SETCURRENTKEY macht Abfragen jetzt nur noch langsamer (da Sortierung) keinesfalls schneller
  • SQL Call Stack Traces – Blog post
  • Es sind keine Writes in die Object und Company Tabellen mehr möglich
  • Security Filters überarbeitet. Erlaubt es Nutzern nur gefilterte Datensätze zu zeigen.
    • Neue Optionen um Probleme mit indirekten Rechten zu lösen
    • Security Filter Feature kann im C/AL direkt an Record-Variablen konfiguriert werden
    • Security-Einstellungen zeigen sofort Wirkung. Keine manuelle Synchronisation der Nutzer oder Neustarts nötig
    • Standard App wurde noch nicht nach möglichen Security Filter Problemen durchforstet
    • Validated Mode sollte möglichst nicht benutzt werden, da es langsamer als die anderen Optionen ist

Locks und Blocks

  • Alle Slides und Samples sind auf Stryks Blog downloadbar
  • SQL Server Lock Escalation sollte vermieden werden -> „always rowlock” benutzen (jedoch nicht auf 32bit und unter 8GB RAM)
  • LOCKTABLE erhöht das Transaction Isolation Level auf Serializable
    • Über einen DB switch kann auf Repeatable Read umgestellt werden (Unterschied wie Tag und Nacht)
    • Das ist sowieso der Standard bei NAV2013
    • Es können zwar Phantom Reads entstehen, aber das sind Probleme die in der Praxis nicht existieren (“habe ich noch nie gesehen”)
  • Block und Dead Lock Detection Tool auf seinem Blog
  • Job Queue von NAV2013 kann auch in älteren Versionen nachgebaut werden
  • Beispiel 1: In Document Dimensions den Clustered SQL Index fixen – Document No.,  Document Type nach vorne -> weniger Blocks da die gelockten Zeilen näher beisammen sind
  • Beispiel 2: In Codeunit 80 und 90 gibt es ein globales Lock auf die „GL Entry“. Das wird auch ausgeführt wenn gar keine Sachbuchungen passieren. Lock mit PostToGL Flag fixen (bereits in NAV2013 gefixt)
  • Beispiel 3: In Tabelle 36 gibt es einen „Warehouse bug“ – Selbst wenn die Warehouse Tabelle leer ist wird die Tabelle gelockt. Generell sollte immer über ISEMPTY geprüft werden ob überhaupt Datensätze im Filter sind bevor man ein DELETEALL oder MODIFYALL durchführt
  • Beispiel 4: Reservation Entry.Lock() hat ein ähnliches Problem. Einfach am Anfang der Funktion prüfen ob die Tabelle leer ist. Wenn ja dann mit EXIT aus der Funktion springen
  • Beispiel 5: No. Series Line Tabelle ist „zu klein“ für das Lock und es werden mehr als eine Zeile gelockt. Folge: Wenn jemand eine Rechnung erzeugt kann ein anderer u.U. keine Artikel erzeugen. Lässt sich leicht mit Dummy Feldern fixen. 😉

Reporting

  • Es gibt nur noch RDCL Reports
  • Classic Sections (und deren Trigger) fallen weg
  • Es gibt einen „Dataset designer“ als Ersatz für die Sections (analog Query designer)
  • Es wird nun RDLC 2008, Report Viewer 2010 und Visual Studio 2010 benutzt.
  • Reports erlauben „Save as Word“
  • “Heavy reports” über Background Session auf dem Server drucken (“Server side printing”)
  • Im Webclient gibt es “Preview” (nur IE) und „Save as PDF“ (alle Browser)
  • „Tray selection“ fixed – zusätzlich ein Codeunit 1 Trigger der es erlaubt die Papierfachsteuerung zu überschreiben
  • Upgrade Prozess
    • Hotfixes in NAV 5 und 6 erlauben Trigger in Codeunit 1 „OnBeforeRunReport“ (erlaubt zu zählen wie oft der Report tatsächlich genutzt wird)
    • Automatische Transformation hilft bei Upgrade von existieren NAV 2009 RDLC Reports (Tools/Upgrade Report)
    • Upgrade braucht ein technisches Upgrade auf NAV2013 als Zwischenschritt, da der Report kompilierbar sein muss um das Transformations-Tool zu benutzen
    • Automatisch vergebene Namen im Anschluss aufräumen
    • Doppelte Spalten entfernen
    • UI Guidelines auf MSDN befolgen
    • CreateTotals entfernen

Insgesamt war es ein sehr gute Veranstaltung mit vielen Informationen zu Dynamics NAV 2013. Vielen Dank an die Organisatoren und die Speaker.

Thursday, 27. September 2012


Notizen von den NavTechDays 2012 Teil 1

Filed under: Dynamics NAV 2009,Navision,Veranstaltungen — Steffen Forkmann at 14:04 Uhr

Microsoft Dynamics NAV 2013 wurde vorgestern released und so trifft es sich das gerade jetzt die NavTechDays 2012 in Antwerpen stattfinden. Hier meine Notizen nach fast einem Tag Konferenz.

Allgemeines

  • Das NAV Menü ist bekanntermaßen sehr umfangreich -> NAV2013 hat jetzt eine Suche dafür
  • Der Classic Client heißt jetzt Development Environment und ist kein echter Client mehr. Da es keine Forms mehr gibt wird auch gern als „Retired Client“ bezeichnet.
  • Die Administration der Service Tiere kann nun vollständig über Powershell gescriptet werden. Das geht auch von remote.
  • Der Page Designer wurde deutlich verbessert und erlaubt nun eine „Live Preview“. Damit kann man die Änderungen direkt betrachten – ohne zu kompilieren und NAV neu zu starten.
    • Gruppen können eingeklappt werden
  • NAV2013 unterstützt OData
    • Erlaubt Query Objekte nach außen über Webservices zu veröffentlichen.
    • Gut für Anbindung von externen (Reporting) Tools
  • Der Windows client (ehemals RTC) wurde verbessert
    • Row styles feature erlaubt es Zeilen je nach Bedingung unterschiedlich zu färben
    • Neue Shortcuts (copy & paste, ….)
    • Grids erlauben es aus der automatischen Anordnung der Controls auszubrechen
    • Addins können .NET Events nutzen
  • „Rapid Start“ soll alle Einrichtungsvorgange vereinheitlichen
    • Fragebögen erstellen
    • Am Ende entsteht ein Package das auf andere Datenbanken angewendet werden kann -> Fragebögen werden angezeigt und Daten werden eingerichtet

Unit Testing

  • MS nutzt das Ding jetzt endlich selber (und zeigt es sogar in der Keynote)
  • Die Testing Features von NAV 2009 wurden nochmal gezeigt
    • Konvention: // *** hinter jede Zeile die Daten füllt, die für den eigentlichen Test unerheblich sind aber aus anderen Gründen gefüllt werden müssen
  • Die neuen „Page Testing“ features erlauben „Scripted UI testing“ durch den neuen Datentyp TestPage.
    • Erlaubt es Pages zu öffnen: myPage.OPENNEW;
    • Kann Daten füllen: myPage.MyField.SETVALUE(value)
    • Ermöglicht es Buttons zu drücken: myPage.MyAction.INVOKE;
    • Alle Parts (auch Subpages) können abgegriffen werden
    • Felder können auf Inhalt, Sichtbarkeit, Editierbarkeit usw. geprüft werden
    • „Page traps“: Registriert sich auf ein Page und wenn die geöffnet wird dann wird zurück in den Test gesprungen
  • Page Tests dauern länger als Unit Tests aber erlauben es aus Usersicht zu testen
  • “Test Isolation” Fführt ein Change tracking durch und setzt die Datenbank nach einem Test wieder in den Ausgangsstand zurück. Teardown Funktionen sind jetzt nicht mehr nötig. Das funktioniert selbst dann, wenn der zu testende Code ein Commit enthält. Wie geil ist das denn? Hammer!
  • Recorder zur Aufzeichnung von Page Tests ist in Planung.

Debugger

  • Debugger ist in C/AL entwickelt und damit anpassbar. WTF?!
  • Erlaubt Remote NAS Debugging und zeigt den Code in C/AL an J
  • Alle Sessions können debuggt werden (auch noch nicht etablierte wie Webservice Sessions)
  • Sogar Endlosschleife können debuggt werden (ging mit altem Debugger natürlich nicht)
  • Conditional Breakpoints (z.B. nur anhalten wenn Variable > 10)
  • Man kann Breakpoints hinter das Ende von Funktionen setzen -> hält beim Verlassen der Funktion an. Egal welches EXIT genutzt wurde
  • Im Call Stack kann man auch in anderen Ebenen die Variablen inspizieren
  • „Debugger Breakpoint List“ erlaubt es die Breakpoints in Gruppen an und ab zu schalten
  • „Break on record changes“ erlaubt es bei jedem DB write anzuhalten.
  • Debugger hat Option um Codeunit 1 zu skippen
  • „Code Coverage“ Feature kann aus C/AL gestartet werden. Berührte Codezeilen können abgefragt und ausgewertet werden -> kommt ins Test Framework

Performance talk

  • Die Data Access Layer ist jetzt komplet neu in Managed Code geschrieben. Damit ist das Anlegen von Records jetzt deutlich schneller, da nicht zwischen C++ und .NET vermittelt werden muss.
    • Temp Records neu geschrieben. Haben jetzt selbe Sortierung wie normale Records.
    • Marked Records sind jetzt auch entsprechend richtig sortiert.
    • @-Operator funktioniert jetzt wieder richtig beim Filtern.
  • Query object
    • Erlaubt Joins (inner, outer,..) und Aggregations (sum, count, average)
    • Wird auf dem SQL Server ausgeführt -> Kein Netzwerktraffic zum NAV Server
    • Massive Performancegewinne möglich
    • Abgefragte Daten sind read-only -> aber dadurch kaum Locks
    • Programmiermodel analog wie Reports
    • Gut z.B. für alle Statistik Pages
    • Wird bereits in vielen Teilen des Standard genutzt
  • Background Sessions erlauben „Fire and Forget“-Tasks. Das funktioniert sogar in andere Mandanten.
    • Beispiel: Buch.-Blatt starten und die Buchungen werden asynchron auf dem Server ausgeführt. Der Client kann ganz normal weiter arbeiten. Wird bereits zum Buchen von Rechnungen verwendet.
    • Erzeugt allerdings eine komplett neue Session – samt Login usw.
    • Background Sessions kosten nichts für die Lizenz.
    • Die Tasks gehen in eine Job Queue. Die erlaubt dass die Tasks nicht alle parallel stattfinden. Durch diese Linearisierung gibt es weniger konkurrierende Locks.
  • CALCSUMS geht auch auf Feldern die nicht im SIFT sind. Wird dann auf dem SQL Server summiert -> schneller als manuelles Summieren auf dem NAV Server.
  • SETAUTOCALCFIELDS („Smart SQL“) ermöglicht es, dass FlowFields immer direkt beim Abrufen des eigentlichen Datensatzes mit abgerufen werden. -> Weniger Roundtrips zum SQL-Server.
    • Immer an bei Pages und Reports.
  • Connection Pooling zum SQL Server. Nur noch ein Account nötig. Das spart sehr viel Memory.
  • Data caching wurde verbessert. Jetzt werden Record API calls benutzerübergreifend gecached.
  • Security model wurde vereinfacht. „Synchronize all logins“ fällt weg, da Permissions nur noch im NAV Server geprüft werden.
  • Isolation Level wurde von SERIALIZABLE auf REPEATABLE READ geändert.
  • Locks wurden massiv reduziert bzw. es wird viel viel später gelockt (90% vs. 10% der Zeit beim Buchen)
  • Dimensionen wurden komplett überarbeitet (viel weniger Datensätze, weniger Writes).
  • „Buffered inserts“ werden jetzt viel öfter genutzt.
  • „SQL callstack trace“ erlaubt es heraus zu bekommen welche Codezeile ein bestimmtes (schlechtes) SQL statement erzeugt hat.
  • Es werden keine Cursors mehr für den SQL Server benutzt sondern Multiple Active Result Sets (MARS).
    • Folge: Kein SETCURRENTKEY mehr nutzen wenn man die Sortierung nicht braucht. (SETCURRENTKEY ist nur noch schlecht auf SQL Server da er sortieren muss.)

Morgen dann sicher mehr.

Wednesday, 26. September 2012


FSharpx type providers are available as separate nuget packages

Filed under: F# — Steffen Forkmann at 20:20 Uhr

In order to simplify the access of the FSharpx type providers I separated them into their own nuget packages. From now on we have:

At the moment all type providers should work with .NET 4.0 and .NET 4.5 and F# 3.0.

Tags: , ,

Tuesday, 18. September 2012


Dev Open Space 2012 – 19.-21.10.2012 in Leipzig

Filed under: Coding Dojo,F#,NaturalSpec,Veranstaltungen — Steffen Forkmann at 7:08 Uhr

Open Source. Open Space. Developer Open Space Nachdem es sich die letzten beiden Jahre mehr und mehr angekündigt hat, wurde der .NET Open Space in Leipzig nun in Dev Open Space 2012 umgetauft. Dies trägt dem Punkt Rechnung, dass die Themenwünsche der Teilnehmer immer breiter geworden sind und wir uns vor allem auch über git, Ruby, JavaScript, HTML5, node.js, CQRS und vieles mehr unterhalten haben. Weiterhin wird es natürlich trotzdem noch reine .NET-Themen geben.

Neu sind außerdem die kostenlosen Workshops die bereits einen Tag vor dem OpenSpace angeboten werden. Ich selbst werde einen zu F# und Test Driven Development halten:

“Test Driven Development (TDD) bringt viele Vorteile für den Code aber erfordert auch eine Menge Übung. Dieser Workshop zeigt, wie man TDD mit F# mittels NaturalSpec and NCrunch erfolgreich einsetzt. NaturalSpec ist ein F#-TDD- Framework, mit dem Unit Tests auf sehr intuitive Weise ausgedrückt werden können. NCrunch hilft, diese Tests ständig (bei jedem Tastendruck) auszuführen. Das zusammen ergibt einen sehr schnellen Feedbackzyklus und TDD wird deutlich schneller. Nach einer kurzen Einführung in die Tools werden im Workshop gemeinsam kleine Programmieraufgaben gelöst.”

Die Anmeldung ist bereits möglich.

https://inlineafarmaci.com
Tags: ,

Thursday, 13. September 2012


Skillsmatter “Progressive F# Tutorials 2012” session in London

Filed under: F#,NaturalSpec,Veranstaltungen — Steffen Forkmann at 15:54 Uhr

I’m happy to announce that I’m giving one of the “Progressive F# Tutorials 2012” in London this year. This event is going to be legendary. Abstract:

Test-Driven Development can give you a lot of benefits for your code but also needs a lot of practice. Come to this session and learn how to master TDD with F#, NaturalSpec and NCrunch.

NaturalSpec is a F# TDD framework which allows to express tests in a very intuitive way and NCrunch helps to execute these tests continuously on very key stroke. This gives a very fast feedback loop and helps to speed up your TDD coding.

After a short introduction of the tools we’ll try to solve a small coding problem together in a coding dojo. All skill levels are welcome and the session will give a lot of room to try out new ideas.

Book your tickets for this awesome event.

Tags: ,

Graph type providers in FSharpx

Filed under: C#,F#,Informatik,Mathematik — Steffen Forkmann at 9:24 Uhr

After the official Visual Studio 2012 launch yesterday I think it’s a good idea to announce two new type providers which are based on the DGMLTypeProvider from the F# 3.0 Sample Pack.

Synchronous and asynchronous state machine

The first one is only a small extension to the DGMLTypeProvider by Tao. which allows to generate state machines from DGML files. The extension is simply that you can choose between the original async state machine and a synchronous version, which allows easier testing.

image

If you want the async version, which performs all state transitions asynchronously, you only have to write AsyncStateMachine instead of StateMachine.

State machine as a network of types

The generated state machine performs only valid state transitions, but we can go one step further and model the state transitions as compile time restrictions:

image

As you can see the compiler knows that we are in State2 and allows only the transitions to State3 and State4.

If you write labels on the edges of the graph the type provider will generate the method names based on the edge label. In the following sample I’ve created a small finite-state machine which allows to check a binary number if it has an even or odd number of zeros:

image

As you can see in this case the compiler has already calculated that 10100 has an odd number of zeros – no need to run the test Zwinkerndes Smiley.

This stuff is already part of the FSharpx.TypeProviders.Graph package on nuget so please check it out and give feedback.

Tags: , ,

Tuesday, 29. May 2012


Porting Clojure’s persistent data structures to .NET part 2 of n – TransientVector

Filed under: C#,F# — Steffen Forkmann at 18:15 Uhr

In the last post I wrote about the PersistentVector which I ported from Clojure to .NET. It’s implemented as an immutable hash array mapped trie which optimizes the constant factors so that we can assume O(1) for count, nth, conj, assocN, peek and pop.

But for some applications Rich Hickey shows us that we can optimize the constant factors even further. If we are sure that we are only holding exactly one reference to the vector than we can mutate the underlying representation instead of copying the arrays on every change. This idea is implemented in the TransientVector which I also ported from Clojure.Core to FSharpx.

Let’s look at a small example. Here we want to convert a collection to a PersistentVector:

As you can see we iterate over the collection and conj the items to the current PersistentVector. But in every step we forget the reference to the last version. This is exactly the point where can use TransientVector:

Here are the results:

Most higher-order functions on vectors like map are also implemented with this trick.

Tags: , , ,

Porting Clojure’s persistent data structures to .NET part 1 of n – PersistentVector

Filed under: C#,F# — Steffen Forkmann at 14:41 Uhr

Rich Hickey created a very nice set of persistent collections for Clojure. I started to port them to FSharpx and today I want to present the PersistentVector. The basic idea is that we want to have something like an array but immutable.

Vectors (IPersistentVector)

A Vector is a collection of values indexed by contiguous integers. Vectors support access to items by index in log32N hops. count is O(1). conj puts the item at the end of the vector.
     From http://clojure.org/data_structures

These vectors are very fast in practical applications since the depth of the underlying tree is not greater than 7. First performance tests show the following on my machine:

These results are not that far away from the Clojure/Java implementation (see below). The lookup seems to be a bit faster but assoc is slower. Maybe that has something to do with the internal array copy function of .NET:

After installing the FSharpx nuget package can use this Vector<T> from C# like this:

More samples can be found in the PersistentVectorTest.fs file.

Additional resources:

Tags: , , , , ,