Signing an F# Assembly (Strong name component)

2020-08-26 05:04发布

问题:

I found this article on CodeProject: http://www.codeproject.com/Articles/512956/NET-Shell-Extensions-Shell-Context-Menus

and thought it would be nice to give it a try, but in F#. So I came up with the following code:

open System
open System.IO
open System.Text
open System.Runtime.InteropServices
open System.Windows.Forms
open SharpShell
open SharpShell.Attributes
open SharpShell.SharpContextMenu

[<ComVisible(true)>]
[<COMServerAssociation(AssociationType.ClassOfExtension, ".txt")>]
type CountLinesExtension() =
    inherit SharpContextMenu.SharpContextMenu()

    let countLines =
        let builder = new StringBuilder()
        do 
            base.SelectedItemPaths |> Seq.iter (fun x -> builder.AppendLine(sprintf "%s - %d Lines" (Path.GetFileName(x)) (File.ReadAllLines(x).Length)) |> ignore  )
            MessageBox.Show(builder.ToString()) |> ignore

    let createMenu =
        let menu = new ContextMenuStrip()
        let itemCountLines = new ToolStripMenuItem(Text = "Count Lines")
        do
            itemCountLines.Click.Add (fun _ -> countLines)
            menu.Items.Add(itemCountLines) |> ignore
        menu

    override this.CanShowMenu() = true
    override this.CreateMenu() = createMenu

However, I noticed that there is no support for signing an F# assembly in VS2012 (step 4. in the article). I learnt that if I want to do so, I need to create a key manually (typing "sn -k keyName.snk" into the command prompt) and then add a flag in "Project Properties -> Build -> Other Flags" (--keyfile:keyName.snk).

I still didn't manage to successfully run this. Moreover, using the author's application (in "Debugging the Shell Extension" section) I get an error that my assembly doesn't contain a COM server.

I believe I'm doing something wrong with the signing the component. Could you help me in running this ?

回答1:

One way to sign an F# assembly is via the AssemblyFileKeyAttribute attribute.

Create a new module and in it put:

module AssemblyProperties

open System
open System.Reflection;
open System.Runtime.InteropServices;

[<assembly:AssemblyKeyFileAttribute("MyKey.snk")>]

do()

Where "MyKey.snk" is the path to your key relative to the project directory.

Another way, as found in this bug report on Microsoft Connect, is to add --keyfile:MyKey.snk to the Other Flags field in the Properties --> Build tab.

Using either approach; running sn -v myfsharpassembly.dll will assert that the assembly is valid after compilation.



回答2:

Maybe the problem is that the assembly is not "ComVisible"?

I'm using this library in F# like this:

[<assembly:ComVisible(true)>]
[<assembly:AssemblyKeyFile("Key.snk")>]
do
   ()

That is, I specify the assembly-level attributes at a top-level do-block.