Pages

Thursday, July 19, 2012

F# code snippet on codeplex

As we are improving the F# ecosystem, the snippet project is created on codeplex web, so our development progress is visible to everyone. The F# code snippet project hosts the F# snippet file which can be consumed by the F# snippet addon. Feel free to follow and/or leave comments. 


Wednesday, July 11, 2012

Type Provider Project Template

I believe a beard well lathered is half shaved. If I have to do the type provider every now and often, I'd better get this process automated. I already have the code snippet support add basic building blocks for type provider class, but i still need to add the API files and often need to use Alt+Arrow Up/Down to adjust the file orders in the project.

I need to find a way to get this sorted out automatically. The Type Provider template is a solution. It can generate the basic project skeleton with API source file, test script, and the backbone type provider source code. The following screen shot shows how it works when add the package. 




The type provider template will sync with the code in the F# 3.0 sample pack


Tuesday, July 10, 2012

Self Note:Type Provider Assembly Resolve


thanks to my co-worker, Vlad, i can solve the type provider type assembly resolve problem. 

the code is below.

// tpc :TypeProviderConfig argument exposes enviroment-related information to the type provider
[< Microsoft.FSharp.Core.CompilerServices.TypeProvider >]
type TP(tpc : Microsoft.FSharp.Core.CompilerServices.TypeProviderConfig) =
    inherit TypeProviderForNamespaces()
   
    let handler = System.ResolveEventHandler(fun _ args ->
        let asmName = AssemblyName(args.Name)
        // assuming that we reference only dll files
        let expectedName = asmName.Name + ".dll"
        let expectedLocation =
            // we expect to find this assembly near the dll with type provider
            let d = IO.Path.GetDirectoryName(tpc.RuntimeAssembly)
            IO.Path.Combine(d, expectedName)
        if IO.File.Exists expectedLocation then Assembly.LoadFrom expectedLocation else null
        )
    do System.AppDomain.CurrentDomain.add_AssemblyResolve handler
   
    interface System.IDisposable with
        member this.Dispose() = System.AppDomain.CurrentDomain.remove_AssemblyResolve handler

Thursday, June 28, 2012

F# Unit Test Template for DLL built with Visual Studio 2010

I published the F# unit test template and a user reports they cannot run the Visual Studio 2010 DLL with this template on Visual Studio 2012. You need to do a bindingDirect in the App.config file.


        < bindingRedirect oldVersion="4.0.0.0" newVersion="4.3.0.0" />

You can find the full file content in a F# console application. The console application create the app.config by default. If this one still cannot solve your problem, you need create a runsetting file and force the legacy mode = true. Please remember to set the test run setting from Visual Studio menu: Test -> Test Settings -> Select Test Setting files... to use the runsetting you just created.

I have not found any drawback when using the Force Legacy mode. So please let me know if you found something.

Tuesday, June 19, 2012

More Options Added to F# Snippets

I added two options to the snippets.



  • Use space to commit is determine if space key can be to insert the content. The current behavior is TRUE

    Here is a sample to help you understand what is going on.

    1. type "cl".
    2. if this value is TRUE, when you press space, "class" will generated. If this value is FALSE, the space will be inserted.

  • Show Intellisense in session is to determine if another f# snippet message should be shown during the snippet session. The current behavior is TRUE.

    this one is tricky. Let us see this sample:

    1. type "cl"
    2. use tab to complete the "class"
    3. use tab to start the code snippet session
    4. type "cl", if the value is TRUE, the intellisense will show "class". If it is FALSE, nothing will show.
  • The third one's name explains everything. If this option selected, only TAB is accepted as the way to insert code snippet, the ENTER key is disabled. The default value is NOT selected.
the F# built-in intellisense will always show. But you can use "ESC" to dismiss it and still keep the code snippet session active. The old behavior is when you use "ESC", the code snippet session is gone as well (bad!).

Please go to Setup instruction to download latest zip file to do a clean setup or go to VS Gallery to download latest package only (without index xml file)



Saturday, June 16, 2012

F# Type Provider as wrapper class II

Thanks to the question from , I can make the F# type provider more useful.  If you have not read the previous post, you can go to here to read that post first. You do not have to put the sealed class in your type provider code. If you can modify the sealed class, it does not make sense to use type provider. This time, we try to reference to a DLL. The source is code is here, in which there are two solutions. One is the type provider project and the other one is the library project contains a seal class. The library will mimic the third party sealed class.

In the source code, the type provider project references to the library1.dll. Everything seems working correctly, until you try to execute the test code in the second Visual Studio,
type T = Samples.ShareInfo.TPTest.TPTestType
let t = T()
let s = t.F2(2)
printfn "AA"
you will get error:
 The type provider 'Samples.FSharp.ShareInfoProvider.CheckedRegexProvider' reported an error in the context of provided type 'Samples.ShareInfo.TPTest.TPTestType', member '.ctor'. The error: Could not load file or assembly 'Library1, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.

I bet you must jaw-droppingly stare at the screen when you first see this error. Does Visual Studio hide some secrete from you? If you install this DLL into the GAC, everything should be fine. If you do not want to  pollute your GAC, the < visual Studio Installation folder > \Common7\IDE\PrivateAssemblies is the magic folder you can put your Library1.dll.

After the file is under that magic folder, you do not have to restart Visual Studio. Just hit F5 and everything should work. 


If you really want to use the type string as a parameter, there is a tutorial from MSDN. What you need to do is convert the incoming string to type by using Assembly.Load and find the type you want. Please note type provider does not accept System.Type as parameter. It can only take string.



F# Type Provider as wrapper class

I still remember those days when I have to change behavior from a sealed class. I have to use a wrapper class and rewrite each method in the sealed class. When I find out the type provider can inherit an non-object class (see this post), I decide to find a way to simplify this task on this Friday night. The source code is here.

The idea is simple, I need to do a wrapper class around the existing sealed class. In addition, logging function is executed before and after each method call. The equivalence C# code is like:

public sealed class A
{
    public void F1() { ... }
}

public class MyClass
{
    private A a = new A();
    public void F1() { a.F1(); }
}

The type provider generate methods with the same name as the base class method, take same parameter, pass the parameter to base class method, and return values from base method invoke. In addition to the base class invoke, logging methods are invoked before and after.

the base class definition is:

[< Sealed >]
type BaseType2() =  
     member this.F1(s) = printfn "%s" s
     member this.F2(i) = printfn "%d" i 

the code to invoke the type provider is:

#r @".\bin\Debug\ShareInfoSampleTypeProvider.dll"
type T = Samples.ShareInfo.TPTest.TPTestType
let t = T()
t.F1("hello")  //invoke F1 and also output logging info
t.F2(2)         //invoke F2 and also output logging info
Because we have the logging function defined as:

type InsertFunctions = class
    static member LogBeforeExecution(obj:BaseType2, methodName:string) = printfn "log before %A %A" obj methodName
    static member LogAfterExecution(obj:BaseType2, methodName:string) = printfn "log after %A %A" obj methodName
end

the final execution is:

log before Samples.FSharp.ShareInfoProvider.BaseType2 "F1"
hello
log after Samples.FSharp.ShareInfoProvider.BaseType2 "F1" 
log before Samples.FSharp.ShareInfoProvider.BaseType2 "F2"
2
log after Samples.FSharp.ShareInfoProvider.BaseType2 "F2"
If you understand the previous post, the only change for current version is how to use Quotation to invoke the code.

  • The first barrier is to how to invoke a method.
the method call is Expr.Call, which takes three parameters if not a static method and will take only two parameters if it is a static method. If you are familiar about how to get quotations, you can refer to MSDN document. The parameter to the Expr.Call is created by using Expr.Value.
  • The second one is how to invoke two or more statements
Invoking statements is handled by Expr.Sequential. The problem it only takes two elements, seems a problem when we want to invoke more than two statements. Actually this is not a problem at all. If the second parameter is a Expr.Sequential, you can have another space to hold your statement. The following code is the what is inside the InvokeCode.

let baseTExpression = <@@ (%%args.[0]:BaseType2) @@>
let mi = baseTy.GetMethod(methodName)
let logExpr = Expr.Call(typeof.GetMethod("LogBeforeExecution"), [ baseTExpression; Expr.Value(methodName) ])
let invokeExpr = Expr.Call(baseTExpression, mi, args.Tail)
let logAfterExpr = Expr.Call(typeof.GetMethod("LogAfterExecution"), [ baseTExpression; Expr.Value(methodName) ])
Expr.Sequential(logExpr, Expr.Sequential(invokeExpr, logAfterExpr) 
Hopefully this can inspire you to explore more about the F# type provider and apply it to your daily coding adventure. :-)