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


"Every solution will only lead to new problems."

Category .NET 3.0

In dieser Kategorie geht es um das neue Microsoft .NET Framework 3.0 und den damit verbundenen Technologien Windows Presentation Foundation, Windows Communication Foundation, Windows Workflow Foundation und Windows CardSpace.

Thursday, 3. January 2013


F# and Microsoft Dynamics NAV 2009 Web Services

Filed under: C#,Dynamics NAV 2009,F#,Navision,Visual Studio,WCF — Steffen Forkmann at 9:25 Uhr

If you are a Dynamics NAV developer you have probably heared of the web services feature which comes with the 2009 version. In this walkthrough you can learn how to create and consume a Codeunit Web Service. This method works very well if you only need to create the C# proxy classes once. If you have more than one developer, an automated build system, changing web services or many web services then you will come to a point where this code generation system is very difficult to handle.

Microsoft Visual F# 3.0 comes with feature called “type providers” that helps to simplify your life in such a situation. For the case of WCF the Wsdl type provider allows us to automate the proxy generation. Let’s see how this works.

Web service generation

In the first step we create the Dynamics NAV 2009 Codeunit web service in exactly the same way as in the MSDN walkthrough.

Connecting to the web service

Now we create a new F# console project (.NET 4.0 or 4.5) in Visual Studio 2012 and add references to FSharp.Data.TypeProvidersSystem.Runtime.Serialization and System.ServiceModel. After this we are ready to use the Wsdl type provider:

At this point the type provider creates the proxy classes in the background – no “add web reference” dialog is needed. The only thing we need to do is configuring the access security and consume the webservice:

Access from C#

This is so much easier than the C# version from the walkthrough. But if you want you can still access the provided types from C#. Just add a new C# project to the solution and reference the F# project. In the F# project rename Program.fs to Services.fs and expose the service via a new function:

In the C# project you can now access the service like this:

Changing the service

Now let’s see what happens if we change the service. Go to the Letters Codeunit in Dynamics NAV 2009 and add a second parameter (allLetters:Boolean) to the Capitalize method. After saving the Codeunit go back to the C# project and try to compile it again. As you can see the changes are directly reflected as a compile error.

In the next blog post I will show you how you can easily access a Dynamics NAV 2013 OData feed from F#.

Tags: , , ,

Thursday, 22. March 2012


WPF Designer for F#

Filed under: C#,F#,WPF — Steffen Forkmann at 19:19 Uhr

F# 3.0 brings the new type providers feature which enables a lot of different applications. Today I’m happy to announce that the FSharpx project brings you a WPF designer for F# in the Visual Studio 11 beta.

image

A big kudos to Johann Deneux for writing the underlying XAML type provider.

  1. Create a new F# 3.0 Console application project
  2. Set the output type to “Windows Application” in the project settings
  3. Use nuget and install-package FSharpx.TypeProviders.Xaml
  4. Add references to WindowsBase.dll, PresentationFramework.dll, System.Xaml.dll and PresentationCore.dll
  5. Add a Xaml file to your project. Something like this:
  6. Now you can access the Xaml in a typed way:
  7. Start the project

Enjoy!

BTW: No code generation needed is for this. No more nasty *.xaml.cs files.
BTW2: Try to change the name of Button1 in the Xaml and press save. Zwinkerndes Smiley

Tags: , , , ,

Saturday, 17. January 2009


Stammtisch 1/2009 der .NET User Group Leipzig

Filed under: .NET 3.0,Veranstaltungen — Steffen Forkmann at 14:58 Uhr

Am 20.01.2009 findet zwischen 19:30 und 21:30 Uhr der 1. Stammtisch der .NET User Group Leipzig im Jahr 2009 statt. Treffpunkt ist das TELEGRAPH Café in Leipzig und als besonderes Highlight hat sich Ralf Westphal angekündigt. Eine Anmeldung ist nicht nötig.

Warning: Creating default object from empty value in /www/htdocs/w007928a/blog/wp-content/plugins/wp-referencesmap/GoogleMapsWrapper.php on line 55


https://hrvatskafarmacija24.com
Tags: ,

Monday, 10. November 2008


A immutable sorted list in F# – part II

Filed under: .NET 3.0,English posts,F#,Informatik,Theoretische — Steffen Forkmann at 13:55 Uhr

Last time I showed how the immutable set implementation in F# can be used to get a immutable sorted list. As a result of using sets, the shown version doesn’t support repeated items. This lack can be wiped out by using an additional dictionary (immutable "Map" in F#) which stores the count of each item.

At first I define two basic helper functions for the dictionary:

module MapHelper =
  let addToMap map idx = 
    let value = Map.tryfind idx map
    match value with
      | Some(x) -> Map.add idx (x+1) map
      | None -> Map.add idx 1 map
      
  let removeFromMap map idx = 
    let value = Map.tryfind idx map
    match value with
      | Some(x) -> 
         if x > 1 then 
           Map.add idx (x-1) map 
         else 
           Map.remove idx map
      | None -> map
      
open MapHelper

Now I can adjust my sorted list implementation:

// a immutable sorted list - based on F# set
type 'a SortedFList =
 {items: Tagged.Set<'a,Collections.Generic.IComparer<'a>>;
  numbers: Map<'a,int>;
  count: int}
   
  member x.Min = x.items.MinimumElement
  member x.Items = 
    seq {
      for item in x.items do            
        for number in [1..x.GetCount item] do
          yield item}
          
  member x.Length = x.count
  member x.IsEmpty = x.items.IsEmpty
  member x.GetCount item = 
    match Map.tryfind item x.numbers with
      | None -> 0
      | Some(y) -> y
    
  static member FromList(list, sortFunction) = 
    let comparer = FComparer<'a>.Create(sortFunction)        
    let m = list |> List.fold_left addToMap Map.empty
      
    {new 'a SortedFList with 
      items = Tagged.Set<'a>.Create(comparer,list) and
      numbers = m and
      count = list.Length}
      
  static member FromListWithDefaultComparer(list) = 
    SortedFList<'a>.FromList(list,compare)    
      
  static member Empty(sortFunction) = 
    SortedFList<'a>.FromList([],sortFunction)
      
  static member EmptyWithDefaultComparer() = 
    SortedFList<'a>.Empty(compare)            
       
  member x.Add(y) =     
    {x with 
      items = x.items.Add(y);
      numbers = addToMap x.numbers y;
      count = x.count + 1} 
    
  member x.Remove(y) =     
    if x.GetCount y > 0 then
      {x with 
        items = x.items.Remove(y);
        numbers = removeFromMap x.numbers y;
        count = x.count - 1}
    else
      x        
Tags: , , , ,

A immutable sorted list in F# – part I

Filed under: .NET 3.0,English posts,F#,Informatik,Theoretische — Steffen Forkmann at 12:06 Uhr

F# supports a powerful implementation of immutable lists (see Dustin’s introduction). But for my current work I needed a sorted list and of course I wanted it the F#-way, which means immutable. I didn’t want to reinvent the wheel so I asked my question in the hubFS forum.

It turned out (thanks to Robert) that F# uses red-black trees to give a fast implementation for the immutable set. This means that a set in F# stores all elements in a balanced binary tree and searching for an element costs only O(log n). As a side effect all elements can be visited in the underlying order, which means the set implementation gives a possibility for implementing a sorted list. The only limitation is that a set usually don’t store objects more than once.

The next problem I got, was that my sorted list needs a specific ordering function. The standard F# set implementation uses structural comparison to give an order, which is not the order I need. But Laurent mentioned the Set.Make function in the F# PowerPack. This function creates a new set type for the given ordering function. The only problem with Set.Make is that it was only designed for OCaml compatibility. But with this hint I was able to put all information together and got a nice immutable sorted list implementation for F#:

// wrap orderingFunction as Collections.Generic.IComparer
type 'a FComparer =
  {compareF: 'a -> 'a -> int}
  static member Create(compareF) =
    {new 'a FComparer with compareF = compareF}
  interface Collections.Generic.IComparer<'a> with
    member x.Compare(a, b) = x.compareF a b    
// a immutable sorted list - based on F# set
type 'a SortedFList =
 {items: Tagged.Set<'a,Collections.Generic.IComparer<'a>> }
   
  member x.Min = x.items.MinimumElement
  member x.Items = seq {for item in x.items do yield item}
  member x.Length = x.items.Count
  member x.IsEmpty = x.items.IsEmpty
    
  static member FromList(list, sortFunction) = 
    let comparer = FComparer<'a>.Create(sortFunction)
    {new 'a SortedFList with 
      items = Tagged.Set<'a>.Create(comparer,list)}
      
  static member FromListWithDefaultComparer(list) = 
    SortedFList<'a>.FromList(list,compare)    
      
  static member Empty(sortFunction) = 
    SortedFList<'a>.FromList([],sortFunction)
      
  static member EmptyWithDefaultComparer() = 
    SortedFList<'a>.Empty(compare)            
       
  member x.Add(y) =     
    {x with items = x.items.Add(y)}    
  member x.Remove(y) =     
    {x with items = x.items.Remove(y)}    

Please note that this implementation stores every item only once. Next time I will show a version which allows to store repeated items.

Tags: , , ,

Friday, 24. October 2008


Using PLINQ in F# – Parallel Map and Reduce (Fold) functions – part 2

Filed under: .NET 3.0,English posts,F#,Informatik,PLINQ — Steffen Forkmann at 18:00 Uhr

Last time I showed how it is possible to use parallel map and fold functions to compute the sum of all factorials between 1 and 3000. The result was a nearly perfect load balancing for this task on a two processor machine. This time I will derive a generic function that computes partial results in parallel and folds them to a final result.

Let’s consider our F# example:

let add a b = a + b  
let fac (x:bigint) = 
  [1I..x] |> List.fold_left (*) 1I
let sequential() =
  [1I..3000I]
   |> List.map fac
   |> List.fold_left add 0I

This is the same as:

let calcFactorialSum min max =
  [min..max] 
   |> List.map fac
   |> List.fold_left add 0I  
 
let f1() = calcFactorialSum    1I 2000I
let f2() = calcFactorialSum 2001I 2200I
let f3() = calcFactorialSum 2201I 2400I
let f4() = calcFactorialSum 2401I 2600I
let f5() = calcFactorialSum 2601I 2800I
let f6() = calcFactorialSum 2801I 3000I
 
let sequential2() =
  f1() + f2() + f3() + f4() + f5() + f6()

We spitted the summation into 6 independent tasks and computed the sum of the partial results. This has nearly no bearing on the runtime.

But with the help of PLINQ we can compute each task in parallel:

let asParallel (list: 'a list) = 
  list.AsParallel<'a>()

let runParallel functions = 
    ParallelEnumerable.Select(
      asParallel functions, (fun f ->  f() ) )
 
let pFold foldF seed (data:IParallelEnumerable<'a>)=
  ParallelEnumerable.Aggregate<'a,'b>(
    data, seed, new Func<'b,'a,'b>(foldF))
 

let calcFactorialsParallel() =
  [f1; f2; f3; f4; f5; f6]
    |> runParallel
    |> pFold add 0I

This time we build a list of functions (f1, f2, f3, f4, f5, f6) and run them in parallel. "runParallel” gives us back a list of the partial results, which we can fold with the function “add” to get the final result.

On my Core 2 Duo E6550 with 2.33 GHz and 3.5 GB RAM I get the following results:

Time Normal: 26.576s

Time Sequential2: 26.205s (Ratio: 0.99)

Time “Parallel Functions”: 18.426s (Ratio: 0.69)

Time PLINQ: 14.990s (Ratio: 0.56) (Last post)

Same Results: true

We can see that the parallel computation of the functions f1 – f6 is much faster than the sequential.

But why is the PLINQ-version (see last post) still faster? We can easily see that each partial function needs a different runtime (e.g. it’s much harder to calculate the factorials between 2800 and 3000 than between 2000 and 2200). On my machine I get:

Time F1: 8.738s

Time F2: 2.663s

Time F3: 3.119s

Time F4: 3.492s

Time F5: 3.889s

Time F6: 4.442s

The problem is that the Parallel Framework can only guess each runtime amount in advance. So the load balancing for 2 processors will not be optimal in every case. In the original PLINQ-version there are only small tasks, and the difference between each runtime is smaller. So it is easier to compute the load balancing.

But of course we can do better if we split f1 into two functions f7 and f8:

let f7() = calcFactorialSum    1I 1500I
let f8() = calcFactorialSum 1501I 2000I

So we can get a better load balancing:

Time F1: 8.721s

Time F7: 4.753s

Time F8: 4.829s

Time Normal: 26.137s

Time “Parallel Functions”: 16.138s (Ratio: 0.62)

Same Results: true

Tags: , , , , , ,

Thursday, 23. October 2008


Using PLINQ in F# – Parallel Map and Reduce (Fold) functions – part 1

Filed under: .NET 3.0,C#,F# — Steffen Forkmann at 18:25 Uhr

If your wondering how Google computes query results in such a short time you have to read the famous “MapReduce”-Paper by Jeffrey Dean and Sanjay Ghemawat (2004). It shows how one can split large tasks into a mapping and a reduce step which could then be processed in parallel.

With PLINQ (part of the Parallel Extensions to the .NET Framework) you can easily use “MapReduce”-pattern in .NET and especially F#. PLINQ will take care of all the MultiThreading and load balancing stuff. You only have to give PLINQ a map and a reduce (or fold) function.

Lets consider a small example. Someone wants to compute the sum of the factorials of all integers from 1 to 3000. With List.map and List.fold_left this is a very easy task in F#:

#light
open System

let add a b = a + b
let fac (x:bigint) = [1I..x] |> List.fold_left (*) 1I

let sum =
  [1I..3000I]
    |> List.map fac
    |> List.fold_left add 0I

printfn "Sum of Factorials: %A" sum

Of course you could do much much better if you don’t compute every factorial on its own (I will show this in one of the next parts) – but for this time I need an easy function that is time consuming.

This simple Task needs 27 sec. on my Core 2 Duo E6550 with 2.33 GHz and 3.5 GB RAM.

But we can do better if we use parallel map and fold functions with help of PLINQ:

let pMap (mapF:'a -> 'b) (data:IParallelEnumerable<'a>) =
  ParallelEnumerable.Select(data, mapF)

let pFold foldF seed (data:IParallelEnumerable<'a>)=
  ParallelEnumerable.Aggregate<'a,'b>(
    data, seed, new Func<'b,'a,'b>(foldF))

Now we can easily transform our calculation to a parallel version:

let sum =
  [1I..3000I].AsParallel<bigint>()
    |> pMap fac 
    |> pFold add 0I

Putting all together we can write a small test application:

#light 
open System
open System.Linq
open System.Diagnostics

let testRuntime f =
  let watch = new Stopwatch()
  watch.Start()
  (f(),watch.Elapsed)

let add a b = a + b
let fac (x:bigint) = [1I..x] |> List.fold_left (*) 1I

let list = [1I..3000I]

let pMap (mapF:'a -> 'b) (data:IParallelEnumerable<'a>)=
  ParallelEnumerable.Select(data, mapF)

let pFold foldF seed (data:IParallelEnumerable<'a>)=
  ParallelEnumerable.Aggregate<'a,'b>(
    data, seed, new Func<'b,'a,'b>(foldF))

let PLINQ() =
  list.AsParallel<bigint>()
    |> pMap fac
    |> pFold add 0I

let sequential() =
  list
   |> List.map fac
   |> List.fold_left add 0I

let (sumSequential,timeSequential) =
  testRuntime sequential
printfn "Time Normal: %.3fs" timeSequential.TotalSeconds

let (sumPLINQ,timePLINQ) =
  testRuntime PLINQ
printfn "Time PLINQ: %.3fs" timePLINQ.TotalSeconds

timePLINQ.TotalSeconds / timeSequential.TotalSeconds
  |> printfn "Ratio: %.2f"

sumSequential = sumPLINQ
  |> printfn "Same Results: %A"

On my machine I get the following results:

Time Normal: 27.955s

Time PLINQ: 15.505s

Ratio: 0.55

Same Results: true

This means I get nearly a perfect load balancing on my two processors for this task.

In part II I describe how one can compute a series of functions in parallel.

Tags: , , , , , , ,

Thursday, 16. October 2008


Debugging in Dynamics NAV 2009

Filed under: .NET 3.0,C#,Dynamics NAV 2009,msu solutions GmbH,Visual Studio — Steffen Forkmann at 13:41 Uhr

Claus Lundstrøm zeigt in einem schönen Blogpost wie man in NAV2009 den Code auf Seite der ServiceTier (also auch remote) debuggen kann – und zwar über Visual Studio 2008 direkt im generierten C#-Code. Mit dieser Variante ist man nicht mehr gezwungen das Debugging über den Classic-Client zu tun, sondern kann direkt aus dem Dynamics NAV RoleTailored-Client debuggen.

Dummerweise ist der generierte C#-Code, wie das bei generiertem Code eigentlich immer der Fall ist, nicht gerade “optisch schöner” C#-Style und hat auch nur noch wenig mit dem Original-C/AL-Code zu tun – ist aber immerhin lesbar.

Das ist ein wirklich interessanter Ansatz und erlaubt mit etwas Geschick auch UnitTesting für NAV 2009. Dafür werde ich demnächst mal versuchen ein kleines Beispiel zu bloggen.

Tags: , , , , ,

Sunday, 12. October 2008


ParallelFX wird Kernkomponente vom .NET Framework 4.0

Filed under: .NET 3.0,F# — Steffen Forkmann at 11:32 Uhr

Wie das ParallelFX-Team bekannt gegeben hat, werden die “Parallel Extensions für das .NET Framework” nun zur Kernkomponente vom .NET-Framework 4.0 befördert.

“Parallel Extensions will indeed be a part of the .NET Framework 4.0.  Not only will it be a part of it, it will be a core part of it.”

Das bedeutet, dass dann vermutlich eine ganze Reihe an Basisfunktionen schon von Hause aus parallel verarbeitet werden kann. Anwenden kann man die Bibliotheken auch jetzt schon ganz einfach – allerdings immer mit zusätzlichem Installationsaufwand. Aber es lohnt sich wirklich.

Ein weiterer interessanter Aspekt ist übrigens, dass das F#-Team bereits angekündigt hat demnächst seine asynchronen Workflows auf ParallelFX umzustellen.

Weitere Informationen zu ParallelFX:

Tags: , , , ,

Tuesday, 15. April 2008


Usability-Thementag am 18. April in Leipzig

Filed under: .NET,Veranstaltungen,Visual Studio,WPF — Steffen Forkmann at 15:58 Uhr

Am 18. April 2008 findet von 9 bis 17 Uhr ein “Usability-Thementag” an der Universität Leipzig statt.

“Neben technologieorientierten Lösungsansätzen, wird im ersten von drei Vorträgen im Allgemeinen auf Benutzerfreundlichkeit im alltäglichen Leben eingegangen. Weiter geht es mit Usability-Aspekten im Bereich des Webs, gefolgt von einem Vortrag zu den technischen Möglichkeiten mit der Windows Presentation Foundation (WPF) und Silverlight. Abgerundet wird der Tag mit einem 90-minütigen Workshop, in dem die erlernten WPF-Kenntnisse in einer Demo-Anwendung direkt am Rechner umgesetzt werden.”

Aus dem Newsletter der .NET-Usergroup Leipzig

Wer sich für dieses Event anmelden möchte, kann eine E-Mail an anmeldung@dotnet-leipzig.de schreiben. Die Mail bitte unbedingt mit Vorname, Nachname und dem Betreff “Usability” versenden. Da die Teilnehmerzahl begrenzt ist, sollte man sich mit der Anmeldung beeilen.

Tags: , , , , ,