I am trying to use DotCover in FAKE , but it is throwing some error , as I am new to FAKE as well as F# , it's becoming difficult for me to understand the root cause of the problem . Here is the code :
#r "D:/FAKEProject/Fake/packages/FAKE/tools/FakeLib.dll"
open Fake
open Fake.DotCover
let testDir = "D:/FAKEProject/Fake/test/"
let filters = ""
Target "Clean" (fun _ ->
CleanDirs [testDir]
)
Target "TestCoverage" (fun _ ->
!! ("D:/FAKEProject/Fake/UnitTest/UnitTest.dll")
|> DotCoverNUnit
(fun p -> { p with Output = testDir ## "NUnitDotCover.snapshot"
ToolPath = "D:/tools/dotCover/dotCover.exe"
Filters = filters })
(fun nunitOptions -> nunitOptions)
)
"Clean"
==> "TestCoverage"
RunTargetOrDefault "TestCoverage"`
It is giving this error
System.Exception: Error running D:/tools/dotCover/dotCover.exe with exitcode -1
at Fake.DotCover.buildParamsAndExecute#124-6.Invoke(String message) in C:\code\fake\src\app\FakeLib\DotCover.fs:line 124
at Fake.DotCover.buildParamsAndExecute[a](a parameters, FSharpFunc`2 buildArguments, String toolPath, String workingDir, Boolean failBuild) in C:\code\fake\src\app\FakeLib\DotCover.fs:line 124
at Fake.DotCover.DotCoverNUnit(FSharpFunc`2 setDotCoverParams, FSharpFunc`2 setNUnitParams, IEnumerable`1 assemblies) in C:\code\fake\src\app\FakeLib\DotCover.fs:line 190
at FSI_0005.DotCover.clo#16-2.Invoke(Unit _arg2) in D:\FAKEProject\Fake\DotCover.fsx:line 17
at Fake.TargetHelper.runSingleTarget(TargetTemplate`1 target) in C:\code\fake\src\app\FakeLib\TargetHelper.fs:line 492`
I am not able to understand why it is searching in C:\code\fake\src\app\fakelib\dotcover.fs
and what is dotcover.fs it is looking for
How to solve this problem , as I am stuck at this error , If anyone can help me regarding this , it would be very helpful .
Thank You
The mysterious C:\code\fake\src\app\FakeLib\DotCover.fs line is simply telling you the filename (and line number) of the source file that threw the error. Not the filename on your system, but the filename on the system where your FAKE.exe file was built. In other words, it's just telling you where the exception was thrown from.
Looking at the FAKE source code, I see that line 124 is near the end of the following block of code:
let buildParamsAndExecute parameters buildArguments toolPath workingDir failBuild =
let args = buildArguments parameters
trace (toolPath + " " + args)
let result = ExecProcess (fun info ->
info.FileName <- toolPath
info.WorkingDirectory <- getWorkingDir workingDir
info.Arguments <- args) TimeSpan.MaxValue
let ExitCodeForFailedTests = -3
if (result = ExitCodeForFailedTests && not failBuild) then
trace (sprintf "DotCover %s exited with errorcode %d" toolPath result)
else if (result = ExitCodeForFailedTests && failBuild) then
failwithf "Failing tests, use ErrorLevel.DontFailBuild to ignore failing tests. Exited %s with errorcode %d" toolPath result
else if (result <> 0) then
failwithf "Error running %s with exitcode %d" toolPath result
else
trace (sprintf "DotCover exited successfully")
The failwithf function is F#'s equivalent of "throw new Exception()", but it lets you specify a message (using printfn-style format codes like %s) to go with the exception. So there's nothing mysterious going on here in F#, it's just that your D:/tools/dotCover/dotCover.exe program has returned a -1 return code. Return codes of -1 usually mean "generic error", so that's not much help in figuring out the cause.
Your next troubleshooting step is to run your dotCover.exe program manually, giving it the same arguments that FAKE is giving it (shouldn't be too hard to figure out, since the FAKE option records are usually pretty well-named) and the same input. Then see what error messages, if any, dotCover.exe is printing out before it fails.
Related
I am trying to write a F# function that reads a CSV file and returns its lines as a sequence of strings that can be further processed in a pipelined expression. The function should handle all exceptions that can arise when opening and reading a file. This is what I came up with so far:
// takes a filename and returns a sequence of strings
// returns empty sequence in case file could not be opened
let readFile (f : string) =
try
seq {
use r = new StreamReader(f) // if this throws, exception is not caught below
while not r.EndOfStream do
yield reader.ReadLine() // same here
}
with ex
| ex when (ex :? Exception) ->
printfn "Exception: %s" ex.Message
Seq.empty
The problem here is that the exceptions that could be thrown by StreamReader() and ReadLine() are not caught in the exception handler but instead are left uncaught and lead to program termination. Also, there seems to be no way of trying to catch exceptions inside the seq {} sequence expression. Right now I cannot think of any other way to design such a function than reading the whole file into an intermediate collection like a list or an array beforehand and then returning this collection as a sequence to the callers, thereby loosing all the benefits of lazy evaluation.
Has anybody got a better idea ?
The reason the exceptions are not caught by the try-with handler here is that the body of the seq is lazily executed. readFile returns the sequence without generating an exception, but then trying to execute that sequence generates an exception in the context where it is being used.
Since F# doesn't let you use try-with within a sequence expression, you have to be a bit creative here. You could use Seq.unfold to generate the sequence like so, for instance:
let readFile (f: string) =
try
new StreamReader(f)
|> Seq.unfold
(fun reader ->
try
if not reader.EndOfStream then
Some(reader.ReadLine(), reader)
else
reader.Dispose()
None
with ex ->
printfn "Exception while reading line: %O" ex
reader.Dispose()
None)
with ex ->
printfn "Exception while opening the file: %O" ex
Seq.empty
Perhaps a less tricky approach would be to wrap StreamReader.ReadLine so that it doesn't throw exceptions. That way you can still use a seq expression and a use statement.
let readLine (reader: StreamReader) =
try
reader.ReadLine() |> Some
with ex ->
printfn "Exception while reading line: %O" ex
None
let readFile2 (f: string) =
try
let r = new StreamReader(f)
seq {
use reader = r
let mutable error = false
while not error && not reader.EndOfStream do
let nextLine = readLine reader
if nextLine.IsSome then yield nextLine.Value else error <- true
}
with ex ->
printfn "Exception while opening the file: %O" ex
Seq.empty
let readFile (f : string) =
try File.ReadLines(f)
with ex -> printfn "Exception: %s" ex.Message; Seq.empty
I have a two-level F# / Argu command tree. Its abbreviated version looks like that:
[<CliPrefix(CliPrefix.Dash)>]
type RunContGenArgs =
| [<Unique>] [<EqualsAssignment>] [<AltCommandLine("-ql")>] MaxQueueLength of int
with
interface IArgParserTemplate with
member this.Usage =
match this with
| MaxQueueLength _ -> "max queue length."
and
[<CliPrefix(CliPrefix.None)>]
ContGenArguments =
| [<Unique>] [<AltCommandLine("run")>] RunContGen of ParseResults<RunContGenArgs>
with
interface IArgParserTemplate with
member this.Usage =
match this with
| RunContGen _ -> "run Continuous Generation."
which, I then use as follows:
[<EntryPoint>]
let main argv =
let parser = ArgumentParser.Create<ContGenArguments>(programName = "ContGen.exe")
let results = parser.Parse argv
match results.GetAllResults() |> ContGenTask.tryCreate with
| Some task -> task.run()
| None ->
printfn "%s" (parser.PrintUsage())
-1
If I run the command like ContGen.exe run help, then it correctly displays help for the command run. However, it then crashes with ugly exception:
Unhandled Exception: Argu.ArguParseException: USAGE: ContGen.exe runcontgen [help] [-maxqueuelength=<int>]
OPTIONS:
-maxqueuelength, -ql=<int>
max queue length.
help display this list of options.
at Argu.ExceptionExiter.Argu-IExiter-Exit[a](String msg, ErrorCode errorCode) in C:\Users\eirik.tsarpalis\devel\public\Argu\src\Argu\Types.fs:line 62
at Argu.ArgumentParser\`1.Parse(FSharpOption\`1 inputs, FSharpOption\`1 configurationReader, FSharpOption\`1 ignoreMissing, FSharpOption\`1 ignoreUnrecognized, FSharpOption\`1 raiseOnUsage) in C:\Users\eirik.tsarpalis\devel\public\Argu\src\Argu\ArgumentParser.fs:line 180
at Program.main(String[] argv) in C:\GitHub\ClmFSharp\Clm\ContGen\Program.fs:line 8
If I change let results = parser.Parse argv into let results = parser.Parse(argv, raiseOnUsage = false), then it does not crash but does not display any help message. And then since command run can run without any second level argument, the program just keeps going instead of displaying help and quitting.
However, I need ContGen.exe run help just display help message and then quit. How can I achieve that? Thanks.
This is a somewhat peculiar behavior of Argu; you need to provide your own exiter to avoid the exception being thrown there.
Something along these lines:
type NonThrowingExiter() =
interface IExiter with
member __.Name = "Exiter" // I don't know what this is used for; I have never seen it appear anywhere
member __.Exit (msg, code) =
if code = ErrorCode.HelpText then
printfn "%s" msg
exit 0
else
printfn "%s" msg // Maybe have code to color the console output red here
exit 1
To use this, create your `ArgumentParser` like this:
let argumentParser =
Argu.ArgumentParser.Create<ContGenArguments>(helpTextMessage = "Help requested",
errorHandler = NonThrowingExiter())
(You don't actually need to create a class for this, of course; an object expression will do it just as well.)
I am pretty new in f# world. I wrote a very small application that query data from sap and show the result as output. When the application try to connect sap, it could throw some exceptions, in case something goes wrong.
Look at following code:
type Customer() =
let mutable _lastName = String.Empty
member self.LastName with get () = _lastName
member self.QueryData () =
//Some CODES here
let bapi = SapBapi()
let bapiFunc = bapi.GetBapiFunc(dest, "BAPI_CUSTOMER_GETDETAIL1")
match bapiFunc with
| Success bp ->
//Some CODES here
let addressData = bp.GetStructure("PE_PERSONALDATA")
_lastName <- addressData.GetString("LASTNAME")
None
| RfcCommunication ex ->
Some(ex :> Exception)
| RfcLogon ex ->
Some(ex :> Exception)
| RfcAbapRuntime ex ->
Some(ex :> Exception)
As you can see, I handle the error with option type and downcast the throwed exception to base exception type.
In the main function
open CustomerBapi
open System
[<EntryPoint>]
let main argv =
let customer = CustomerBapi.Customer()
let ex = customer.QueryData()
match ex with
| Some ex ->
printfn "%s" ex.Message
| None ->
printfn "%s" customer.LastName
Console.ReadLine() |> ignore
0 // return an integer exit code
This code works but do I handle exception in the right way?
I read an article in internet, that handling exception in f# should return an error code, it's more easy then the exception style.
A typical way of handling errors within the type system is to employ an Either type.
type Either<'a,'b> =
| Left of 'a
| Right of 'b
Conventionally Right value carries the success result and Left carries an error or exception (either as a string or an exc type). A simple way to think about it is to treat it like an option where Right corresponds to the Some case and instead of a None you have error information.
So your code could become:
// QueryData no longer needs to depend on side effects to work,
//so you can make it a regular function instead of a method
let result = queryData()
match result with
| Left ex ->
// handle exception
printfn "%s" ex.Message
| Right result ->
// either set the property, or make customer a record
// and set the name field here
customer.LastName <- result
printfn "%s" customer.LastName
The bit about error codes sounds very wrong, would like to know where you found it.
In general I think that your solution is okay, but can be improved.
You mix a bit the functional and OO style in your code. It feels a bit strange to me that you are working with the exception as the only optional value. Usually the customer should be the value which has the optionality included and the match should be if the customer has a value or not.
The attribute and C# examples are noted here but it doesn't look to be possible for FSharp.
http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
// using System.Runtime.CompilerServices
// using System.Diagnostics;
public void DoProcessing()
{
TraceMessage("Something happened.");
}
public void TraceMessage(string message,
[CallerMemberName] string memberName = "",
[CallerFilePath] string sourceFilePath = "",
[CallerLineNumber] int sourceLineNumber = 0)
{
Trace.WriteLine("message: " + message);
Trace.WriteLine("member name: " + memberName);
Trace.WriteLine("source file path: " + sourceFilePath);
Trace.WriteLine("source line number: " + sourceLineNumber);
}
Sample Output:
message: Something happened.
member name: DoProcessing
source file path: c:\Users\username\Documents\Visual Studio 2012\Projects\CallerInfoCS\CallerInfoCS\Form1.cs
source line number: 31
Is it possible to do the above in F# and if so what is the notation?
A quick search through the compiler source code shows that the name CallerMemberName does not appear anywhere in the code, so I think this feature is not supported. (You can certainly mark a parameter with the attribute, but these attributes are special - they instruct the compiler instead of being discovered and used in some way at runtime.)
Update July 2016: As of late June, F# now supports CallerLineNumber and CallerFilePath, but CallerMemberName is still absent. It seems like that one in particular is more difficult to implement, unfortunately.
On a related note, F# has a few special identifiers that let you get the current source file name and line number, so you might be able to get similar information with __SOURCE_DIRECTORY__ and __LINE__
(but not from the caller as in C#).
Here's a quick 'n' dirty hack, which abuses inline to get this info:
module Tracing =
open System
open System.Text.RegularExpressions
let (|TraceInfo|_|) (s:string) =
let m = Regex.Match(s, "at (?<mem>.+?) in (?<file>.+?\.[a-zA-Z]+):line (?<line>\d+)")
if m.Success then
Some(m.Groups.["mem"].Value, m.Groups.["file"].Value, int m.Groups.["line"].Value)
else None
let inline trace s =
printfn "%s" s
match Environment.StackTrace with
| TraceInfo(m, f, l) ->
printfn " Member: %s" m
printfn " File : %s" f
printfn " Line : %d" l
| _ -> ()
It actually does work, more or less:
I wrote the following code to execute a SQLServer StoredProc in F#
module SqlUtility =
open System
open System.Data
open System.Data.SqlClient
SqlUtility.GetSqlConnection "MyDB"
|> Option.bind (fun con -> SqlUtility.GetSqlCommand "dbo.usp_MyStordProc" con)
|> Option.bind (fun cmd ->
let param1 = new SqlParameter("#User", SqlDbType.NVarChar, 50)
param1.Value <- user
cmd.Parameters.Add(param1) |> ignore
let param2 = new SqlParameter("#PolicyName", SqlDbType.NVarChar, 10)
param2.Value <- policyName
cmd.Parameters.Add(param2) |> ignore
Some(cmd)
)
|> Option.bind (fun cmd -> SqlUtility.ExecuteReader cmd)
|> Option.bind (fun rdr -> ExtractValue rdr)
let GetSqlConnection (conName : string) =
let conStr = ConfigHandler.GetConnectionString conName
try
let con = new SqlConnection(conStr)
con.Open()
Some(con)
with
| :? System.Exception as ex -> printfn "Failed to connect to DB %s with Error %s " conName ex.Message; None
| _ -> printfn "Failed to connect to DB %s" conName; None
let GetSqlCommand (spName : string) (con : SqlConnection) =
let cmd = new SqlCommand()
cmd.Connection <- con
cmd.CommandText <- spName
cmd.CommandType <- CommandType.StoredProcedure
Some(cmd)
let AddParameters (cmd : SqlCommand) (paramList : SqlParameter list) =
paramList |> List.iter (fun p -> cmd.Parameters.Add p |> ignore)
let ExecuteReader (cmd : SqlCommand ) =
try
Some(cmd.ExecuteReader())
with
| :? System.Exception as ex -> printfn "Failed to execute reader with error %s" ex.Message; None
I have multiple problems with this code
First and foremost the repeated use of Option.bind is very irritating... and is adding noise. I need a more clearer way to check if the output was None and if not then proceed.
At the end there should be a cleanupfunction where I should be able to close + dispose the reader, command and connection. But currently at the end of the pipeline all I have is the reader.
The function which is adding parameters... it looks like it is modifying the "state" of the command parameter because the return type is still the same command which was sent it... with some added state. I wonder how a more experienced functional programmer would have done this.
Visual Studio gives me a warning at each of the place where i do exception handling. what's wrong with that" it says
This type test or downcast will always hold
The way I want this code to look is this
let x : MyRecord seq = GetConnection "con" |> GetCommand "cmd" |> AddParameter "#name" SqlDbType.NVarchar 50 |> AddParameter "#policyname" SqlDbType.NVarchar 50 |> ExecuteReader |> FunctionToReadAndGenerateSeq |> CleanEverything
Can you recommend how can I take my code to the desired level and also any other improvement?
I think that using options to represent failed computations is more suitable to purely functional langauges. In F#, it is perfectly fine to use exceptions to denote that a computation has failed.
Your code simply turns exceptions into None values, but it does not really handle this situation - this is left to the caller of your code (who will need to decide what to do with None). You may as well just let them handle the exception. If you want to add more information to the exception, you can define your own exception type and throw that instead of leaving the standard exceptions.
The following defines a new exception type and a simple function to throw it:
exception SqlUtilException of string
// This supports the 'printf' formatting style
let raiseSql fmt =
Printf.kprintf (SqlUtilException >> raise) fmt
Using plain .NET style with a few simplifications using F# features, the code looks a lot simpler:
// Using 'use' the 'Dispose' method is called automatically
let connName = ConfigHandler.GetConnectionString "MyDB"
use conn = new SqlConnection(connName)
// Handle exceptions that happen when opening the connection
try conn.Open()
with ex -> raiseSql "Failed to connect to DB %s with Error %s " connName ex.Message
// Using object initializer, we can nicely set the properties
use cmd =
new SqlCommand( Connection = conn, CommandText = "dbo.usp_MyStordProc",
CommandType = CommandType.StoredProcedure )
// Add parameters
// (BTW: I do not think you need to set the type - this will be infered)
let param1 = new SqlParameter("#User", SqlDbType.NVarChar, 50, Value = user)
let param2 = new SqlParameter("#PolicyName", SqlDbType.NVarChar, 10, Value = policyName)
cmd.Parameters.AddRange [| param1; param2 |]
use reader =
try cmd.ExecuteReader()
with ex -> raiseSql "Failed to execute reader with error %s" ex.Message
// Do more with the reader
()
It looks more like .NET code, but that is perfectly fine. Dealing with databases in F# is going to use imperative style and trying to hide that will only make the code confusing. Now, there is a number of other neat F# features you could use - especially the support for dynamic operators ?, which would give you something like:
let connName = ConfigHandler.GetConnectionString "MyDB"
// A wrapper that provides dynamic access to database
use db = new DynamicDatabase(connName)
// You can call stored procedures using method call syntax
// and pass SQL parameters as standard arguments
let rows = db.Query?usp_MyStordProc(user, policy)
// You can access columns using the '?' syntax again
[ for row in rows -> row?Column1, row?Column2 ]
For more information about this, see the following MSDN series:
How to: Dynamically Invoke a Stored Procedure
Step 1: Create a Database and Show the Poll Options
Step 2: Implement Voting for an Option