Running F# Interactive from Windows context menu

It is looks like really reasonable option!

Gene Belitski's avatarIn F# Major

Today a question popped up on Stack Overflow on how to arrange running F# scripts from Windows context menu, but in case of abnormal termination still having opportunity to access diagnostics. Regular context menu item Run with F# interactive lacks the latter because interactive console window closes abruptly on script failure.

Although I gave an outline of the solution as Stack Overflow answer, it lacks level of details that those who want to use such feature may find useful. So, I decided to give here a more detailed description. I will show the implementation for my own work environment, which is Windows 7 Ultra x64 + VS2012 Ultra RC. Reproducing the approach for other environments may require trivial adjustments.

1. Let’s begin with spying the mechanics of stock context menu item Run with F# interactive… implementation. Let’s fire regedit in Run as Administrator mode and search through the registry for…

View original post 209 more words

F# null trick

fsharp_null_250I have faced with an interesting F# behaviour on the null check. I tried to make a MongoDB query using C# Driver LINQ but F# compiler said that I could not compare the result with null, because result could not be null, but I am sure that query can return nothing =).

I am going to show you the same behaviour with classic LINQ. Please, look at the source code:

open System
open System.Linq
open System.Collections.Generic

type typeA = {Variable:int}

let x = List<typeA>().FirstOrDefault()

if (x = null) then None else Some(x)

If you evaluate first 7 lines of code, you will see that x is equal to null, List is empty, so the value of our LINQ query will be default(null). But, if you try to execute the line number 9, F# compiler will say that it cannot be compiled, because the typeA does not have a null as a proper value, but x is null! Hmm… real magic…

null_trick.fsx(9,9): error FS0043: The type ‘typeA’ does not have ‘null’ as a proper value

Actually, there is an excellent MSDN article “Null Values (F#)“, which should be read carefully. At the first look you may think that AllowNullLiteralAttribute is an answer and try to modify the typeA in the following way:

[<AllowNullLiteral>]
type typeA = {Variable:int}

But you can not have this code compiled, because

null_trick.fsx(6,6): error FS0934: Records, union, abbreviations and struct types cannot have the ‘AllowNullLiteral’ attribute

CLIMutableAttrubute is not an option too, because it does not affect null-behaviour. At the end of the “Null Values (F#)” article you will see an interesting example with a null check:

match box value with
| null -> printf "The value is null."
| _ -> printf "The value is not null."

Boxing is an answer! We need it to perform a null check for an arbitrary value. So, the working example will look like:

open System
open System.Linq
open System.Collections.Generic

type typeA = {Variable:int}

let x = List<typeA>().FirstOrDefault()

if (box x = null) then None else Some(x)

F# world is full of magic. Wonders await us at every turn.

P.S. Read more tales of null in Steffen Forkmann’s blog.

F# Exception Formatter

200px-exception-printerDetailed pretty printed exception is a key to understand the real cause of the problem. We have a piece of code in C# that was reused for many projects, which formats exceptions sequence into human readable form with all exception details.

This source code was translated from C# and hopefully will be helpful to someone else:

open System
open System.Reflection
open System.Text
open Microsoft.FSharp.Core.Printf

let formatDisplayMessage (e:Exception) =
    let sb = StringBuilder()
    let delimeter = String.replicate 50 "*"
    let nl = Environment.NewLine
    let rec printException (e:Exception) count =
        if (e 😕 TargetException && e.InnerException <> null)
        then printException (e.InnerException) count
        else
            if (count = 1) then bprintf sb "%s%s%s" e.Message nl delimeter
            else bprintf sb "%s%s%d)%s%s%s" nl nl count e.Message nl delimeter
            bprintf sb "%sType: %s" nl (e.GetType().FullName)
            // Loop through the public properties of the exception object
            // and record their values.
            e.GetType().GetProperties()
            |> Array.iter (fun p ->
                // Do not log information for the InnerException or StackTrace.
                // This information is captured later in the process.
                if (p.Name <> "InnerException" && p.Name <> "StackTrace" &&
                    p.Name <> "Message" && p.Name <> "Data") then
                    try
                        let value = p.GetValue(e, null)
                        if (value <> null)
                        then bprintf sb "%s%s: %s" nl p.Name (value.ToString())
                    with
                    | e2 -> bprintf sb "%s%s: %s" nl p.Name e2.Message
            )
            if (e.StackTrace <> null) then
                bprintf sb "%s%sStackTrace%s%s%s" nl nl nl delimeter nl
                bprintf sb "%s%s" nl e.StackTrace
            if (e.InnerException <> null)
            then printException e.InnerException (count+1)
    printException e 1
    sb.ToString()

Now, you can print exceptions into a more readable form. For example, if you execute this expression:

let x =
    try
        try
            Some(10 / 0)
        with
        | e -> InvalidOperationException("Incorrect operation",e) |> raise
    with
    | e ->
         printfn "%s" (e|>formatDisplayMessage)
         None

you will see the following output

Incorrect operation
**************************************************
Type: System.InvalidOperationException
TargetSite: Void main@()
Source: FSI-ASSEMBLY
HResult: -2146233079

StackTrace
**************************************************

at <StartupCode$FSI_0019>.$FSI_0019.main@() in D:\Projects\Exception.fs:line 48

2)Attempted to divide by zero.
**************************************************
Type: System.DivideByZeroException
TargetSite: Void main@()
Source: FSI-ASSEMBLY
HResult: -2147352558

StackTrace
**************************************************

at <StartupCode$FSI_0019>.$FSI_0019.main@() in D:\Projects\Exception.fs:line 46

P.S. If you wish, you can add this function into FSI printers list.

fsi.AddPrinter(formatDisplayMessage)

F# Weekly #14, 2013

fsharp_girlWelcome to F# Weekly,

A roundup of F# content from this past week:

News

Video

Blogs

That’s all for now.  Have a great week.

Previous F# Weekly edition – #13

F# Weekly #13, 2013

censoredWelcome to F# Weekly,

One more week has passed. This past week was full of interesting blog posts that are waiting for you:

News

Video

Blogs

That’s all for now.  Have a great week.

Previous F# Weekly edition – #12

“Probably the best coffee in the world.” by Dave Thomas

My first disappointment on F# type system.

Today I found that there are examples of code that correct for C# and could not be compiled in F#. I was very surprised and upset.

I continued playing with Neo4jClient and tried to implement more complex model. I have found that it  is not possible to define F# type for cross entity relationship. To make such relationship I need to define type that implements two interfaces, like this:

type FollowRelationship(target) =
    inherit Relationship(target)
    interface IRelationshipAllowingSourceNode<Person>
    interface IRelationshipAllowingTargetNode<Company>

    override this.RelationshipTypeKey
        with get() = "follow"

But F# compiler does not allow the creation of such type. I’ve got the following compilation error:

This type implements or inherits the same interface at different generic instantiations ‘IRelationshipAllowingParticipantNode’ and ‘IRelationshipAllowingParticipantNode’. This is not permitted in this version of F#.

It happens because IRelationshipAllowingSourceNode and IRelationshipAllowingTargetNode inherited from a single generic interface IRelationshipAllowingParticipantNode and F# does not allow to implement the same interface in different generic instantiations.

Here is an implementation of these interfaces from Neo4jClient source code.

public interface IRelationshipAllowingParticipantNode<out TNode>
{
}
public interface IRelationshipAllowingSourceNode<out TNode>
    : IRelationshipAllowingParticipantNode<TNode>
{
}
public interface IRelationshipAllowingTargetNode<out TNode>
    : IRelationshipAllowingParticipantNode<TNode>
{
}

As I found, there is actually no way to do it in F#. An only option is to write such types in C#. We have a similar question about this on StackOverflow: “Implementing the same interface at different generic instantiations“.

May be it is not a real constrain of F#, but it adds a noise to C#/F# integration. It is means that not all C# design patterns are integrable with F#.

It can be one more answer to

Microsoft Patents related to SharePoint 2013 Search

Extremely useful to understand what is under the hood of SharePoint 2013 Search.

alexeykozhemiakin's avatarInsights into search black magic

While investigating relevancy calculation in new SharePoint 2013, I did a research and it turned out that there are a lot publicly available patents which cover search in SharePoint, most of them are done in scope of Microsoft Research programs, according to names of inventors. Although there is no direct evidence that it was implemented exactly as described in patents, I created an Excel spreadsheet which mimiques logic described in patents which actual values from SharePoint – and numbers match!

I hope most curious of you will find it helpful to deep dive into Enterprise Search relevancy and better understand what happens behind the curtain.

Enterprise relevancy ranking using a neural network

Internal ranking model representation schema

Techniques to perform relative ranking for search results

Ranking and providing search results based in part on a number of click-through features

Document length as…

View original post 28 more words

Using Neo4j Graph DB With F#

Neo4j_logo

Today, I have found Neo4j and could do nothing but play with it. It looks extremely attractive(for example, for enterprise social data).

Neo4j is an open-source, high-performance, enterprise-grade NOSQL graph database.

Neo4j stores data in nodes connected by directed, typed relationships with properties on both, also known as a Property Graph.

First good news, Neo4j has REST API and .NET client library that is available on NuGet. Let’s download it and reference from our script.

#r "System.Net.Http.dll"
#r "System.Net.Http.WebRequest.dll"
#r "Neo4jClient.dll"
#r "Newtonsoft.Json.dll"

open System
open Neo4jClient
open System.Linq

Than, we model a twitter data with following and friendship relationships. Let’s define a Person entity, we need to do nothing more than define a new .NET type.

[<CLIMutable>]
type Person = { Name:string; Twitter:string }

We also need to define relationships. Let’s start from following relationship that is simple and does not store any extra data. To define such relationship we need to write new type that inherits Relationship then implement two interfaces which constrain types of source and target entities that can be connected by this relationship. The last step is to define RelationshipTypeKey property that helps us to identify this relationship in graph.

type FollowRelationship(target) =
    inherit Relationship(target)
    interface IRelationshipAllowingSourceNode<Person>
    interface IRelationshipAllowingTargetNode<Person>

    override this.RelationshipTypeKey
        with get() = "follows"

We also can define relationship that store any extra data. To do so, we need to create a new class for metadata and pass it into Relationship constructor.

[<CLIMutable>]
type KnowsData = { Details:string }

type KnowsRelationship(target, data) =
    inherit Relationship(target, data)
    interface IRelationshipAllowingSourceNode<Person>
    interface IRelationshipAllowingTargetNode<Person>

    override this.RelationshipTypeKey
        with get() = "knows"

So, we are ready to build a graph. Let’s setup a connection to DB and create data.

let client = new GraphClient(new Uri("http://localhost:7474/db/data"));
client.Connect();

let createPerson person =
    client.Create person

let pA = createPerson { Name = "Person A"; Twitter="tA"}
let pB = createPerson { Name = "Person B"; Twitter="tB"}
let pC = createPerson { Name = "Person C"; Twitter="tC"}
let pD = createPerson { Name = "Person D"; Twitter="tD"}

let follows target source =
    client.CreateRelationship(source, FollowRelationship target)

pB |> follows pA
pC |> follows pA
pD |> follows pB
pD |> follows pC

let knows target details source =
  client.CreateRelationship(source,KnowsRelationship(target,{Details=details}))

pB |> knows pC "colleagues"

We have built the graph. It’s time to make a query to search something. Neo4j supports a special graph oriented query language – Cypher that looks readable even for analysts, not only for programmers. Neo4jClient has a LINQ-like query builder for Cypher.

let pAfollowers =
    client.Cypher
        .Start("n", pA)
        .Match("n<-[r:follows]-e")
        .Return<Person>("e")
        .Results
        .Select(fun x -> x.Name)

If you execute this query, you will see a list of followers of “Person A“. It is [“Person B”; “Person C”].

Neo4j has a cool web UI, where you can not only maintain server, but browse, edit and query your data.

Let’s open Data Browser tab, click on the Layout button and add a new layout. Here we can define rules for how we want to show entities based on their internal properties values. Please fill the form according to the picture below.

Neo4j_Layout

After that save the layout, open Data browse tab one more time and search entity by id 2. You should see the following beautiful graph.

Neo4j_graph

Have a good time playing with graphs! 🙂

Using Neo4j with F# – Cypher 2.0” is a new version of this demo that is updated to VS2013 and Cypher 2.0. Thanks to Chris Skardon.