Search code examples
c#.netpowershellcakebuild

CAKE: Unsafely load assembly


I use CAKE 0.21.1.0.

I want to add a task that performs the equivalent of this PowerShell operation:

$dlls = @(${dll1}, ${dll2})
$dlls | % { [Reflection.Assembly]::UnsafeLoadFrom($_) }
[StaticClassFromLocalLibrary]::SomeStaticMethod(SomeArgument)

I have decided not to use the CAKE PowerShell add-in because running the PowerShell script directly throws the error <script>.ps1 is not digitally signed. The script will not execute on the system. Because of my employer's IT policy, I am not permitted to run Set-ExecutionPolicy to circumvent the problem. This is why I want to translate the steps taken in the PowerShell script directly into instructions in CAKE.

Initially, I wrote these lines in my CAKE script:

System.Reflection.Assembly.UnsafeLoadFrom(dll1);
System.Reflection.Assembly.UnsafeLoadFrom(dll2);
StaticClassFromLocalLibrary.SomeStaticMethod(SomeArgument);  

However, an exception was thrown, saying that the name StaticClassFromLocalLibrary was not found in the current context.

I then added this line to my CAKE script:

#r @"\\hostName\Folder1\Folder2\Folder3\Folder4\Some.Local.Project.dll"

However, because it was not loaded in an unsafe manner, another exception was thrown, this time informing me that the DLL could not be loaded.

How can I use the #r directive (or any other CAKE command) to specify that I would like the DLL to be loaded in an unsafe manner?

EDIT:

I have solved my problem by consulting this page and adopting the suggestion in the accepted answer.


Solution

  • There's no build in unsafe loading in Cake but as it's just C# what you can do is just convert your PowerShell snippet into C#

    var assembly = System.Reflection.Assembly.UnsafeLoadFrom("./tools/Addins/Newtonsoft.Json/lib/net45/Newtonsoft.Json.dll");
    
    var type = assembly.GetType("Newtonsoft.Json.JsonConvert");
    
    var method = type.GetMethod("SerializeObject", new [] {typeof(object) });
    
    var SerializeObject = (Func<object, string>) Delegate.CreateDelegate(
                                               typeof(Func<object, string>), null, method);
    
    var json = SerializeObject(new { Hello = "World"});
    
    Information("{0}", json);
    

    Which will output something like

    {"Hello":"World"}