BorrowedTorch.UIDPGenerator 2.0.0

Prefix Reserved
There is a newer version of this package available.
See the version list below for details.
dotnet add package BorrowedTorch.UIDPGenerator --version 2.0.0
                    
NuGet\Install-Package BorrowedTorch.UIDPGenerator -Version 2.0.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BorrowedTorch.UIDPGenerator" Version="2.0.0">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BorrowedTorch.UIDPGenerator" Version="2.0.0" />
                    
Directory.Packages.props
<PackageReference Include="BorrowedTorch.UIDPGenerator">
  <PrivateAssets>all</PrivateAssets>
  <IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BorrowedTorch.UIDPGenerator --version 2.0.0
                    
#r "nuget: BorrowedTorch.UIDPGenerator, 2.0.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BorrowedTorch.UIDPGenerator@2.0.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BorrowedTorch.UIDPGenerator&version=2.0.0
                    
Install as a Cake Addin
#tool nuget:?package=BorrowedTorch.UIDPGenerator&version=2.0.0
                    
Install as a Cake Tool

BorrowedTorchUI Dependency Properties Generator

Generator of dependency properties for the BorrowedTorchUI framework. It scans a project folder for XML .dpg files and generates, next to each one, a partial element class with dependency property fields, wrapping properties and initialization code, plus an optional partial style class.

It ships as a NuGet package that runs the generator before every build of the consuming project, and can also be run by hand from the command line.

Requirements

  • .NET 10 SDK. The project targets plain net10.0, so it builds and runs on Windows, Linux and macOS.
  • The generated style classes use the C# field keyword, so the consuming project must compile with C# 14 or later.

NuGet package

Reference the package from the project that contains the .dpg files:

<ItemGroup>
  <PackageReference Include="BorrowedTorch.UIDPGenerator" Version="2.0.0" />
</ItemGroup>

Every build then runs the generator over the project folder first and compiles the generated .g.cs files, including on the very first build, when they did not exist yet. The package is a development dependency (PrivateAssets="all"), so it does not flow to projects that reference yours.

MSBuild property Default Description
BorrowedTorchDpgIndentSize 4 Spaces per indentation level in the generated code.
BorrowedTorchDpgEnabled true Set to false to stop generating code during the build.
<PropertyGroup>
  <BorrowedTorchDpgIndentSize>2</BorrowedTorchDpgIndentSize>
</PropertyGroup>

How it behaves in the build:

  • The generator runs out of process with the dotnet host of the build, so it works the same from dotnet build, Visual Studio and Rider. The machine needs a .NET 10 or later runtime, which the .NET 10 SDK already provides.
  • [BUIDPG] warnings and errors are reported as MSBuild warnings and errors, so they show up in the IDE's error list. A .dpg file that fails fails the build.
  • Unchanged output files are not rewritten, so their timestamps stay put and incremental builds are not invalidated. Editing a .dpg file is enough for the Visual Studio fast up-to-date check to start a build.
  • Design-time builds (IntelliSense) do not run the generator.
  • In a multi-targeting project (<TargetFrameworks>) the generator runs once in the outer build, before the per-framework builds, which then find the files up to date and do not write them in parallel.
  • Generated files are only picked up from inside the project folder. A style <Dir> that points outside of it needs its own <Compile Include="…" />.

Building the package

dotnet pack -c Release -o nupkg

The version comes from <Version> in BorrowedTorch.UIDependencyPropertiesGenerator.csproj. To consume the package without publishing it, add the output folder as a package source in a nuget.config next to the consuming solution:

<configuration>
  <packageSources>
    <add key="local" value="path\to\nupkg" />
  </packageSources>
</configuration>

NuGet caches packages by id and version, so bump the version (or clear the cache with dotnet nuget locals global-packages --clear) after repacking a version that was already restored.

Command line

dotnet run --project <path>\BorrowedTorch.UIDependencyPropertiesGenerator.csproj -- <projectDir> [<indentSize>]
Argument Description
projectDir Folder that is scanned recursively for *.dpg files. Must exist.
indentSize Spaces per indentation level in the generated code. Optional, default 4, must be >= 0.

Exit code 0 means every .dpg file was processed. Exit code 1 means the arguments were invalid or at least one file failed (malformed XML, missing <Element> root, I/O error). A failing file is reported on stderr with the [BUIDPG] tag and does not stop the other files.

The tool can also be published as a single executable and run as BorrowedTorch.UIDependencyPropertiesGenerator.exe <projectDir> [<indentSize>]:

dotnet publish -c Release -r win-x64 --self-contained true /p:PublishSingleFile=true

The .dpg format

<Element name="Button">
  <Using>System</Using>
  <Using>BorrowedTorch.UI.Core</Using>
  <Namespace>BorrowedTorch.UI.Elements</Namespace>

  <DP type="int">Width</DP>
  <DP type="string" checkEquality="false">Text</DP>
  <DP type="bool" excludeFromStyle="true">IsPressed</DP>

  <Style name="ButtonStyle">
    <Using>BorrowedTorch.UI.Styles</Using>
    <Namespace>BorrowedTorch.UI.Styles</Namespace>
    <Dir>..\..\Styles</Dir>
  </Style>
</Element>
Node Description
<Element name="…"> Root. name is the element class name; default is the .dpg file name without extension.
<Element>/<Using> One using directive each. BorrowedTorch.UI.Modules is always imported. Blank and duplicate entries are ignored.
<Element>/<Namespace> File-scoped namespace of the element class. Omitted: global namespace.
<DP type="T">Name</DP> One dependency property. type is required. checkEquality (default true) is passed to SetValue; excludeFromStyle (default false) leaves the property out of the style.
<Style name="…"> Present: a style class is generated too. name defaults to <ElementName>Style.
<Style>/<Using> Extra using directives of the style class, after BorrowedTorch.UI.Modules. Element usings and the element's namespace are merged in after them, duplicates removed.
<Style>/<Namespace> File-scoped namespace of the style class. Omitted: global namespace.
<Style>/<Dir> Output folder of the style class. A relative path is resolved against the folder of the .dpg file. Default: ..\..\Styles.

In BorrowedTorchUI every element has its own folder under Elements, and the default <Dir> puts the style next to the other styles, beside the hand-written halves of the partial classes:

Elements/Button/Button.dpg  ->  Elements/Button/Button.g.cs           (next to Button.cs)
                            ->  Styles/ButtonStyle/ButtonStyle.g.cs   (next to ButtonStyle.cs)

Rules and validation:

  • Element and attribute names are case-sensitive; boolean attribute values are not (true, True, TRUE).
  • Only direct children of <Element> and <Style> are read. Values are trimmed.
  • Children may appear in any order. <DP> entries keep their order in the generated members, <Using> entries keep their order in the using directives.
  • type is copied into the C# code as is, so nullable (Color?), generic and array types work. The file is XML, so the < of a generic type must be written as &lt;, and by convention > as &gt;: <DP type="Func&lt;string, string&gt;">TextFilter</DP>.
  • The generated files are compiled with the project's global usings (global using, ImplicitUsings), so <Using> is only needed for namespaces that are not imported globally. The element class's Initialize uses Action, so System must be imported one way or the other.
  • Use / as the separator in <Dir> when the path must also work on Linux or macOS; Windows accepts \ and /.
  • A <DP> without type, without a name, or with a name already declared is skipped with a warning.
  • An invalid boolean attribute value is reported and the default is used.
  • Warnings are printed on stderr with the line number of the offending node; they do not fail the run.

Generated code

For the example above the element class goes to <dpg folder>\Button.g.cs:

// <auto-generated>
//     Generated by BorrowedTorchUI Dependency Properties Generator from Button.dpg.
//     Changes to this file will be lost when it is regenerated.
// </auto-generated>

using BorrowedTorch.UI.Modules;
using System;
using BorrowedTorch.UI.Core;

namespace BorrowedTorch.UI.Elements;

public partial class Button : GenericStyleAndMouseCursorsData<ButtonStyle>
{
    #region Dependency properties
    public DependencyProperty<int> WidthDP;
    public DependencyProperty<string> TextDP;
    public DependencyProperty<bool> IsPressedDP;
    #endregion

    #region Wrapping properties
    public virtual int Width { get => WidthDP.Value; set => WidthDP.SetValue(value, true); }
    public virtual string Text { get => TextDP.Value; set => TextDP.SetValue(value, false); }
    public virtual bool IsPressed { get => IsPressedDP.Value; set => IsPressedDP.SetValue(value, true); }
    #endregion

    #region Dependency properties initialization
    private void InitializeDependencyProperties()
    {
        WidthDP = new DependencyProperty<int>(this);
        TextDP = new DependencyProperty<string>(this);
        IsPressedDP = new DependencyProperty<bool>(this);
    }
    #endregion

    #region Dependency properties disposal
    internal override void DisposeDependencyProperties()
    {
        base.DisposeDependencyProperties();
        WidthDP?.Dispose();
        TextDP?.Dispose();
        IsPressedDP?.Dispose();
    }
    #endregion

    #region Common initialization
    private void Initialize(Action preActions = null, Action postActions = null, Action initSubscriptions = null, Action additionalInstructions = null)
    {
        InitializeDependencyProperties();
        preActions?.Invoke();
        postActions?.Invoke();
        initSubscriptions?.Invoke();
        additionalInstructions?.Invoke();
        ApplyGeneralStyle();
        this.ApplyMouseCursorsOnState();
    }
    #endregion
}

The style class goes to <Dir>\<StyleName>\<StyleName>.g.cs, here <dpg folder>\..\..\Styles\ButtonStyle\ButtonStyle.g.cs:

// <auto-generated>
//     Generated by BorrowedTorchUI Dependency Properties Generator from Button.dpg.
//     Changes to this file will be lost when it is regenerated.
// </auto-generated>

using BorrowedTorch.UI.Modules;
using BorrowedTorch.UI.Styles;
using System;
using BorrowedTorch.UI.Core;
using BorrowedTorch.UI.Elements;

namespace BorrowedTorch.UI.Styles;

public partial class ButtonStyle : BaseStyle
{
    // a bit per property, set once the property was assigned: only assigned properties are applied
    private ulong _assigned0;

    public int Width { get; set => SetProperty(ref field, value, ref _assigned0, (1UL << 0)); }
    public string Text { get; set => SetProperty(ref field, value, ref _assigned0, (1UL << 1)); }

    #region Assigned properties
    public override bool IsSet(string propertyName)
    {
        return propertyName switch
        {
            nameof(Width) => (_assigned0 & (1UL << 0)) != 0,
            nameof(Text) => (_assigned0 & (1UL << 1)) != 0,
            _ => base.IsSet(propertyName)
        };
    }

    protected override bool UnsetProperty(string propertyName)
    {
        switch (propertyName)
        {
            case nameof(Width):
                if ((_assigned0 & (1UL << 0)) == 0) return false;

                Width = default;
                _assigned0 &= ~(1UL << 0);

                return true;
            case nameof(Text):
                if ((_assigned0 & (1UL << 1)) == 0) return false;

                Text = default;
                _assigned0 &= ~(1UL << 1);

                return true;
            default:
                return base.UnsetProperty(propertyName);
        }
    }

    protected override void CopyAssignedTo(BaseStyle target)
    {
        base.CopyAssignedTo(target);

        var style = (ButtonStyle)target;

        if ((_assigned0 & (1UL << 0)) != 0) style.Width = CloneValue(Width);
        if ((_assigned0 & (1UL << 1)) != 0) style.Text = CloneValue(Text);
    }
    #endregion

    #region Apply
    internal override void ApplyValues(BaseElement element, ValueSources valueSource, BaseStyle defaults)
    {
        base.ApplyValues(element, valueSource, defaults);

        var e = (Button)element;
        var d = defaults as ButtonStyle;

        if ((_assigned0 & (1UL << 0)) != 0)
            e.WidthDP.SetValue(Width, true, true, valueSource);
        else if (d != null && (d._assigned0 & (1UL << 0)) != 0)
            e.WidthDP.SetValue(d.Width, true, true, valueSource);
        else
            e.WidthDP.ClearValue(valueSource);

        if ((_assigned0 & (1UL << 1)) != 0)
            e.TextDP.SetValue(Text, true, true, valueSource);
        else if (d != null && (d._assigned0 & (1UL << 1)) != 0)
            e.TextDP.SetValue(d.Text, true, true, valueSource);
        else
            e.TextDP.ClearValue(valueSource);
    }

    internal override void ClearValues(BaseElement element, ValueSources valueSource)
    {
        base.ClearValues(element, valueSource);

        var e = (Button)element;

        e.WidthDP.ClearValue(valueSource);
        e.TextDP.ClearValue(valueSource);
    }
    #endregion
}

A style property counts as assigned once it is set, also when it is set to its default value. IsSet tells whether it is, UnsetProperty takes it back out. ApplyValues sets the assigned properties in the element's layer of the given value source, takes an unassigned property from defaults (a style of the same type) when that has it assigned, and clears the others; ClearValues clears them all. CopyAssignedTo copies the assigned properties to another style of the same type. Base classes go first: the base style's properties are applied and copied before those of the derived style, and DisposeDependencyProperties disposes the base element's dependency properties before the element's own.

The generated code builds on these members of the consuming project, which BorrowedTorchUI has:

  • DependencyProperty<T> with Value, SetValue(T, bool), SetValue(T, bool, bool, ValueSources), ClearValue(ValueSources) and Dispose(), and the ValueSources enum, in BorrowedTorch.UI.Modules.
  • BaseStyle, the hand-written half, with SetProperty<T>(ref T field, T value, ref ulong assigned, ulong bit), which stores the value and sets the bit, and CloneValue<T>(T), which copies a value for a cloned style.
  • BaseElement, the class every element derives from.

Two names are special:

  • An element named BaseElement derives from DisposableBase instead of GenericStyleAndMouseCursorsData<…Style>, its Initialize does not call ApplyGeneralStyle(), and it declares DisposeDependencyProperties as virtual, which the other elements override.
  • A style named BaseStyle implements ICloneable instead of deriving from BaseStyle, and declares the style members above as virtual, which the other styles override.

In BorrowedTorchUI both come from Elements/ElementCore/BaseElement.dpg, which names its style explicitly with <Style name="BaseStyle">; the default would be BaseElementStyle.

Every generated file starts with an <auto-generated> header, so analyzers treat it as generated code. *.g.cs files are listed in .gitignore; regenerate them instead of committing them.

Project layout

File Responsibility
Program.cs Command line parsing, exit code.
Generator.cs Finds .dpg files, resolves output paths, writes files only when changed.
DpgParser.cs Turns the XML into ElementDefinition, StyleDefinition, DependencyPropertyInfo.
SourceEmitter.cs Renders the C# text of the element and style classes.
StyleMembers.cs Renders the members of a style class: assigned bits, properties, apply, clear, copy.
build/*.targets Imported by NuGet into consuming projects: runs the generator before the build.
buildMultiTargeting/*.targets Imports build/*.targets into the outer build of multi-targeting consuming projects.
Tests/BorrowedTorch.UIDependencyPropertiesGenerator.Tests xUnit tests for the parser, the emitter, the file generation, the CLI and the package.

Tests

dotnet test Tests/BorrowedTorch.UIDependencyPropertiesGenerator.Tests

PackageTests pack the generator into a temporary folder feed and build throw-away consuming projects against it with the dotnet CLI, which takes a few tens of seconds. To run only the fast tests:

dotnet test Tests/BorrowedTorch.UIDependencyPropertiesGenerator.Tests --filter "Category!=Package"

There is intentionally no solution file: dotnet build and dotnet run in the repository root keep working on the generator project alone, and the test project references it directly.

License

MIT, see LICENSE.

There are no supported framework assets in this package.

Learn more about Target Frameworks and .NET Standard.

This package has no dependencies.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
4.0.0 137 10/23/2026
3.0.0 121 10/21/2026
2.0.0 110 10/20/2026
1.0.0 112 10/16/2026