Showing posts with label Notes from the lab. Show all posts
Showing posts with label Notes from the lab. Show all posts

Thursday, July 11, 2024

F# and OpenSilver v3.0

An update to the previous series of posts.

Having updated to the OpenSilver3.0 .vsix, the process of porting the standard astroclock test app from 2.1 to a newly minted 3.0 base solution was

  1. Add a global.json to keep the dotnet 9.0 pv SDK from being selected by default
  2. Copy the appliction source and resource files from the 2.1 project
  3. Add the extra files to the project - in this case, Computation.fs and textured_paper.png
  4. Adjust the app namespace in the browser and simulator projects
  5. And that's it.

The process was entirely transparent from the app and user experience point of view.

Only the one niggle - an obsolete code warning in the generated browser project persists from previous releases

Severity	Code	Description	Project	File	Line	Suppression State	Details
Warning (active)	CS0618	'WebAssemblyJSRuntime.InvokeUnmarshalled<T0, TResult>(string, T0)' is obsolete: 'This method is obsolete. Use JSImportAttribute instead.'	astroclock.opensilver3._0.Browser	D:\Github\astroclock\astroclock.opensilver3.0\astroclock.opensilver3.0\astroclock.opensilver3._0.Browser\Interop\UnmarshalledJavaScriptExecutionHandler.cs	19		

The code lives here.

Now when life quietens down, I shall have to port my other work-in-progress project, that has been languishing for several months now, from 2.1 to 3.0 as well.

Saturday, February 10, 2024

F# and OpenSilver v2.1

An update to the previous series of posts, just three months after the last one.

Compared to previous iterations, "it just works". The only changes from the original Silverlight code are

  • The XAML is precompiled where it stands in a new F# App project, rather than being loaded at runtime
  • The Y-coordinate related changes in the XAML and F# from 2.0 need to be applied
  • The background image is compiled as Content, and in the XAML, referred to by ImageSource="ms-appx://textured_paper.png", but is otherwise as before (note, I've change the background texture on my website in the last 15 years)

In particular, no messing about with IntermediateOutputPath, or having to create stubs for anything; as I said, "it just works".

Now it's all in one place, I've deployed a live version too.

Wednesday, November 08, 2023

F# and OpenSilver v2.0 (Continued)

An update to the previous series of posts.

Building while NuGetting

While I stand by my assertion that the previous post showed the simplest way to build (by not using NuGet to get the package, but referencing the key assembly the old-fashioned way) here is how to build with OpenSilver 2.0.1 as a NuGet reference. First, add properties

    <SkipXamlPreprocessor>true</SkipXamlPreprocessor>
    <OpenSilverGenerateAssemblyInfo>false</OpenSilverGenerateAssemblyInfo>

then if there isn't already a $(ProjectName).OpenSilver.XamlDesigner.fs file in the root of the project (generated there by the OpenSilver compiler taking some untested path before it was switched off), it should look like this:

// <auto-generated>
//     Generated by the FSharp WriteCodeFragment class.
// </auto-generated>
namespace FSharp

open System
open System.Reflection


[<assembly: System.Runtime.CompilerServices.InternalsVisibleTo("XamlDesignerBackground")>]
do()

added with Compile Action of None, and then see it's copied into the appropriate place by

  <Target Name="FixUp" BeforeTargets="BeforeCompile;CoreCompile">
    <ItemGroup>
        <MisgeneratedFiles Include="$(ProjectName).AssemblyInfo.OpenSilver.XamlDesigner.fs"/>
    </ItemGroup>
    
    <Copy SourceFiles="@(MisgeneratedFiles)"
          DestinationFolder="$(IntermediateOutputPath)"
        />
  </Target>

Publishing less

In the browser project, rather than enabling AOT, which saves time, and not space, have properties

    <SatelliteResourceLanguages>en</SatelliteResourceLanguages>
    <BlazorEnableCompression>false</BlazorEnableCompression>
    <!-- Uncomment to enable AOT compilation when publishing -->
    <!--<RunAOTCompilation>true</RunAOTCompilation>-->

and it doesn't hurt to switch of satellites in the Presentation project, either.

That takes us from

to

Thursday, November 02, 2023

F# and OpenSilver v2.0

An update to the previous series of posts following the v2.0 stable release of OpenSilver.

The good news is that proper F# support in promised in the pipeline, but for now we still have to do some work.

Proceed as before, but in the F# project that inherits from the abstract C# w/XAML, a NuGet based reference to OpenSilver 2.x invokes the XAML preprocessor, and adds a file in the intermediate output directory to the compilation list. I've not found any simpler way to suppress this than by side-stepping NuGet entirely for this project

    <Reference Include="OpenSilver">
      <HintPath>$(NuGetPackageRoot)opensilver\2.0.1\lib\netstandard2.0\OpenSilver.dll</HintPath>
    </Reference>

and having to manage the version.

The other thing I noticed in 2.0 was that the sense of the Y-axis seems to have changed wrt render transforms, e.g. to draw a clock face with a series of lines radiating from a centre of (120,120) like this, rotations incrementing 30 degrees at a time, the negative Y values from 1.1 needed to be positive

        <Line
      Name="t1"
      X1="0" Y1="-108"
      X2="0" Y2="-100"
      Stroke="White"
      StrokeThickness="2">
          <Line.RenderTransform>
            <CompositeTransform Rotation="30" TranslateX="120" TranslateY="120" />
          </Line.RenderTransform>
        </Line>

and for the clock hands, add an extra 180 degrees as well as negating the Y values (that the unlabelled 1 o'clock and 7 o'clock lines have swapped makes no odds, but the hands are important).

The resulting code for running with v2.0 can be found here. The published code comes to ~130Mb, which is a lot chunkier than 25kb of JavaScript needed to do the job, but I guess it could be possible for many apps to share the same library files.

Wednesday, November 16, 2022

Hacking Fake.Build for net7.0

It's too early yet to do the AltCover after-action for net7.0 like I did for net5.0; but it is proving a slog like net5.0 rather than being too transparent to mention like net6.0 was.

While the dotnet 7.0.100 build has its own problems, the Fake build system currently (5.23.x, 6.0 alpha) doesn't handle it at all - the former may work for limited scenarios, but more complicated ones fall over with library version mismatches; the latter politely askes for a v6 runtime and stops.

So, you have a build process based on a Fake script, but want to run with v7.0.100 as SDK, through your project global.json. What do?

Well, the Fake documentation gives some alternatives - turn the script into a net7.0 project that links against the Fake libraries; but that imposes some restrictions on how you set up targets, because you can only define such things (as opposed to the functions that define the target's intended action) after setting up a build context. Or you can run as a fsi script, but the documentation then leads into how to hack paket into the mix.

However, since net5.0, scripts are able to reference nuget packages directly, so rather than having a paket.dependencies, with a #r "paket: groupref [whatever] //", and a call out to paket on the command line, your scripts can be self-contained, with a block of #r "nuget: [library][, optional version]" lines at the top, and a command line that is just dotnet fsi [my fake script.fsx]

And doing it this way, you can build on the net7.0 runtime.

Friday, October 07, 2022

F# and OpenSilver v1.1

An update to the previous series of posts following the v1.1 stable release of OpenSilver.

The recipe given as before just works, when all packages are updated and the browser project build is done with net6.0. One warning is emitted using the latest (6.0.401) SDK, about the IntermediateOutputPath override. The fix is to create a Directory.Build.props in the browser project directory, and move the two lines added to the project previously to the new file

<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <PropertyGroup>
    <IntermediateOutputPath>shorter file path here</IntermediateOutputPath>
    <BaseIntermediateOutputPath>$(IntermediateOutputPath)</BaseIntermediateOutputPath>
  </PropertyGroup>
</Project>

While the System.Windows.Application.LoadComponent API now exists, it requires build-time XAML compilation, and that the named class which it decorates exists in the same assembly, so at this time would only make an adjustment to the C# assembly, replacing the constructor InitializeComponent call with one to LoadComponent, but leaving the same inheritance in the F# layer.

It is possible that the 2.0 release will allow XAML compilation in the F# layer, but on-the-fly compilation seems not to be on the cards.

Also, in language independent mode, the ImageBrush and ImageSource APIs used by the original Silverlight AstroClock are now present. Alas, while that means uncommenting that XAML clause can be done without compile or runtime error, the interesting bits are marked NotImplemented, and live in a "work in progress" source folder, so there is currently no point in doing so.

The resulting code for running with v1.1 can be found here.

Friday, May 13, 2022

F# under the covers XIX -- `with` clauses

Once again, the half-year update has included some interesting changes in code generation, this time around try/with clauses.

Two cases to show this, one simple, one more complex. As always, decompilations are for debug (unoptimized) builds, though in this case, the release builds differ only in details of the branch instructions.

      try
        ...
      with
      | :? FormatException -> Default
      try
        ...
      with
      | :? ArgumentException as a -> a |> (logException store)
      | :? NotSupportedException as n -> n |> (logException store)
      | :? IOException as i -> i |> (logException store)
      | :? System.Security.SecurityException as s -> s |> (logException store)
      | :? UnauthorizedAccessException as u -> u |> (logException store)

Before the 6.0.300 SDK update, the simple case was entirely direct in its handling of the exception

	.try
	{
	...
		IL_006d: leave.s IL_0098
	} // end .try
	catch [netstandard]System.Object
	{
		IL_006f: castclass [netstandard]System.Exception
		IL_0074: stloc.s 8
		IL_0076: ldloc.s 8
		IL_0078: isinst [netstandard]System.FormatException

but afterwards it becomes much fancier, with duplication of effort in the handled case, and only makes sense if the exit from the filter in the unhandled case is faster than from a catch.

	.try
	{
        ...
		IL_006e: leave.s IL_00b5
	} // end .try
	filter
	{
		IL_0070: castclass [netstandard]System.Exception
		IL_0075: stloc.s 8
		IL_0077: ldloc.s 8
		IL_0079: isinst [netstandard]System.FormatException
		IL_007e: stloc.s 9
                ...
	} // end filter
	catch
	{
		IL_008c: castclass [netstandard]System.Exception
		IL_0091: stloc.s 10
		IL_0093: ldloc.s 10
		IL_0095: isinst [netstandard]System.FormatException
		IL_009a: stloc.s 11
                ...
	} // end handler

the new code being equivalent to C# catch (object obj2) when ((((Exception)obj2) is FormatException) ? true : false)

The more complex case was like

	catch [netstandard]System.Object
	{
		IL_0010: castclass [netstandard]System.Exception
		IL_0015: stloc.1
		// ArgumentException ex2 = ex as ArgumentException;
		IL_0016: ldloc.1
		IL_0017: isinst [netstandard]System.ArgumentException
		IL_001c: stloc.2
		// if (ex2 == null)
		IL_001d: ldloc.2
		IL_001e: brfalse.s IL_0022
        ...

or, decompiled

	catch (object obj)
	{
		Exception ex = (Exception)obj;
		ArgumentException ex2 = ex as ArgumentException;
		if (ex2 == null)
		{
			NotSupportedException ex3 = ex as NotSupportedException;
			if (ex3 == null)
			{
			// ... throw on exhaustion
			}
			NotSupportedException j = ex3;
			Exception e4 = j;
			logException(store, e4);
			return result;
		}
		ArgumentException a = ex2;
		Exception e5 = a;
		logException(store, e5);
		return result;
	}

but now it looks like

	catch [netstandard]System.Object
	{
		IL_0010: castclass [netstandard]System.Exception
		IL_0015: stloc.1
		// object obj2 = ex;
		IL_0016: ldloc.1
		IL_0017: stloc.2
		// if (!(obj2 is ArgumentException))
		IL_0018: ldloc.2
		IL_0019: isinst [netstandard]System.ArgumentException
		IL_001e: ldnull // omitted in release
		IL_001f: cgt.un // omitted in release
		IL_0021: brtrue.s IL_0065
...
		IL_0065: ldloc.1
		IL_0066: unbox.any [netstandard]System.ArgumentException
		IL_006b: stloc.s 7

or in C#

	catch (object obj)
	{
		Exception ex = (Exception)obj;
		object obj2 = ex;
		if (!(obj2 is ArgumentException))
		{
			object obj3 = ex;
			if (!(obj3 is NotSupportedException))
			{
			// ... throw on exhaustion
			}
			NotSupportedException j = (NotSupportedException)(object)ex;
			NotSupportedException ex5 = j;
			bool store5 = store;
			NotSupportedException e4 = ex5;
			logException(store5, e4);
			return result;
		}
		ArgumentException a = (ArgumentException)(object)ex;
		ArgumentException ex6 = a;
		bool store6 = store;
		ArgumentException e5 = ex6;
		logException(store6, e5);
		return result;
	}

which discards the results of the isinst instructions, then does an unbox.any for any case that actually matches; which could provide a marginal space improvement, in the case where no clause matches -- i.e. another possible optimization the unhandled exception scenario; which in both cases are the "I don't care, this has just failed completely" route.

Wednesday, October 13, 2021

F# and OpenSilver v1.0

An update to the previous series of posts following the first stable release of OpenSilver.

While the details of which lines of code in the Browser and Simulator projects need to be redirected at the F# types have changed since the earlier posts at alpha-7 release, the principle remains the same -- where the generated code refers to the C#/XAML App type, replace that with the derived F# type. The F# (logic) and C# (just the XAML, reified as abstract base types) are set up exactly as before.

If you're porting an old solution, from a pre-release OpenSilver, unless you've been staying on the bleeding edge, it's simpler to start by creating a new one, copying the F# project and the XAML project from old to overwrite the new, and otherwise starting from scratch, remembering to check in all the as-generated files before making the edits.

At this point, provided that all the repointing to the F# project and types is done correctly, it should all "just work".

There is one gotcha, though, that has appeared in the updates for publishing the Browser WASM since my alpha-7 exploration, in that some potentially very long file paths can now be invoked that point deep under the project's default obj subfolder. If your project is already down a few layers from the drive root it will run foul of the Copy MSBuild task which appears to still labour under the old DOS MAX_PATH of 255 characters. Copying to an overlong path fails by timing out, so breaking the build. In that case add

    <IntermediateOutputPath>shorter file path here</IntermediateOutputPath>
    <BaseIntermediateOutputPath>$(IntermediateOutputPath)</BaseIntermediateOutputPath>

where a suitable up-tree location is specified e.g. starting at the top of the repo, or in a shallow build output directory outside the repo, rather than as a child of a project directory. Note that both values need to be set and aligned, lest defaults be assumed during the process.

The resulting code can be found here.

Thursday, March 04, 2021

F# and XAML and OpenSilver ctd.

Last time, we concluded that what we really want is a reimplementation of the Silverlight System.Windows.Application.LoadComponent, whereas what we have at the moment is generated C# code built from the XAML.

In practice, those generated InitializeComponent methods are a compile-time version of what the runtime component load would give us. This leads to a next step that takes us in the direction of what our ideal would be, and is in any case closer to the initial manual code-only approach.

Start with a new OpenSilver application, and add an F# netstandard2.0 library like last time. This time, however, make this assembly depend on the primary OpenSilver project, and the .Simulation and .Browser projects depend on the F# library. Add OpenSilver to the F# library project, as a nuget package, but this time there's no need to add any ExcludeAssets qualifier, nor to static link the F# core library.

The F# library now contains the Page (or UserControl) and Application classes that you would want to write, but their XAML goes into the C# project that it builds against. In the XAML project, remove everything in the initial classes after the // Enter construction logic here... comments. In the .Simulation project, point the debug parameters at the F# library, and in the .Browser project's RunApplication method, construct the F# Application type. This is important, otherwise nothing will show when you try to run the application!

We can now go one of two ways to invoke the InitializeComponent methods into the F# code.

First, we can treat the generated InitializeComponent code as almost the static utility LoadComponent method we would desire; in which case, in the F# library, the Application leeches from the corresponding generated code by

    member this.InitializeComponent() =
        let prototype = Inversion.App()
        this.Resources <- prototype.Resources

and the Page similarly

    member this.InitializeComponent() =
       let prototype = Inversion.MainPage()
       prototype.InitializeComponent()
       this.Content <- prototype.Content
       let hack = typeof.GetField("_nameScopeDictionary",
                                                System.Reflection.BindingFlags.Instance |||
                                                System.Reflection.BindingFlags.NonPublic)

       hack
       |> Option.ofObj
       |> Option.map ((fun f -> f.GetValue prototype) >> Option.ofObj)
       |> Option.flatten
       |> Option.map(fun o -> o :?> System.Collections.Generic.Dictionary<string, Object>)
       |> Option.iter (fun dict ->
             dict
             |> Seq.iter (fun kvp ->>this.RegisterName(kvp.Key, kvp.Value)))

takes the work from its pre-processed XAML, here using an over-engineered construction to get at the private name registration dictionary while avoiding any hint of NRE. These methods should then be called from the respective F# type constructors.

Alternatively, we remove the sealed qualifier from the generated Application, mark it and the MainPage class abstract, and let the F# types directly subclass the skeleton types in the C# library; this case needs no F# level InitializeComponent methods as the code we're interested in already gets called during the base class constructor call.

If this starts with the same application code as previous -- here my original Silverlight ephemeris clock -- we get the same visual appearance as with the previous approach, so no extra pictures in this post.

F# and XAML and OpenSilver

Emboldened by yesterday's success, what happens when we try to emulate the next steps?

First off, when pasting the F# code into the project, we see that System.Windows.Application.LoadComponent isn't present. Adding the XAML file has that subsumed by the OpenSilver environment, to appear as a <Page/> element in the project file that generates C# code that also fails at compile time. That latter can be switched off by modifying the package reference to look like

    <PackageReference Include="OpenSilver" Version="1.0.0-alpha-007">
      <ExcludeAssets>build; native; contentfiles; analyzers</ExcludeAssets>
    </PackageReference>

but we still don't have the runtime-generated model that System.Windows.Application.LoadComponent would give us.

Without that support, we can still use the hybrid approach of the early F# Silverlight days.

In this case, start with a new OpenSilver project and add an F# netstandard2.0 library as a dependencyand add the modified package reference to the new F# library, to allow access to the GUI types. The C# project gets the project-related XAML file, with the necessary modifications for porting to OpenSilver, and the F# code now, rather than subclassing a UI element, works by composition and delegation, much as for the F#/Silverlight3.0 template for VS2008.

The F# type, rather than subclassing a UI type now takes one as a construction argument, and the C# initializer, having constructed the main control and initialized the UI tree can simply pass that object to the F# type constructor, storing the instance as a member variable. Any event handlers can then delegate to the F# object as well.

  public partial class MainPage : Page
  {
    private Astroclock.AstroPage carry;

    public MainPage()
    {
      this.InitializeComponent();

      var temp = new Astroclock.AstroPage(this);
      temp.Begin();
      carry = temp;
    }
  ...

At this point, attempting a build fails in the C# layer with

2>MSBUILD : error : C#/XAML for HTML5: BeforeXamlPreprocessor (pass 1) failed: System.IO.FileNotFoundException: Could not load file or assembly 'FSharp.Core, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.

so we go back and add

    <OtherFlags>--standalone</OtherFlags>  

to the top-level Property Group on the F# project, and suddenly things start working.

For an example at this stage, I've ported the full applet to OpenSilver here. The other significant change to mention is that rather than just being a UserControl embedded into HTML, this is now a Page with the static HTML text included as TextBlock elements instead, but that is a generic OpenSilver behaviour I've just gone with the flow on, not something F# specific. Nor, I suspect, are the not quite circular circles...

Of course what we really want is a reimplementation of the Silverlight System.Windows.Application.LoadComponent. It's just a pity that that dives into native code in agcore.dll to do the interesting bits.

Also, alas, as currently implemented the browser version doesn't update even though the simulator does. Maybe if the updates were an event driven thing, like the button in the previous example?

Update: Events did the trick -- removing the sleepy BackgroundWorkers from the F# code, and instead adding a DispatcherTimer to fire the relevant UpdateXxx methods once a second unblocked the browser behaviour. The timer can be in either the C# or the F# layer. Again, I suspect that this is generic OpenSilver/Blazor behaviour, not anything F# specific.

Next -- A more LoadComponent-like approach with other benefits.

Wednesday, March 03, 2021

F# and OpenSilver -- first steps

This set of lab notes turned into a series of 3 4 (with the 1.0 release) posts.


Many years ago, I made a series of posts experimenting with F# (then still in preview) and Silverlight

  • documenting some of the hacks required to get it to work. Now, more than a decade later, WASM is the new in-browser hotness, with many approaches to getting your non-JS code to run in browser.

    One of these is OpenSilver, which is intended as a near as possible drop-in replacement for Silverlight. Like the original, it assumes C# and XAML with code-behind first, but let's see what we can do about that...

    Assuming you have OpenSilver set up, then the equivalent of the first post above is relatively simple. Make a new OpenSilver application solution, then replace the actual application project with a new netstandard2.0 F# library (in the solution and as a project reference in the two helper projects). Add OpenSilver as a nuget package to the F# project, then paste in the code from the same first working example to replace the initial stub code. In the .Browser project, fix the type of the App class -- new SilverLightFSharp.MyApp(); -- and then run whichever helper.

    It should look like this :--

    in the simulator after you click the button.

    Next -- Adding XAML, initial attempts

    Tuesday, January 22, 2019

    I like this recipe

    A couple of months back, I'd got a freshly baked and still warm baton from the local shop, and had the idea of thickly buttering it to accompany a bowl of soup -- only to discover how not like butter the "light" spreadable that was in the fridge tasted in bulk, being 2 parts of rapeseed oil to 3 of butter. Looking for alternatives was disappointing, as the commercial spreadables are all much the same, being seed-oil margarine mixes, even the ones boasting that they use olive oil.

    Fortunately, the internet came through, with this recipe for a home-made butter/olive oil spread.

    It does need translating from the American units -- in round numbers it comes to 180g oil for a 250g block of butter. Choose a salad-grade extra-virgin oil, because you will taste it in the finished product (which is part of what makes it so good!). The butter needs to be soft enough that you can cream it but no more -- only a few seconds in the microwave if you get it straight out of the fridge, just enough that it's soft. Melting the butter is -- well, you know how melting and then cooling butter works; the resulting mix turns out somewhat green-ish in colour and doesn't work quite as well.

    Assuming the butter is just right, you can start stirring it with a hand blender, and then add the oil. When it's all mixed, it will have a custard-like consistency and appearance, and can be poured into a suitable container to put in the fridge. Leave it a few hours and it will solidify, but be spreadable. In use, it melts somewhat more readily than the commercial greases e.g. on a freshly toasted crumpet; and you won't want to leave it out of the fridge when not in active use.



    Thursday, January 10, 2019

    Yet another MSBuild-on-Linux back-slash gotcha

    Another variant of a known family of such issues, encountered as AltCover issue #49, the interesting tale of what you get when your MSBuild sets a task array parameter with

    AssemblyExcludeFilter="$(AltCoverAssemblyExcludeFilter.Split('|'))"

    and the value of AltCoverAssemblyExcludeFilter is the-|xunit\.; surprisingly, the answer is

    the-
    xunit/.

    There isn't even an explicit ItemList in sight, and yet the '\' still gets interpreted as a path separator and "helpfully" *nix-ified. Doubling up the '\' via .Replace('\','\\') ahead of the split doesn't escape the character -- you just get a '//' in the output, nor does escaping on the command line as the-|xunit%5C..

    For the moment, with no obvious MSBuild level fix, I'm working around this by doing .Replace('\', %00) and then converting the NUL back inside the custom MSBuild task.


    Saturday, February 25, 2017

    Powershell Transcript cmdlets and secondary runspaces gotcha

    So, I had some fun this past week, with a piece of code that, stripped to its essentials, looked like


    which yields

    Stop-Transcript : An error occurred stopping transcription: The host is not currently transcribing.
    At line:1 char:1
    + Stop-Transcript
    + ~~~~~~~~~~~~~~~
        + CategoryInfo          : InvalidOperation: (:) [Stop-Transcript], PSInvalidOperationException
        + FullyQualifiedErrorId : InvalidOperation,Microsoft.PowerShell.Commands.StopTranscriptCommand

    with a transcript (again, stripped to its essentials) of

    Transcript started, output file is ...
    PS>$pool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1,1)
    PS>$pool.Open()
    PS># do stuff...
    PS>$pool.Close()
    **********************
    Windows PowerShell transcript end

    with nothing after the Close() showing up.

    It turns out that, however you create a runspace, even if using an instance of a custom PSHost subclass and explicitly minting one through CreateRunspace(), the runspace will still get attached to an internal PSHost subtype, which couples it to a whole web of other internal and/or sealed types, eventually linking it to the transcription state of the overall PowerShell session. And when a runspace closes, it closes all open transcripts attached to it.

    WTF FAIL!

    Fortunately, there is one public API available to us that can sever this link, and one that makes a perverse sort of sense, after you've run through all the plumbing:


    which finishes with

    Transcript stopped, output file is...

    and a transcript that looks like

    Transcript started, output file is ...
    
    PS>$pool = [System.Management.Automation.Runspaces.RunspaceFactory]::CreateRunspacePool(1,1)
    PS>$save = [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace
    PS>try {
        [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace = $null
        $pool.Open()
        # do stuff...
        $pool.Close()
        # do more stuff...
    }
    finally {
        [System.Management.Automation.Runspaces.Runspace]::DefaultRunspace = $save
    }
    PS>Stop-Transcript
    **********************
    Windows PowerShell transcript end

    because it turns out that, via a long chain of indirections, it is the -- fortunately thread-static -- global default runspace which is the thing that contaminates our intended-to-be-isolated worker environment.

    Now, it would be understandable if runspace construction were to directly use the default runspace as a prototype, but it's nothing so obvious. It actually comes in via the UI object that is tenuously attached to the runspace reaching out to the default runspace. That's not so good, and speaks of excessive internal coupling.

    Checking metrics on the assembly System.Management.Automation 3.0.0.0, we can see that it is indeed highly internally coupled, with a relational cohesion of 7.22, which is a level that is not so much coherent as positively incestuous. So while I didn't spot any other obvious booby-traps waiting to be sprung, I'm sure there are others that will rise up and bite the occasional edge-case.


    Sunday, February 05, 2017

    SHA256.Create() and "Works on my machine" FIPS-compliance

    I've just had an interesting run-in with a little-advertised and not backwards-compatible feature in .net 4.6 and up, and how it affects FIPS-compliance, for those of us who have to worry about such things.

    You see, in the recent .net versions (unlike the older ones), the selection of the default implementation toggles on whether the machine has HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Lsa\FipsAlgorithmPolicy\[Enabled] set non-zero or not (or the equivalent group policy), and will select a FIPS-certified implementation for SHA256 (and SHA384 and SHA512), and, interestingly only for those flavours of SHA-2, using exactly the same criterion as is used to make the non-compliant implementations raise an exception on construction. So, assuming no app or machine level overrides, the matrix looks like this:

    SHA###.Create()
    no FIPS enforcementFIPS enforced
    .net 4.6 and up

    (Dev machine)
    SHA###Managed

    OK
    SHA###Cng

    "Works on my machine."
    .net 4.5.2 or earlier

    (Slow-moving customer environment)
    SHA###Managed

    OK
    SHA###Managed

    KABOOM!

    The end-stop selection of algorithm defaults (where not overridden by a specific [class].Create()) in .net 4.5.2 are drawn from mscorlib alone, many FIPS-compliant, with the notable exceptions being the "new" (SHA-2, or AES which is present only by the original name of Rijndael), or old-and-deprecated (like MD5) algorithms. As in most cases, [DerivedClass].Create() is just a synonym for [BaseAlgorithm].Create(), you can get a false sense of security here -- SHA256CryptoServiceProvider.Create() will equally spit out an instance of SHA256Managed in three of the cases above, and SHA256Cng in the fourth ("works on my machine").

    TL;DR -- if you have to worry about FIPS, don't use [Algorithm].Create(), but select the one you mean by calling its constructor explicitly.


    Wednesday, January 04, 2017

    C# under the covers III

    So, you have some code that looks like this


        private static bool Match(int item, int? target)
        {
            if (target.HasValue)
            {
                return item == target;
            }
    
            return false;
        }

    How many tests do you need to write to get 100% branch coverage?

    If you answered "two -- one with a value, one without", you'd be as surprised as I was when I tried it.

    It turns out that the implicit extraction of the value of the nullable value contains its own HasValue check, and the IL looks like


    IL_0000: nop
    IL_0001: ldarga.s target
    IL_0003: call instance bool valuetype [mscorlib]System.Nullable\u00601::get_HasValue()
    IL_0008: ldc.i4.0
    IL_0009: ceq
    IL_000b: stloc.1
    IL_000c: ldloc.1
    IL_000d: brtrue.s IL_002b
    
    IL_000f: nop
    IL_0010: ldarg.0
    IL_0011: stloc.2
    IL_0012: ldarg.1
    IL_0013: stloc.3
    IL_0014: ldloc.2
    IL_0015: ldloca.s CS$0$0003
    IL_0017: call instance !0 valuetype [mscorlib]System.Nullable\u00601::GetValueOrDefault()
    IL_001c: bne.un.s IL_0027
    
    IL_001e: ldloca.s CS$0$0003
    IL_0020: call instance bool valuetype [mscorlib]System.Nullable\u00601::get_HasValue()
    IL_0025: br.s IL_0028
    
    IL_0027: ldc.i4.0
    
    IL_0028: stloc.0
    IL_0029: br.s IL_002f
    
    IL_002b: ldc.i4.0
    IL_002c: stloc.0
    IL_002d: br.s IL_002f
    
    IL_002f: ldloc.0
    IL_0030: ret

    Roughly, it goes "get a value, or the default, and test that; if not equal, accept that, otherwise only accept the equality if the nullable had a value."

    If you write


        private static bool Match(int item, int? target)
        {
            if (target.HasValue)
            {
                return item == target.Value;
            }
    
            return false;
        }

    then there is no compiler-generated branch for you to be caught by -- and it's probably slightly better coding practise, anyway.


    Wednesday, December 21, 2016

    Bringing your consumer NAS onto a static IP or non-standard DHCP subnet

    Having gone through this again recently, as I upgraded from the Seagate Central I bought a couple of years back to a later and bigger version, a note to self for when I go through the exercise again in a couple of years, to save having to put it together again --

    1. This is the Secret Sauce : with a dual-NIC computer (e.g. one that's on the home subnet on WiFi but also has an unused ethernet port) set up Internet Connection Sharing of the WiFi to the ethernet. That makes that PC act as a DHCP server on the default 192.168.0/8 subnet on the ethernet link, which is where we can bootstrap the process.
    2. Connect the NAS and the PC to a switch.
    3. Now administer the NAS from the PC to configure its network settings to your main home subnet.
    4. Do not panic if the NAS admin page tells you the reconfigure has not been saved because contact has been lost with the device.
    5. Unplug the NAS from the switch and connect to your router.
    6. Now breathe a sigh of relief as you can now see the NAS on the main network, then complete the NAS set-up.

    The presence of known vulnerabilities in consumer NAS software means that it is also advisable, after a first firmware update, to close all outbound connections from the device, apart from DNS (which tends to be the protocol used for connection liveness testing), so it doesn't go calling out to any remote access server. You do block all the inbound connections already, don't you?

    Yes, this means you can't watch your movies while on holiday, but if that's what you want to do, why ever go anywhere in the first place?


    Sunday, November 27, 2016

    Fixing SMB access in recent Windows 10 updates

    One of the updates that came down the wire to the machine I'm running on the insider slow ring in the last few weeks had the effect that trying to access the SMB share on my router gave a message like

    \\Remote-Server\Path is not accessible. You might not have permission to use this network resource. Contact the administrator of this server to find out if you have access permissions. etc.

    Breaking out Wireshark and comparing a machine still on build 1607 (local account login) with the test machine (MSFT login) showed that the SMB handshake would perform the initial exchange of Session Setup AndX Request, NTLMSSP_NEGOTIATE and Session Setup AndX Response, NTLMSSP_CHALLENGE, Error: STATUS_MORE_PROCESSING_REQUIRED, but the test machine would not then emit a Session Setup AndX Request, NTLMSSP_AUTH, User: Machine\User packet. Further experiment would be needed to tell whether this is because I'm running that machine with a MSFT login rather than a local account, rather than it being an insider build, but in the end, the fix turned out to be going to Control Panel\User Accounts\Credential Manager and creating a new Windows credential just for the Remote-Server address, with username and password sufficient to log on to the share (so for a wide-open read-only share, any username and an empty password will do).

    Sunday, July 24, 2016

    Another little MSVC Rust gotcha.

    I've now set up VSCode with Rust on three machines -- the first two went without a hitch; the latest simply refused when running cargo install racer to compile kernel32-sys, with a x86/x64 mismatch.

    And running dumpbin /headers on the system libraries mentioned in the dump of the failing link command, sure enough the x86 versions were being picked up by default. Now, going in and doing environment surgery started to unblock the system, but I wanted to figure out why this machine was giving problems.

    Much scratching of head later, I realised that the first machine I'd run the command in a PowerShell window without running the Visual Studio VSVARS32.BAT, and that on the second, though I had run that environment set-up as part of my PowerShell profile, that one was running WinX/x86.

    Moral of the story -- don't run cargo install from a Visual Studio prompt.

    Monday, July 04, 2016

    Rain brings on the Rust

    One thing that the wet weather in recent weeks accomplished was to give me some time to play with Rust again, after a go-round a couple of years back, when it still needed to run in an mingw prompt, the code was full of sigils, and I couldn't get an executable to link against advapi32.dll; then again towards the end of 2014 when I migrated a fork of the rust-windows project to the then-current version.

    Last year was a bit of a wash all over, coding for fun being one of the major casualties of the year, so it was pretty much a start anew, to build myself a simple "hello world", porting a simple Win32 program to the new language.

    It was reasonably easy to find useful samples and fragments from which to Frankenstein together a working program. What I did not find, however, was any good guide to adding resources to the project using the native (rather than the foreign) tool-chain. So I cast around a bit and hacked this together:


    It's hacky, since it builds the .rc file to a .res file that actually calls itself a .lib, so that the cargo tool will add the extensionless name as a .lib to the linker, and the linker, fortunately, ignores the file extension and just looks at the file content. It's also hacky in that it hard-codes the path to a local rc.exe, and works around the fact that that tool does not offer an output directory parameter by tree-walking from the directory where we want to place the output to where the source resides.

    I'm sure there must be a better way, but this works. Apart from the fact that a VERSIONINFO compiles OK into the resulting .exe (as can be seen by opening it in Visual Studio), but doesn't show in the file properties. Application icons work just fine, though.