Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"CompileAssemblyFromSource" in f# powerPack codeDom

I am trying to get going a basic program to dynamically compile and run f# code. I am trying to run the following code:

open System 
open System.CodeDom.Compiler 
open Microsoft.FSharp.Compiler.CodeDom 

// Our (very simple) code string consisting of just one function: unit -> string 
let codeString =
"module Synthetic.Code\n    let syntheticFunction() = \"I've been compiled on the      fly!\""
// Assembly path to keep compiled code
let synthAssemblyPath = "synthetic.dll"

let CompileFSharpCode(codeString, synthAssemblyPath) =
    use provider = new FSharpCodeProvider() 
    let options = CompilerParameters([||], synthAssemblyPath) 
    let result = provider.CompileAssemblyFromSource( options, [|codeString|] ) 
    // If we missed anything, let compiler show us what's the problem
    if result.Errors.Count <> 0 then 
        for i = 0 to result.Errors.Count - 1 do
            printfn "%A" (result.Errors.Item(i).ErrorText)
    result.Errors.Count = 0

if CompileFSharpCode(codeString, synthAssemblyPath) then
    let synthAssembly = Reflection.Assembly.LoadFrom(synthAssemblyPath) 
    let synthMethod  =      synthAssembly.GetType("Synthetic.Code").GetMethod("syntheticFunction") 
    printfn "Success: %A" (synthMethod.Invoke(null, null))
else
    failwith "Compilation failed"

from this site: http://infsharpmajor.wordpress.com/2012/04/01/how-to-dynamically-synthesize-executable-f-code-from-text/

The issue I am having is with the following line:

let result = provider.CompileAssemblyFromSource( options, [|codeString|] ) 

Where I get the exception: The System cannot find the file specified.

I have included the required references Fsharp.compiler.codeDom.dll and Fsharp.compiler.dll and I am not sure what else could be there issue. I am currently trying to get the dll source code for CodeDom off of codeplex and step through it but it would save me a lot of headache if somebody is able to see some issue I am overlooking.

Thank you for your time, -Alper

like image 490
Alper Vural Avatar asked Oct 21 '22 03:10

Alper Vural


1 Answers

Underneath the F# PowerPack's CodeDOM implementation uses the F# compiler to generate code, which means it needs a way to find the compiler and related metadata.

First off you may need to copy the FSharp.Core.sigdata file to your bin folder (the metadata). You may also need to add the F# compiler (fsc.exe) to your path or alternatively just copy it into your bin folder (fsc.exe is in C:\Program Files (x86)\Microsoft SDKs\F#\3.0\Framework\v4.0). Atleast this worked for me on my Windows 8 machine with Visual Studio 2012 installed.

like image 173
Phillip Trelford Avatar answered Oct 25 '22 17:10

Phillip Trelford