Is it possible to add a description to this target? Or would I have to go about it another way?
Target "Test" (fun _ ->
trace "Testing stuff..."
)
Edit:
TargetHelper allows for the description to be shown when listTargets() is called.
At least, that's my understanding from the code here:
https://github.com/fsharp/FAKE/blob/master/src/app/FakeLib/TargetHelper.fs#L360-L365
If you just want to make your build script readable, you can add a comment in the normal F# way:
// Tests some stuff
Target "Test" (fun _ ->
trace "Testing stuff..."
)
As far as I know, there isn't anything built-in for adding descriptions to your targets in FAKE, but the nice thing about FAKE is that it is just an F# library, and so it is very customizable.
Here is one thing you could do - define your own function that wraps Target, but takes an additional description and builds a "Help" target with the descriptions automatically:
// The 'TargetDescr' function calls 'Target', but stores the description
let Description = System.Text.StringBuilder("Usage:\n")
let TargetDescr name comment f =
Description.AppendFormat(" * {0} - {1}\n", name, comment) |> ignore
Target name f
// Now you can define targets using 'TargetDescr' and get help page for free!
TargetDescr "Test" "Tests some stuff..." (fun _ ->
trace "Testing stuff..."
)
TargetDescr "Help" "Displays this help" (fun _ ->
printfn "%O" Description
)
Related
EDITED to show the ignore return as pointed out by Fyodor and the resulting error
I have a .fsx file with several targets that work as expected, but I can't get a target for OpenCover to work. This is what I have for the Target code:
Target "Coverage" (fun _ ->
OpenCover
(fun p -> { p with ExePath = "./packages/OpenCover.4.6.519/tools/OpenCover.Console.exe"
TestRunnerExePath = "./packages/Machine.Specifications.Runner.Console.0.10.0-Unstable0005/tools/mspec-clr4.exe"
Output = reportDir + "MspecOutput.xml"
Register = "-register:user"
}
)
testDir ## "FakeTest2UnitTesting.dll" + "--xml " + reportDir + "MspecOutput.xml" |> ignore
)
But I now get the following build error:
build.fsx(45,3): error FS0039: The value or constructor 'OpenCover' is not defined. Maybe you want one of the following:
OpenCoverHelper
NCover
I don't know what I am doing wrong. Can someone show me how to use the OpenCoverHelper from the FAKE API?
Thanks
After a lot of playing around an googling, I finally came up with the solution. The basic problem was that I didn't open the OpenCoverHelper. I made the assumption that it was included in FAKE as it is in the Api and there was no documentation saying anything else. So, here is the code I use:
// include Fake lib
#r #"packages/FAKE.4.61.2/tools/FakeLib.dll"
open Fake
open Fake.OpenCoverHelper
Target "Coverage" (fun _ ->
OpenCover (fun p -> { p with
ExePath = "./packages/OpenCover.4.6.519/tools/OpenCover.Console.exe"
TestRunnerExePath = "./packages/Machine.Specifications.Runner.Console.0.10.0-Unstable0005/tools/mspec-clr4.exe"
Output = "./report/MspecOutput.xml"
Register = RegisterUser
})
"./test/FakeTest2UnitTesting.dll + --xml ./report/MspecOutput.xml"
)
Hopefully this will help someone in the future.
my question is the following:
When I try to install my Windows Service I get the following error:
snippet:
...
No public installers with the RunInstallerAttribute.Yes attribute could be found in the <path to exe> assembly.
...
I follow this tutorial
I have one Program.fs file containing:
[<RunInstaller(true)>]
type public FSharpServiceInstaller() =
inherit Installer()
do
< some logic, doesn't really matter >
This should be sufficient, as a matter of fact, I don't even think I need to add the public keyword to the type definition. Installing this executable with InstallUtil.exe gives me the same error as installing it using the following code:
[<EntryPoint>]
let main args =
if Environment.UserInteractive then
let parameter = String.Concat(args);
match parameter with
| "-i" -> ManagedInstallerClass.InstallHelper [| Assembly.GetExecutingAssembly().Location |]
| "-u" -> ManagedInstallerClass.InstallHelper [| "/u"; Assembly.GetExecutingAssembly().Location |]
| _ -> printf "Not allowed!\n"
else
ServiceBase.Run [| new CreditToolsService() :> ServiceBase |];
0
I have tried running this script in PowerShell, cmd and Visual Studio CLI as both administrator and my normal account but I keep getting the same error. If anyone knows what I'm doing wrong I would really appreciate some help.
OK, so here goes...
I've looked at the code provided by user1758475 and just randomly started copy pasting solutions into an application. Don Symes's solution "just worked" and I finally figured out why: I did not (and he does) have a namespace declaration, in my source. Seems like this was the culprit! After I added the namespace the installer worked like a charm.
As Curt Nichols pointed out, the installer should not be in a module because a module effectively hides the type from the calling code.
Thank you for help in figuring this out.
For those of you who want to see a working example:
namespace FileWatcher
open System
open System.Reflection
open System.ComponentModel
open System.Configuration.Install
open System.ServiceProcess
open System.IO
open System.Configuration
type FileWatcherService() =
inherit ServiceBase(ServiceName = "FileWatcher")
let createEvent = fun (args: FileSystemEventArgs) ->
printf "%s has been %s\n" args.FullPath (args.ChangeType.ToString().ToLower())
|> ignore
override x.OnStart(args) =
let fsw = new FileSystemWatcher ()
fsw.Path <- "C:\TEMP"
fsw.NotifyFilter <- NotifyFilters.LastAccess ||| NotifyFilters.LastWrite ||| NotifyFilters.FileName ||| NotifyFilters.DirectoryName ||| NotifyFilters.CreationTime
fsw.Filter <- "*.txt"
fsw.EnableRaisingEvents <- true
fsw.IncludeSubdirectories <- true
fsw.Created.Add(createEvent)
override x.OnStop() =
printf "Stopping the FileWatcher service"
[<RunInstaller(true)>]
type public FSharpServiceInstaller() =
inherit Installer()
do
// Specify properties of the hosting process
new ServiceProcessInstaller
(Account = ServiceAccount.LocalSystem)
|> base.Installers.Add |> ignore
// Specify properties of the service running inside the process
new ServiceInstaller
( DisplayName = "AAA FileWatcher Service",
ServiceName = "AAAFileWatcherService",
StartType = ServiceStartMode.Automatic )
|> base.Installers.Add |> ignore
module Program =
[<EntryPoint>]
let main args =
printf "starting the application...\n"
if Environment.UserInteractive then
let parameter = String.Concat(args);
match parameter with
| "-i" -> ManagedInstallerClass.InstallHelper [| Assembly.GetExecutingAssembly().Location |]
| "-u" -> ManagedInstallerClass.InstallHelper [| "/u"; Assembly.GetExecutingAssembly().Location |]
| _ -> printf "Not allowed!\n"
else
ServiceBase.Run [| new FileWatcherService() :> ServiceBase |];
0
Working live production example at https://github.com/zbilbo/TB4TG/blob/master/TourneyBot.Service/Installer.fs
Think it needs to be installed with InstallUtil.exe though.
Possibly not the finest moment in coding, but that specific service code is from Don Syme more or less: http://blogs.msdn.com/b/dsyme/archive/2011/05/31/a-simple-windows-service-template-for-f.aspx, so it is probably fine, but the rest of the "surrounding" code on that repository may not be idiomatic ;-)
Don Symes blog also explains a lot more so it should be easily to adept it to your needs. It also links to a Win Service Template on VS Gallery: http://blogs.msdn.com/b/mcsuksoldev/archive/2011/05/31/f-windows-application-template-for-windows-service.aspx
I'm using the NUnit testing technique suggested in the yet to be released book "F# Deep Dives Version 12" (Sec. 2.2 "Adding Tests")
The code below executes fine compiled or interactive with MEMOIZE defined/undefined. However, executing the unit test from the GUI NUnit works fine with MEMOIZE undefined, but it fails with a "Null Reference Exception" when MEMOIZE is defined. Notice memorize() uses a Closure. I'm suspecting the exception is happening because some initialization code generated by the compiler is not getting executed when NUnit starts up. What do you think?
open System
open System.Collections.Generic
open NUnit.Framework
open FsUnit
let memoize (f: 'T -> 'U) =
let t = new Dictionary<'T, 'U>(HashIdentity.Structural)
fun n ->
if t.ContainsKey n then t.[n]
else let res = f n
t.Add(n, res)
res
//TODO: Insure J>0 & K>0 & J<K
let isMult =
#if MEMOIZE
memoize (fun (j,k) -> k % j = 0)
#else
(fun (j,k) -> k % j = 0)
#endif
type ``Given the isMult function``() =
[<TestCase(3,1,false)>]
[<TestCase(3,2,false)>]
[<TestCase(3,3,true)>]
[<TestCase(5,10,true)>]
[<TestCase(3,15,true)>]
[<TestCase(5,13,false)>]
[<TestCase(5,15,true)>]
member t.``the result is calculated correctly``(j, k, expected) =
let actual = isMult (j,k)
actual |> should equal expected
UPDATE:
The standalone NUnit application is version 2.6.3.13283.
"FinnNk" gave me an idea! I installed Nuget package "NUnitTestAdapter". Now I can test directly within VS 2013. No surprises, though. I get all tests 'green' when MEMORIZE is undefined and all tests 'red' when it is defined.
The exception is still the same: "Null Reference Exception". However, now that it executes in the IDE, I can have the debugger stop on the exception. All I can determine so far at the breakpoint is that it needs the symbols from:
C:\WINDOWS\Microsoft.Net\assembly\GAC_32\mscorlib\v4.0_4.0.0.0__b77a5c561934e089\mscorlib.pdb
I installed the new VS 2015 Preview Edition. Nothing different happens in that environment. Now that .NET Framework is open source, maybe I can zero the debugger precisely on the problem with the source code for "mscorlib".
Are you running your NUnit tests in multiple threads? Normal dictionary is not thread-safe so weird things can happen. How about if you use ConcurrentDictionary, will it give the same result?
let memoize (f: 'T -> 'U) =
let t = System.Collections.Concurrent.ConcurrentDictionary<'T, 'U>()
fun n -> t.GetOrAdd(n, f)
How do I tell FAKE to compile a .fs file using fsc?
Bonus points for explaining how to also pass arguments like -a and -target:dll.
EDIT: I should clarify that I'm trying to do this without having an MSBuild/xbuild/.sln file. In other words, I want FAKE to fully take the place of MSBuild/xbuild.
FAKE has tasks to directly invoke the F# compiler. Usually you can use the Fsc task. If you want a target to compile an F# source file MyFile.fs to MyFile.exe, you can do:
Target "MyFile.exe" (fun _ ->
["MyFile.fs"]
|> Fsc (fun ps -> ps))
The Fsc task lets you compile multiple source files and specify every F# compile parameter. This simple example doesn't do that, but you can. To read up on the details, head over to the tutorial.
I recommend you read Ian Battersby's page on FAKE make on this topic
Code Excerpt:
first:
#!/bin/bash
TARGET=$1
BUILDTARGETS=$2
if [ -z "$BUILDTARGETS" ]
then
BUILDTARGETS="/Library/Frameworks/Mono.framework/Libraries/mono/xbuild/Microsoft/VisualStudio/v9.0"
fi
if [ -z "$TARGET" ]
then
CTARGET="Default"
else
CTARGET=`echo ${TARGET:0:1} | tr "[:lower:]" "[:upper:]"``echo ${TARGET:1} | tr "[:upper:]" "[:lower:]"`
fi
if [ ! -d "$BUILDTARGETS" ]
then
echo "BuildTargets directory '${BUILDTARGETS}' does not exist."
exit $?
else
export BUILDTARGETS="$BUILDTARGETS"
fi
echo "Executing command: $CTARGET"
mono packages/FAKE.1.64.6/tools/Fake.exe build.fsx target=$CTARGET
then
#I #"packages/FAKE.1.64.6/tools"
#r "FakeLib.dll"
open Fake
let buildDir = #"./build/"
let testDir = #"./test"
let fxReferences = !! #"*/*.csproj"
let testReferences = !! #"Tests/**/*.csproj"
let buildTargets = environVarOrDefault "BUILDTARGETS" ""
Target "Clean" (fun _ ->
CleanDirs [buildDir; testDir]
)
Target "Build" (fun _ ->
MSBuild buildDir "Build" ["Configuration","Debug"; "VSToolsPath",buildTargets] fxReferences
|> Log "Build-Output: "
)
Target "BuildTest" (fun _ ->
MSBuildRelease testDir "Build" testReferences
|> Log "Test-Output: "
)
Target "Test" (fun _ ->
!! (testDir + #"/*.Tests.dll")
|> xUnit (fun p ->
{ p with
ShadowCopy = true;
HtmlOutput = true;
XmlOutput = true;
OutputDir = testDir })
)
"Clean"
==> "Build"
"Build"
==> "BuildTest"
Target "Default" DoNothing
RunParameterTargetOrDefault "target" "Default"
Here's a possibly-useful -- though admittedly small -- twist on Yawar's answer above, which might make it fit in a bit better with the other FAKE examples you're likely to encounter.
The Fsc helper function wants a string list of filenames, which is fine as far as it goes. But most examples use the !! operator to find files, which results in FileIncludes which happens not to be a string list. You can convert a FileIncludes to a string list suitable for feeding to Fsc with Seq.toList.
Just to be thorough, I also convert things to relative pathnames (possibly just a personal quirk).
So here's an example of searching for all *.fs files and compiling them with some representative compiler options:
Target "BuildApp" (fun _ -> // Compile application source code
!! (srcApp ## #"**/*.fs") // Look for F# source files
|> Seq.map toRelativePath // Pathnames relative to current directory
|> Seq.toList // Convert FileIncludes to string list
|> Fsc (fun p -> // which is what the Fsc task wants
{p with // Fsc parameters: making an executable,
FscTarget = Exe // for any CPU, directing output to build
Platform = AnyCpu // area (both assembly & XML doc).
Output = ...exe file... // Executable generated
OtherParams = ["--doc:" + ...xmldoc file...) ]})
) //
As Yawar pointed out, there are a boatload of other compiler options covered in the tutorial.
I found this function Exec here http://fsharp.github.io/FAKE/apidocs/fake-processhelper-shell.html.
Target "UpdateTools" (fun _ ->
Exec "cmd"
)
But I keep getting this error, when I try to run it: "The value or constructor 'Exec' is not defined".
I'm new to FAKE and have not used F#, so forgive me if this should be obvious.
Can someone tell me why this api is not accessible like that?
The documentation is documenting class Shell. That means, you need to call it like:
Target "UpdateTools" (fun _ ->
ignore(Shell.Exec "cmd")
)
or, if you need to work with the error code further:
Target "UpdateTools" (fun _ ->
let errorCode = Shell.Exec "cmd"
//do something with the error code
()
)
Hope it is a bit clearer now.