← raval.aratoingegneria.it

RAVAL API reference

version 2.10.2 · .NET 10 · Avalonia 12.1.4

RAVAL (Roberto Avalonia Library) writes Avalonia user interfaces in C# without XAML: fluent extensions that set a property and return the control itself, events bound to methods with a name instead of lambdas, and a JSON API server on Kestrel. Everything is in the RAVAL namespace. MIT license.

using RAVAL;

RAva.VStack(8,
  new TextBlock().Text("Total").FontSize(18).Bold(),
  new TextBox().OnTextChanged(Filter).OnEnter(Search),
  RAva.HStack(8,
    new Button().Content("_Cancel").OnClick(Close),
    new Button().Content("_Save").Classes("accent").OnClick(Save)));

RAva

static class RAva

Fluent extensions to build Avalonia user interfaces in code only: each one returns the control itself.

Layout

Margins, alignment, size and position in a Grid or DockPanel.

Margin

static T Margin<T>(this T c, double all) where T : Layoutable

The same margin on all four sides.

static T Margin<T>(this T c, double horiz, double vert) where T : Layoutable

Horizontal and vertical margin.

static T Margin<T>(this T c, double l, double t, double r, double b) where T : Layoutable

Left, top, right, bottom margin.

Align

static T Align<T>(this T c, HorizontalAlignment h, VerticalAlignment v) where T : Layoutable

Horizontal and vertical alignment.

HAlign

static T HAlign<T>(this T c, HorizontalAlignment h) where T : Layoutable

Horizontal alignment.

VAlign

static T VAlign<T>(this T c, VerticalAlignment v) where T : Layoutable

Vertical alignment.

Width

static T Width<T>(this T c, double w) where T : Layoutable

Fixed width.

Height

static T Height<T>(this T c, double h) where T : Layoutable

Fixed height.

Column

static T Column<T>(this T c, int column, int span = 1) where T : Control

The grid column (and how many it spans).

Row

static T Row<T>(this T c, int row, int span = 1) where T : Control

The grid row (and how many it spans).

Dock

static T Dock<T>(this T c, Dock side) where T : Control

The side of the DockPanel.

Content

Children, text, content and tool tips.

Children

static T Children<T>(this T p, params Control[] children) where T : Panel

Adds the children to the panel.

Text

static T Text<T>(this T t, string text) where T : TextBlock

The text of a TextBlock.

Content

static T Content<T>(this T c, object content) where T : ContentControl

The content of a ContentControl. A text with the access underscore («_Save») also gives the accessible name without the underscore: see NameFromContent in RAvaAccess.cs.

Child

static T Child<T>(this T d, Control child) where T : Decorator

The child of a Border (or of another Decorator).

ToolTip

static T ToolTip<T>(this T c, string text) where T : Control

The tip shown when the mouse rests on the control.

Text and fonts

Size, weight, style, family and color of the text; on a panel the children inherit them.

FontSize

static T FontSize<T>(this T c, double size) where T : Control

The font size, in pixels. On a panel it applies to all the text it contains.

FontWeight

static T FontWeight<T>(this T c, FontWeight weight) where T : Control

The font weight (normal, bold...).

Bold

static T Bold<T>(this T c) where T : Control

Bold text.

Italic

static T Italic<T>(this T c) where T : Control

Italic text.

FontFamily

static T FontFamily<T>(this T c, string family) where T : Control

The font family, by name («Consolas», «Segoe UI»...).

Foreground

static T Foreground<T>(this T c, IBrush brush) where T : Control

The color of the text.

static T Foreground<T>(this T c, string color) where T : Control

The color of the text, written as in HTML («#1a7fb5», «#801a7fb5» with the opacity, «Red»).

Wrap

static T Wrap<T>(this T t) where T : TextBlock

The text wraps to a new line when there is no more room, instead of going out of the control.

TextAlign

static T TextAlign<T>(this T t, TextAlignment alignment) where T : TextBlock

The alignment of the lines of text inside the TextBlock (left, center, right).

Frames and look

Border, corners, padding, background, visibility and style classes. On a control without the property they throw a clear InvalidOperationException.

Border

static T Border<T>(this T c, double thickness, double radius = 0) where T : Control

The border thickness and, if given, the radius.

CornerRadius

static T CornerRadius<T>(this T c, double radius) where T : Control

The radius of the rounded corners.

BorderBrush

static T BorderBrush<T>(this T c, IBrush brush) where T : Control

The color of the border.

static T BorderBrush<T>(this T c, string color) where T : Control

The color of the border, written as in HTML.

Padding

static T Padding<T>(this T c, double all) where T : Control

The space inside the border, the same on all 4 sides.

static T Padding<T>(this T c, double horiz, double vert) where T : Control

The space inside the border: horizontal, vertical.

static T Padding<T>(this T c, double l, double t, double r, double b) where T : Control

The space inside: left, top, right, bottom.

Background

static T Background<T>(this T c, IBrush brush) where T : Control

The background: panels, Border, TextBlock and templated controls (windows included).

static T Background<T>(this T c, string color) where T : Control

The background, written as in HTML.

Visible

static T Visible<T>(this T c, bool visible) where T : Control

Visible or hidden (hidden takes no space).

Enabled

static T Enabled<T>(this T c, bool enabled) where T : Control

Enabled or not: a disabled control looks dimmed and does not respond.

Opacity

static T Opacity<T>(this T c, double opacity) where T : Control

The opacity, from 0 (invisible) to 1 (opaque).

Classes

static T Classes<T>(this T c, params string[] classes) where T : Control

Adds the style classes («accent» for the main button of the Fluent theme...).

Ready-made panels

The panels written all the time, in a single call.

HStack

static StackPanel HStack(double spacing, params Control[] children)

A horizontal StackPanel with the given children, spacing pixels apart.

VStack

static StackPanel VStack(double spacing, params Control[] children)

A vertical StackPanel with the given children, spacing pixels apart.

Grid

static Grid Grid(string columns, string rows = "")

A Grid with columns and rows written as in Avalonia: «Auto» fits the content, «*» takes the space left, «2*» twice as much, a number is a fixed size. No rows = a single row.

Spacing

static T Spacing<T>(this T p, double spacing) where T : StackPanel

The space between the children of a StackPanel.

static T Spacing<T>(this T g, double columns, double rows) where T : Grid

The space between the columns and the rows of a Grid.

Events without lambdas

Pass a method with a name: it receives the useful value, not sender and EventArgs.

OnClick

static T OnClick<T>(this T b, Action action) where T : Button

The method to call when the button is clicked.

static MenuItem OnClick(this MenuItem m, Action action)

The method without arguments to call when the item is chosen, like OnClick of the Button. It is not generic: a second generic OnClick with a different constraint would have the same signature (error CS0111); so a Button still uses the generic one, a MenuItem this.

OnTextChanged

static T OnTextChanged<T>(this T t, Action<string> action) where T : TextBox

The method to call with the new text, at every change of the TextBox.

OnEnter

static T OnEnter<T>(this T t, Action action) where T : TextBox

The method to call when Enter is pressed in the TextBox. It listens in the Tunnel phase, before the box: so it also works with AcceptsReturn, where the TextBox would use Enter to start a new line and mark it handled. Then Enter is marked handled: the box does not start a new line, and the Tunnel handlers of the same control added before OnEnter (called after: the last added goes first) do not see it.

OnChecked

static T OnChecked<T>(this T c, Action<bool> action) where T : ToggleButton

The method to call with the new state (true = checked) of a CheckBox, ToggleSwitch, RadioButton...

OnSelectionChanged

static T OnSelectionChanged<T>(this T l, Action<object?> action) where T : SelectingItemsControl

The method to call with the chosen item (null if none) of a ListBox, ComboBox...

Every

static DispatcherTimer Every(TimeSpan interval, Action action)

A timer, already started, that calls the method every interval, on the user interface thread. Stop it with Stop() when it is no longer needed (for instance when the window closes).

OnThemeChanged

static T OnThemeChanged<T>(this T c, Action action) where T : Control

The method to call when the control goes from the light theme to the dark one or back: for those who draw in Render, which Avalonia does not redraw by itself when the theme changes.

Menu items

Keyboard shortcuts for menu items (OnClick works for MenuItem too).

HotKey

static MenuItem HotKey(this MenuItem m, string gesture)

The keyboard shortcut of the item («Ctrl+S», «Ctrl+Shift+N», «F5»): written on the right of the item and working. InputGesture only writes it; HotKey makes it work, even with the menu closed and the focus in a TextBox (tested in Avalonia 12.1.4). Do not use it for Ctrl+C, Ctrl+X, Ctrl+V and Ctrl+A: the TextBox handles them itself. Put the item in the menu with Items.Add: with ItemsSource, while the menu is closed, it is not in the tree yet and the key does not work.

Accessibility

The name a screen reader announces.

AutomationName

static T AutomationName<T>(this T c, string name) where T : Control

The accessible name: what the screen reader (Narrator, VoiceOver, Orca) announces for the control. Needed above all by the buttons with an icon only, which would be announced by their symbol («✕»).

Colors and theme resources

Brushes from HTML colors, and properties that follow the light/dark theme.

Resource

static T Resource<T>(this T c, AvaloniaProperty property, string key) where T : Control

The property bound to a theme resource (it changes by itself with the theme).

ThemeBrush

static IBrush ThemeBrush(this Control c, string key, IBrush fallback)

The brush of a resource in the control's current theme, for those who draw by themselves in Render; fallback if the key is missing or is not a brush.

Brush

static SolidColorBrush Brush(string color)

A solid color brush from a color written as in HTML: «#1a7fb5», «#801a7fb5» (the first two digits are the opacity), «#18b» or a name like «Red». A badly written color throws an exception.

static SolidColorBrush Brush(uint argb)

A solid color brush from a 0xAARRGGBB number (AA = opacity, FF = opaque).

Ready-made look

The pieces of a clean tool window, colored by theme resources (see RStyles.Clean).

Caption

static TextBlock Caption(string text, string key = "InkSoft")

The title of a section: upper case, small, in the resource key (a muted ink).

Card

static Border Card(Control content, string backgroundKey = "Panel", string borderKey = "Border")

A rounded panel with a 1 pixel border around the content; background and border come from the theme resources.

Bar

static Border Bar(Control content, bool top, string backgroundKey = "Bar", string borderKey = "Border")

A bar across the window (toolbar at the top, status bar at the bottom), with the dividing line on the side of the content.

ToolbarButton

static Button ToolbarButton(string text, string tip, Action action)

A flat button of a toolbar, with its tooltip.

CodeBox

static TextBox CodeBox(int lines)

A multiline text box in a monospaced font, without wrapping, tall enough for the given lines.

RThemes

sealed class RThemes

The application colors for the light and the dark theme; Apply puts them in the resources.

Constructors

RThemes

RThemes()

No colors yet: add them with Color, then call Apply.

Properties

Count

int Count { get; }

How many colors have been given.

Methods

Standard

static RThemes Standard()

The colors RAVAL itself uses, ready: Back, Panel, Ink, InkSoft, Border, Bar, Tree, StatusBar, StatusInk, ChartBack, ChartGrid, ChartInk. The dark theme is a graphite with a hint of blue in three levels of light (the bar darkest, the documents, the panels lightest), so that the eye sees where a zone ends without heavy borders; the text is not pure white, which dazzles on a dark background. It is the palette of ASTRIP, made standard. Add the colors of the application with Color before Apply.

Color

RThemes Color(string key, string light, string dark)

A color in its two versions, written as in HTML («#1a7fb5»).

RThemes Color(string key, uint light, uint dark)

A color in its two versions, as 0xAARRGGBB numbers.

Apply

void Apply(Application app)

Puts the colors in the application resources: they apply to every window.

void Apply(StyledElement element)

Puts the colors in the resources of a window or of a control: they apply only inside it.

RStyles

sealed class RStyles

Application styles written in code.

Constructors

RStyles

RStyles()

No styles yet: add them with For and Set.

Fields

Monospace

const string Monospace = "Cascadia Mono, Consolas, Menlo, monospace"

The monospaced fonts of the «code» class.

Properties

Count

int Count { get; }

How many styles have been given.

Methods

For

RStyles For<T>(string cssClass = "") where T : StyledElement

A new style for the controls of type T, or only those with the given class (as in «Button.toolbar»); the next Set calls fill it.

Set

RStyles Set(AvaloniaProperty property, object value)

A value of the last style started with For.

Apply

void Apply(Application app)

Adds the styles to the application (after its theme).

void Apply(StyledElement element)

Adds the styles to one control: they apply to it and to what is inside it, not to the rest of the application (a dense list in a log view, the look of one window).

Clean

static RStyles Clean()

The ready-made set for tool applications. Classes: Button.toolbar (flat), Button.small (palettes), TextBlock.caption (section titles), TextBox.code (netlists, sources, numbers in columns), Border.droparea (a box to drop files on) and Border.drop (the same box while something it accepts is over it, RDrop). Set no border on the box itself: a local value wins over every style.

Accent

static void Accent(Application app, Color light, Color dark)

The accent color of the Fluent theme in the two variants, with the three lighter and three darker shades (SystemAccentColorLight1-3, Dark1-3) at 15, 30 and 45% towards white or black.

RTable

sealed class RTable : UserControl

A read-only table with sorting and selection.

Constructors

RTable

RTable()

An empty table.

Properties

Rows

List<string[]> Rows { get; }

The rows, as they are shown.

SelectedIndex

int SelectedIndex { get; }

The selected row (−1: none).

HeaderKey

string HeaderKey { get; set; }

The theme resource of the header background.

StripeKey

string StripeKey { get; set; }

The theme resource of the stripes.

Events

SelectionChanged

event Action<int>? SelectionChanged

When the selection changes, with the new row.

Methods

Columns

RTable Columns(params string[] headers)

The columns; «:R» right, «:C» center at the end of a header.

Header

string Header(int column)

The header of a column (without the alignment suffix).

AddRow

RTable AddRow(params string[] cells)

Adds a row (missing cells are empty).

Clear

void Clear()

Removes all the rows.

Select

void Select(int row)

Selects a row (−1: none) and tells SelectionChanged.

Sort

void Sort(int column, bool descending = false)

Sorts by a column: by value if every cell is a number, else alphabetically. The selection is lost.

RVirtualTable

sealed class RVirtualTable : UserControl

A read-only table that builds only the visible rows.

Constructors

RVirtualTable

RVirtualTable()

An empty table.

Properties

Rows

List<string[]> Rows { get; }

All the rows, in the order shown when not filtered.

HeaderKey

string HeaderKey { get; set; }

The theme resource of the header background («Bar»).

ColumnCount

int ColumnCount { get; }

How many columns.

SelectedIndex

int SelectedIndex { get; }

The selected row of Rows (−1: none).

SelectedRow

string[]? SelectedRow { get; }

The cells of the selected row (null: none).

ShownCount

int ShownCount { get; }

How many rows are shown (after the filter).

Shown

IReadOnlyList<string[]> Shown { get; }

The rows shown, in order (after sort and filter).

Filter

string Filter { get; set; }

The words searched: only the rows with a cell that contains them (case not counted); the empty text shows every row.

Events

SelectionChanged

event Action<int>? SelectionChanged

When the selection changes, with the row of Rows (−1: none).

Methods

Columns

RVirtualTable Columns(params string[] headers)

The columns; «:R» right, «:C» center at the end of a header. The widths are measured again from the rows already there.

Header

string Header(int column)

The header of a column (without the alignment suffix).

SetWidth

RVirtualTable SetWidth(int column, double width)

Sets the width of a column, dip (the measured one otherwise).

ColumnWidth

double ColumnWidth(int column)

The width of a column, dip.

AddRow

RVirtualTable AddRow(params string[] cells)

Adds a row (missing cells are empty).

AddRows

RVirtualTable AddRows(IEnumerable<string[]> rows)

Adds many rows at once, measuring the widths again.

Clear

void Clear()

Removes every row (the columns stay).

LoadCsv

void LoadCsv(string text, bool headers = true)

A CSV text (RCsv: commas, points, quotes): the first row gives the headers, the columns whose cells are all numbers go to the right. Without headers the columns are named A, B, C...

Select

void Select(int row)

Selects a row of Rows (−1: none) and scrolls to it, if it is shown.

Sort

void Sort(int column, bool descending = false)

Sorts Rows by a column: by value if every cell that is not empty is a number (also «4k7», «1.5p»), else alphabetically.

Text

string Text()

The rows shown, with the headers, as text with tabs (RClipboard.SetText).

RPropertyList

sealed class RPropertyList : UserControl

An editable list of name = value pairs, also from the properties of an object.

Constructors

RPropertyList

RPropertyList()

An empty list.

Properties

Target

object? Target { get; }

The object whose properties are shown (null: pairs added by hand).

Count

int Count { get; }

How many properties.

Events

Changed

event Action<string, string>? Changed

When a value is confirmed and different: name, new value.

Rejected

event Action<string, string>? Rejected

When a value cannot be written into the object (Show): the name and the reason. The box has already gone back to the value of the object.

Methods

Add

RPropertyList Add(string name, string value)

Adds a property with its value.

Show

RPropertyList Show(object target)

Shows the public properties of an object (texts, numbers, yes/no, enums) in place of what is there; the values confirmed are written back into it.

Reload

void Reload()

Reads the values of the object again (it changed elsewhere).

Clear

void Clear()

Removes all the properties (and forgets the object).

Value

string? Value(string name)

The value of a property (null if there is none).

Box

TextBox? Box(string name)

The text box of a property (null if there is none).

Confirm

void Confirm(int i)

Confirms the value of row i, as Enter does: Changed if different from the last confirmed one; with Show, written into the object or refused.

Convert

static object? Convert(string text, Type type)

A text as a value of the type: numbers as RFormat reads them, yes/no in words, enums by name (null if it does not convert).

RTree

sealed class RTree : UserControl

A tree of RTreeNode with selection, search and lazy items.

Constructors

RTree

RTree()

An empty tree, without the search box.

Properties

View

TreeView View { get; }

The TreeView inside, for styles and properties not given here.

Searchable

bool Searchable { get; set; }

Whether the search box above the tree is shown (false).

Roots

IReadOnlyList<RTreeNode> Roots { get; }

The nodes at the top.

Selected

RTreeNode? Selected { get; }

The selected node (null: none).

Filter

string Filter { get; set; }

The words searched: the nodes whose text or value contains them (case not counted) stay, with those above and below; the empty text shows everything. Only the children already known are searched: a loader is not called by the filter.

Found

int Found { get; }

How many nodes matched the last filter.

Events

SelectionChanged

event Action<RTreeNode?>? SelectionChanged

When the selected node changes (null: none).

Opened

event Action<RTreeNode>? Opened

When a node is opened: double click, or Enter on the selection.

Methods

FromJson

static RTree FromJson(string json)

The tree of a JSON text (RTreeNode.FromJson): its members at the top.

FromXml

static RTree FromXml(string xml)

The tree of an XML text (RTreeNode.FromXml): the root element at the top.

Add

RTree Add(params RTreeNode[] nodes)

Adds nodes at the top.

Remove

bool Remove(RTreeNode node)

Removes a node at the top; false if it is not one.

Clear

void Clear()

Removes every node.

LoadJson

void LoadJson(string json)

Shows a JSON text in place of what is there.

LoadXml

void LoadXml(string xml)

Shows an XML text in place of what is there.

LoadNode

void LoadNode(RNode data)

Shows a tree of data in place of what is there: a root without a name (a JSON document) leaves its members at the top, a root with a name (an XML element) is the only node at the top. Each node keeps its RNode in Tag.

Select

void Select(RTreeNode? node)

Selects a node, opening the nodes above it and scrolling to it.

Expand

void Expand(RTreeNode node)

Opens a node, and the nodes above it.

Collapse

void Collapse(RTreeNode node)

Closes a node (its children keep their state).

ExpandAll

void ExpandAll(int levels = 2147483647)

Opens the nodes down to the given depth (1: the roots only). Every loader on the way is called: on a disk, keep the depth small.

CollapseAll

void CollapseAll()

Closes every node.

Find

RTreeNode? Find(string path, string separator = "/")

The node at a path written as RTreeNode.Path writes it, «server/port» or, with «.», «items[2].name» (null if there is none). The children are loaded on the way.

RTreeNode

sealed class RTreeNode

A node of an RTree, with children added or loaded when needed.

Constructors

RTreeNode

RTreeNode(string text, string? value = null)

A node with a text and, if given, a value.

RTreeNode(string text, Func<RTreeNode, IEnumerable<RTreeNode>> loader)

A node whose children are read by the loader the first time they are needed (when it is opened, searched or walked).

Properties

Text

string Text { get; set; }

The text shown.

Value

string? Value { get; set; }

The value, shown dimmed after the text (null: none).

Key

string Key { get; set; }

The segment of the path: the text, unless set.

Tag

object? Tag { get; set; }

Anything the caller wants to keep with the node.

Color

Color? Color { get; set; }

The color of the text (null: the color of the theme).

Item

TreeViewItem? Item { get; }

The item on the screen (null until the node above is opened): for a context menu, a tooltip, a style.

Parent

RTreeNode? Parent { get; }

The node above (null for a root).

Loaded

bool Loaded { get; }

Whether the children are known (added, or already loaded).

HasChildren

bool HasChildren { get; }

Whether the node has children, or may have (not yet loaded).

Children

IReadOnlyList<RTreeNode> Children { get; }

The children, read by the loader the first time.

KnownChildren

IReadOnlyList<RTreeNode> KnownChildren { get; }

The children already known, without loading (empty if not loaded).

Depth

int Depth { get; }

How deep the node is: 0 for a root.

Methods

Add

RTreeNode Add(params RTreeNode[] children)

Adds children at the end.

Remove

bool Remove(RTreeNode child)

Removes a child; false if it is not a child of this node.

Reload

void Reload()

Forgets the loaded children: the loader reads them again (a folder whose files have changed). Nothing for a node without a loader.

Path

string Path(string separator = "/")

The path from the root: the keys joined by the separator, and the keys that begin with «[» (the items of an array) attached without it. Path(".") of a JSON value is «server.port» or «items[2].name», the same keys RSettings reads.

Descendants

IEnumerable<RTreeNode> Descendants()

The node and all the nodes below it, depth first. Only the children already known: a loader is not called (a disk is not read whole).

Child

RTreeNode? Child(string key)

The child with the key (null if none); loads the children.

ToString

string ToString()

The text and the value, as a line.

FromJson

static RTreeNode FromJson(string json, string name = "json")

The tree of a JSON text (RNode.FromJson): objects and arrays are nodes with their members as children (the value shows how many: «{3}», «[12]»), texts, numbers and true/false are leaves with their value. Throws JsonException if the text is not JSON.

FromXml

static RTreeNode FromXml(string xml)

The tree of an XML text (RNode.FromXml): one node for each element, its text as the value, the attributes as the first children with the key «@name». Throws XmlException if the text is not XML.

FromNode

static RTreeNode FromNode(RNode data, string name = "data")

The tree of an RNode already read or built, the RNode kept in Tag of each node. A root without a name takes the given one.

FromFolder

static RTreeNode FromFolder(string path)

A folder whose content is read when the node is opened: the folders first, then the files with their size, both in alphabetical order. The full path is in Tag. A folder that cannot be read shows the error as its only child.

RNode

sealed class RNode

A node of a tree of data, read from JSON or XML and written back.

Constructors

RNode

RNode(RNodeKind kind, string name, string? value = null, bool isText = true)

A node of the given kind; value is the text of a value, attribute or element.

Properties

Kind

RNodeKind Kind { get; }

What the node is.

Name

string Name { get; set; }

The name: the key of an object member, «[i]» in an array, «@name» for an attribute.

Value

string? Value { get; }

The value as text (null for objects, arrays, JSON null, elements without text).

IsText

bool IsText { get; }

Whether a JSON value is a text, written with the quotes (false: number, true, false).

Parent

RNode? Parent { get; }

The node above (null for the root).

Source

object? Source { get; set; }

What the node was read from: the JsonNode, the XElement or the XAttribute (null if built).

Tag

object? Tag { get; set; }

Anything the caller wants to keep with the node.

Children

IReadOnlyList<RNode> Children { get; }

The children, in file order.

Count

int Count { get; }

How many children.

Item

RNode? this[string name] { get; }

The child with the name (null if none): node["server"], node["@port"].

Methods

Object

static RNode Object(string name = "")

A JSON object.

Array

static RNode Array(string name = "")

A JSON array.

Text

static RNode Text(string name, string value)

A JSON text value.

Number

static RNode Number(string name, double value)

A JSON number, with all its digits.

Bool

static RNode Bool(string name, bool value)

A JSON true or false.

Element

static RNode Element(string name, string? text = null)

An XML element, with its text if given.

Attribute

static RNode Attribute(string name, string value)

An XML attribute (the name without «@»).

At

RNode? At(int index)

The child at the position (null if out of range).

Child

RNode? Child(string name)

The child with the name (null if none).

Add

RNode Add(params RNode[] children)

Adds children at the end. In an array they are renamed «[i]» by their position; a child taken from another node leaves it.

Remove

bool Remove(RNode child)

Removes a child; false if it is not a child of this node.

Set

RNode Set(string text)

Changes a value to a text (quoted in JSON).

RNode Set(double number)

Changes a value to a number, with all its digits.

RNode Set(bool flag)

Changes a value to true or false.

Path

string Path(string separator = ".")

The path from the root: the names joined by the separator, the names «[i]» attached without it, the root left out when it has no name (the root of a JSON document). «server.port», «parts[2].value».

Find

RNode? Find(string path, string separator = ".")

The node at a path below this one (null if there is none): Find("server.port"), Find("parts[2].value"), Find("server/@port", "/").

Descendants

IEnumerable<RNode> Descendants()

The node and all the nodes below it, depth first.

GetString

string GetString(string path, string def, string separator = ".")

The text at the path (the default if missing or without a value).

GetInt

int GetInt(string path, int def, string separator = ".")

The integer at the path (the default if missing or not an integer).

GetDouble

double GetDouble(string path, double def, string separator = ".")

The real number at the path, written with the point (the default otherwise).

GetBool

bool GetBool(string path, bool def, string separator = ".")

The yes/no at the path: true, yes, on, 1 and false, no, off, 0 (the default otherwise).

GetList

List<string> GetList(string path, string separator = ".")

The values of the children at the path (empty if missing): the items of an array.

ToString

string ToString()

The name and the value, as a line.

Load

static RNode Load(string file)

A file read whole: XML for «.xml», JSON for every other extension. Throws JsonException or XmlException if the text is not valid.

FromJson

static RNode FromJson(string json)

The tree of a JSON text, with a root without a name. Comments and commas before a bracket are accepted. Throws JsonException.

static RNode FromJson(JsonNode? json, string name)

The tree of a JSON node already read.

FromXml

static RNode FromXml(string xml)

The tree of an XML text: elements with the attributes «@name» as the first children and their text as the value. Throws XmlException.

static RNode FromXml(XElement e)

The tree of an element already read.

Save

void Save(string file)

Writes the file: XML if the node is an element, JSON otherwise (a temporary file, then renamed).

ToJson

string ToJson()

The JSON text of the node, indented, with the accents as they are.

ToJsonNode

JsonNode? ToJsonNode()

The node as a JsonNode. An XML element becomes an object: the attributes as «@name» members, the text as «#text», the elements by name (an array when the name repeats).

ToXml

XElement ToXml()

The node as an XElement. A JSON object or array becomes an element named as the node («root» for the root), its members elements, the items of an array elements «item».

RNodeKind

enum RNodeKind

What an RNode is: a JSON object, array or value, an XML element or attribute.

Values

Object

Object = 0

A JSON object: named children.

Array

Array = 1

A JSON array: children named «[0]», «[1]»...

Value

Value = 2

A JSON value: text, number, true, false or null (Value null).

Element

Element = 3

An XML element: attributes first, then elements; Value is its text.

Attribute

Attribute = 4

An XML attribute, named «@name».

RDialog

static class RDialog

Modal message boxes, each in one awaited call.

Properties

Ok

static string Ok { get; set; }

The button that accepts a message («OK»).

Cancel

static string Cancel { get; set; }

The button that gives up («Cancel»).

InfoTitle

static string InfoTitle { get; set; }

The title of Info («Information»).

WarningTitle

static string WarningTitle { get; set; }

The title of Warning («Warning»).

ErrorTitle

static string ErrorTitle { get; set; }

The title of Error («Error»).

ConfirmTitle

static string ConfirmTitle { get; set; }

The title of Confirm («Confirm»).

InputTitle

static string InputTitle { get; set; }

The title of Ask («Input»).

Details

static string Details { get; set; }

The header of the details of an exception («Details»).

Events

Opening

static event Action<RDialogBox>? Opening

When a dialog is about to open, with its window: for the tests, for a log of what the user was asked, or to change it before it shows.

Methods

Info

static Task Info(Control owner, string text, string? title = null)

A message with «OK».

Warning

static Task Warning(Control owner, string text, string? title = null)

A warning with «OK».

Error

static Task Error(Control owner, string text, Exception? e = null, string? title = null)

An error with «OK». With an exception, its message follows the text and the whole exception is under «Details», to copy; the error is also written in the log (RLog.Error), so it is not lost when the user closes the box.

Confirm

static Task<bool> Confirm(Control owner, string question, string? yes = null, string? title = null)

A question with «Cancel» and the button that confirms (yes, «OK» if not given): true only if that button is pressed.

Ask

static Task<string?> Ask(Control owner, string question, string initial = "", string? title = null)

A text to ask, in a box already filled with initial and selected: the text written, or null if the user gives up.

Choose

static Task<int> Choose(Control owner, RDialogKind kind, string title, string text, params string[] buttons)

A choice among buttons, in the order given (the last one is Enter): the index of the button pressed, −1 for Esc or the close button.

Show

static Task<int> Show(Control owner, RDialogBox box)

Opens a dialog built by the caller over the window of owner: the answer.

RDialogKind

enum RDialogKind

What a dialog says: it chooses the sign and its color.

Values

Info

Info = 0

Something done or to know: «i» in blue.

Warning

Warning = 1

Something that may go wrong: «!» in orange.

Error

Error = 2

Something that went wrong: «×» in red.

Question

Question = 3

A question: «?» in blue.

RDialogBox

sealed class RDialogBox : Window

The window of RDialog: sign, text, an optional control under the text, buttons on the right. Built by RDialog; build it directly to put something else under the text, then RDialog.Show.

Constructors

RDialogBox

RDialogBox(RDialogKind kind, string title, string text, Control? extra, params string[] buttons)

A dialog of the kind, with a title, a text, a control under it (or null) and the buttons.

Properties

Answer

int Answer { get; }

The index of the button pressed (−1: none, Esc, closed).

Input

TextBox? Input { get; set; }

The text box of Ask (null in the others): it gets the focus.

Body

Control Body { get; }

What the window shows, sign, text and buttons (for a figure).

Buttons

IReadOnlyList<Button> Buttons { get; }

The buttons, in the order given.

Methods

Pick

void Pick(int index)

Presses a button, as a click does: the dialog closes with its index.

RFiles

static class RFiles

File and folder pickers that answer with a path; text files read and written whole.

Properties

LastFolder

static string? LastFolder { get; set; }

The folder where the next picker opens (the folder of the last file chosen).

Methods

OpenAsync

static Task<string?> OpenAsync(Control owner, string title, params string[] types)

One file to open (null if none chosen); types as «name|*.a;*.b».

OpenManyAsync

static Task<List<string>> OpenManyAsync(Control owner, string title, params string[] types)

Several files to open (empty if none chosen).

SaveAsync

static Task<string?> SaveAsync(Control owner, string title, string name, params string[] types)

The file to save (null if the user gives up), proposing name. The picker asks before replacing a file; the extension of the first type is added when the user writes none.

FolderAsync

static Task<string?> FolderAsync(Control owner, string title)

A folder (null if none chosen).

Types

static List<FilePickerFileType> Types(params string[] types)

The types of a picker from texts «name|*.a;*.b»: «CSV|*.csv», «Images|*.png;*.jpg». A text without «|» is a pattern alone, named after itself.

ReadText

static string ReadText(string path)

A text file read whole (UTF-8, or the encoding of its BOM).

WriteText

static void WriteText(string path, string text)

A text file written whole in UTF-8 without BOM, through a temporary file then renamed: a crash halfway leaves the old file. The folder is created if missing.

RClipboard

static class RClipboard

Copy and paste of text, tables, files and images.

Methods

SetText

static Task SetText(Control owner, string text)

Puts a text in the clipboard.

GetText

static Task<string?> GetText(Control owner)

The text in the clipboard (null if there is none).

SetTable

static Task SetTable(Control owner, IEnumerable<string[]> rows)

Puts rows of cells in the clipboard as a spreadsheet copies them: tabs between the cells, a line for each row.

GetTable

static Task<List<string[]>> GetTable(Control owner)

The rows of cells in the clipboard (empty if there is no text).

Tsv

static string Tsv(IEnumerable<string[]> rows)

Rows of cells as text with tabs and line breaks. Tabs and breaks inside a cell become spaces: a cell never splits.

Cells

static List<string[]> Cells(string? text)

The rows of a text copied from a spreadsheet: lines split at the tabs. The empty last line that sheets add is dropped; null gives no rows.

GetFiles

static Task<List<string>> GetFiles(Control owner)

The files in the clipboard, as paths (empty if none, or none on the disk).

SetFiles

static Task SetFiles(Control owner, IEnumerable<string> paths)

Puts files in the clipboard, to paste in a folder of the system; the paths that do not exist are skipped.

SetImage

static Task SetImage(Control owner, Bitmap image)

Puts an image in the clipboard (a chart: RImage.Render).

GetImage

static Task<Bitmap?> GetImage(Control owner)

The image in the clipboard (null if there is none).

Clear

static Task Clear(Control owner)

Empties the clipboard.

RDrop

sealed class RDrop

A control that accepts dropped files or texts.

Methods

Files

static RDrop Files(Control target, Action<List<string>> dropped, params string[] patterns)

The files dropped on the control go to the method, as paths: only those that match one of the patterns («*.csv»; none: all).

Text

static RDrop Text(Control target, Action<string> dropped)

A text dropped on the control (from an editor, a browser) goes to the method.

Accepts

bool Accepts(string path)

Whether a file name matches the patterns (true if there are none).

Deliver

bool Deliver(IEnumerable<string> paths)

Gives paths to the method as a drop would: those that match, and only if one does (for the tests, or a «open» that reuses the drop).

Stop

void Stop()

The control no longer accepts drops.

RChart

class RChart : Control

A line chart with markers.

Constructors

RChart

RChart()

An empty chart.

Properties

MinX

double MinX { get; set; }

The lowest abscissa shown (NaN: from the data).

MaxX

double MaxX { get; set; }

The highest abscissa shown (NaN: from the data).

TimeAxis

bool TimeAxis { get; set; }

Whether the abscissas are times, seconds as RTime.X writes them: the divisions fall on round times, the labels are hours or dates.

Zoomed

bool Zoomed { get; }

Whether the user has zoomed or moved the view (ResetView undoes it).

RangeX

ValueTuple<double, double> RangeX { get; }

The abscissas shown in the last drawing.

RangeY

ValueTuple<double, double> RangeY { get; }

The ordinates of the left axis shown in the last drawing.

Series

List<RSeries> Series { get; }

The curves.

Limits

List<RLimit> Limits { get; }

The limit lines.

Markers

List<double> Markers { get; }

The abscissas of the markers.

TitleY

string TitleY { get; set; }

The title of the left axis.

TitleY2

string TitleY2 { get; set; }

The title of the right axis ("" if no curve uses it).

UnitX

string UnitX { get; set; }

The unit of the abscissas, written with the SI prefix.

LogX

bool LogX { get; set; }

Whether the abscissa is logarithmic.

MinY

double MinY { get; set; }

The lowest value shown on the left axis (NaN: from the data).

MaxY

double MaxY { get; set; }

The highest value shown on the left axis (NaN: from the data).

BackgroundKey

string BackgroundKey { get; set; }

The theme resource of the background.

GridKey

string GridKey { get; set; }

The theme resource of the grid.

InkKey

string InkKey { get; set; }

The theme resource of the texts and the frame.

TextSize

double TextSize { get; set; }

The size of the texts.

FormatX

Func<double, string>? FormatX { get; set; }

How an abscissa is written (null: RFormat.Si with UnitX). A method group, for example chart.FormatX = Degrees;.

Culture

CultureInfo Culture { get; set; }

How the numbers of the axes and of the markers are written: the point (invariant, the default), as RTable, RCsv and RFormat write them; set CultureInfo.CurrentCulture for the comma of the computer.

PlotArea

Rect PlotArea { get; }

The area of the curves in the last drawing, pixels.

Events

ViewChanged

event Action? ViewChanged

After the wheel or a drag has changed the view.

MarkersChanged

event Action? MarkersChanged

After a click has changed the markers.

Methods

SetView

void SetView(double x0, double x1, double y0 = NaN, double y1 = NaN)

Shows the abscissas from x0 to x1 (and, if given, the ordinates from y0 to y1).

ResetView

void ResetView()

Shows all the data again (and MinX, MaxX, MinY, MaxY if set).

ZoomX

void ZoomX(double x, double factor)

Zooms the abscissa by a factor around x (2: half the span); on a logarithmic axis around x in decades.

ZoomY

void ZoomY(double y, double factor)

Zooms the left ordinate by a factor around y.

ValueY

double ValueY(Point p)

The ordinate of the left axis under a pixel.

Refresh

void Refresh()

Redraws after a change of the curves.

PixelX

double PixelX(double x)

The pixel of an abscissa (after the first drawing).

PixelY

double PixelY(double y)

The pixel of an ordinate of the left axis.

ValueX

double ValueX(Point p)

The abscissa under a pixel (NaN outside the curves).

Render

void Render(DrawingContext ctx)

Draws background, grid, curves, limits, markers, legend.

RSeries

sealed class RSeries

A curve of an RChart.

Constructors

RSeries

RSeries(string name, double[] x, double[] y, int color = 0)

A curve; the color is the i-th of RColor.Palette.

Properties

Name

string Name { get; }

The name, in the legend ("" keeps it out of the legend).

X

double[] X { get; }

The abscissas, in any order (increasing for the markers).

Y

double[] Y { get; }

The ordinates (NaN leaves a hole in the curve).

Sorted

bool Sorted { get; }

Whether the abscissas never decrease: then the markers read the curve.

Brush

IBrush Brush { get; set; }

The color.

Dashed

bool Dashed { get; set; }

Whether it is dashed (a measurement, a limit).

RightAxis

bool RightAxis { get; set; }

Whether it uses the right axis instead of the left one.

Thickness

double Thickness { get; set; }

The line thickness, pixels.

Style

RSeriesStyle Style { get; set; }

Line, points or both (Line).

PointSize

double PointSize { get; set; }

The diameter of the points, pixels (5).

Methods

At

double At(double x)

The ordinate at x, interpolated between the two nearest samples (NaN outside the curve, or if the abscissas are not sorted).

With

RSeries With(double[] x, double[] y)

A copy with the same name, color and look, and other points.

RSeriesStyle

enum RSeriesStyle

How a curve of RChart is drawn.

Values

Line

Line = 0

A line through the points.

Points

Points = 1

Only the points (a scatter plot).

LineAndPoints

LineAndPoints = 2

The line and the points on it.

RLiveSeries

sealed class RLiveSeries

A curve of RChart that grows while the data arrive, from any thread.

Constructors

RLiveSeries

RLiveSeries(RChart chart, string name, int color = 0)

A live curve in the chart, with its name and the i-th color of RColor.Palette.

Properties

Window

double Window { get; set; }

The span of abscissa kept and shown, from the last point back (NaN: all).

MaxPoints

int MaxPoints { get; set; }

The most points kept: the oldest go (100 000).

Series

RSeries Series { get; }

The curve as it is now in the chart (a new RSeries after each batch).

Count

int Count { get; }

How many points are kept now (on the UI thread).

Style

RSeriesStyle Style { get; set; }

Line, points or both (set on the UI thread).

Methods

Add

void Add(double x, double y)

Adds a point, from any thread; the abscissas must grow.

void Add(DateTime t, double y)

Adds a point at a time (RTime.X), from any thread.

Clear

void Clear()

Removes every point (on the UI thread).

Drain

void Drain()

Takes the points waiting now, on the UI thread: what the Post does, callable directly by a test or a timer.

RLimit

sealed class RLimit

A limit drawn on an RChart: a thick horizontal segment from X1 to X2 at the height Y (the goals of an optimizer, a mask of a standard).

Constructors

RLimit

RLimit(double x1, double x2, double y, IBrush brush)

A limit from x1 to x2 at the height y.

Properties

X1

double X1 { get; }

Where the segment starts.

X2

double X2 { get; }

Where the segment ends.

Y

double Y { get; }

The height.

Brush

IBrush Brush { get; set; }

The color (green when met, red when not, for example).

Label

string Label { get; set; }

A short text written over the segment ("" for none).

RTicks

static class RTicks

The divisions of a chart axis.

Methods

Step

static double Step(double a, double b, int n)

The round step (1, 2 or 5 times a power of ten) that gives about n divisions between a and b.

Expand

static ValueTuple<double, double> Expand(double a, double b, int n)

The range widened to whole steps on both sides.

Linear

static List<double> Linear(double a, double b, int n)

The round divisions between a and b, ends included.

Log

static List<double> Log(double a, double b)

The divisions of a logarithmic axis between a and b (both positive): 1, 2 and 5 of each decade.

RTime

static class RTime

Times as abscissas of RChart, with round divisions.

Methods

X

static double X(DateTime t)

A date as an abscissa: seconds from the year 1.

Date

static DateTime Date(double x)

An abscissa as a date (the kind is Unspecified, as the date given).

Step

static double Step(double x0, double x1, int n)

The round step for about n divisions between x0 and x1, seconds.

Ticks

static List<double> Ticks(double x0, double x1, double step)

The divisions between x0 and x1 at the step: multiples of the step from midnight, so that hours fall on whole hours of the day.

Label

static string Label(double x, double step, CultureInfo culture)

The label of a division: «HH:mm:ss» below a minute, «HH:mm» below a day, the day «yyyy-MM-dd» at midnight or for steps of days; the tenths and hundredths for steps below a second.

Long

static string Long(double x, CultureInfo culture)

The whole date and time, for a marker: «yyyy-MM-dd HH:mm:ss».

RSmithChart

sealed class RSmithChart : Control

The interactive Smith chart.

Constructors

RSmithChart

RSmithChart()

The empty chart, with the impedance grid.

Properties

Z0

double Z0 { get; set; }

The normalization impedance, ohm (50).

ShowImpedance

bool ShowImpedance { get; set; }

Whether the impedance grid is drawn (true).

ShowAdmittance

bool ShowAdmittance { get; set; }

Whether the admittance grid is drawn (false).

MaxGamma

double MaxGamma { get; set; }

The largest |Γ| shown: 1 is the normal chart, 2 or more the expanded chart, where the resistance is negative outside |Γ| = 1.

Series

List<RComplexSeries> Series { get; }

The curves (one Γ per frequency).

Markers

List<RSmithMarker> Markers { get; }

The points.

Circles

List<RSmithCircle> Circles { get; }

The circles (VSWR, Q, stability, gain, noise).

MarkerValues

bool MarkerValues { get; set; }

Whether each marker writes Z and VSWR under its label (true).

ShowReading

bool ShowReading { get; set; }

Whether the reading under the pointer is written (true).

Zoom

double Zoom { get; }

The magnification of the view (1: the whole chart).

ViewCenter

Complex ViewCenter { get; }

The Γ at the center of the view (0 for the whole chart).

Culture

CultureInfo Culture { get; set; }

How the numbers are written (invariant: the point).

BackgroundKey

string BackgroundKey { get; set; }

The theme resource of the background.

GridKey

string GridKey { get; set; }

The theme resource of the grid.

InkKey

string InkKey { get; set; }

The theme resource of the texts and of the outer circle.

TextSize

double TextSize { get; set; }

The size of the texts.

Under

Complex? Under { get; }

The Γ under the pointer, or null.

Radius

double Radius { get; }

The radius of the circle |Γ| = 1 in pixels, with the zoom.

Events

MarkerMoved

event Action<RSmithMarker>? MarkerMoved

A draggable marker has been moved.

Methods

PixelOf

Point PixelOf(Complex gamma)

The point of the control of a reflection coefficient.

GammaAt

Complex GammaAt(Point p)

The reflection coefficient of a point of the control.

ZoomAt

void ZoomAt(Point p, double factor)

Zooms by a factor keeping the Γ at the given point where it is (the wheel does it at the pointer); the zoom stays from 1 to 50.

ResetView

void ResetView()

Shows the whole chart again.

SavePng

void SavePng(string path, double widthCm = 12, double dpi = 300)

Saves the chart as PNG, square, the given centimetres wide at the given dpi (RImage); the chart is then laid out again on the screen.

Render

void Render(DrawingContext ctx)

Draws background, grids, circles, curves, markers, legend and reading.

Move

void Move(RSmithMarker m, Complex gamma)

Brings a marker to the given Γ (inside |Γ| = MaxGamma) and tells MarkerMoved: what the mouse does, usable from code and tests.

RSmithMarker

sealed class RSmithMarker

A point of an RSmithChart, with its label and, if given, its frequency.

Constructors

RSmithMarker

RSmithMarker(string label, Complex gamma, IBrush brush, bool draggable = false)

A point with label and color.

Properties

Label

string Label { get; set; }

The label written next to the point.

Gamma

Complex Gamma { get; set; }

The reflection coefficient.

Brush

IBrush Brush { get; set; }

The color.

Draggable

bool Draggable { get; set; }

Whether the mouse can drag it (RSmithChart.MarkerMoved tells).

Frequency

double Frequency { get; set; }

The frequency of the point, Hz (NaN: not written).

RSmithCircle

sealed class RSmithCircle

A circle of an RSmithChart (VSWR, Q, stability, gain, noise), with name and color.

Constructors

RSmithCircle

RSmithCircle(string name, RCircle circle, IBrush brush)

A circle with name and color.

Properties

Name

string Name { get; }

The name written at the top of the circle.

Circle

RCircle Circle { get; }

The circle in the Γ plane.

Brush

IBrush Brush { get; }

The color.

Dashed

bool Dashed { get; set; }

Whether it is dashed.

Fill

IBrush? Fill { get; set; }

A brush that fills the circle (null: none): the unstable region of a stability circle, half transparent.

RComplexSeries

sealed class RComplexSeries

A curve of complex numbers (one per frequency) for RSmithChart and RPolarChart.

Constructors

RComplexSeries

RComplexSeries(string name, Complex[] points, double[]? frequencies = null, int color = 0)

A curve with its frequencies (or none); the color is the i-th of RColor.Palette.

Properties

Name

string Name { get; }

The name, in the legend ("" keeps it out).

Points

Complex[] Points { get; }

The points: Γ on the Smith chart, any complex on the polar one.

Frequencies

double[] Frequencies { get; }

The frequencies of the points, Hz (empty: none written).

Brush

IBrush Brush { get; set; }

The color.

Dashed

bool Dashed { get; set; }

Whether it is dashed (a measurement).

Thickness

double Thickness { get; set; }

The line thickness, pixels.

Methods

Pattern

static RComplexSeries Pattern(string name, double[] degrees, double[] values, bool decibels, int color = 0)

A radiation pattern: a value for each angle in degrees, in dB if decibels (as the gain of an antenna), linear otherwise. The polar chart draws it at its angle.

RSmithMath

static class RSmithMath

Conversions of the reflection coefficient and the circles of the Smith chart.

Methods

Gamma

static Complex Gamma(Complex z, double z0 = 50)

The reflection coefficient of an impedance on Z0.

Impedance

static Complex Impedance(Complex gamma, double z0 = 50)

The impedance of a reflection coefficient, ohm (infinite at Γ = 1).

Admittance

static Complex Admittance(Complex gamma, double z0 = 50)

The admittance of a reflection coefficient, siemens.

Vswr

static double Vswr(Complex gamma)

The voltage standing wave ratio (infinite for |Γ| ≥ 1).

static RCircle Vswr(double vswr)

Constant voltage standing wave ratio.

ReturnLoss

static double ReturnLoss(Complex gamma)

The return loss, dB (positive; infinite for Γ = 0).

Degrees

static double Degrees(Complex z)

The angle of a complex number, degrees from −180 to 180.

Polar

static Complex Polar(double magnitude, double degrees)

A complex number from magnitude and angle in degrees.

Resistance

static RCircle Resistance(double r)

Normalized resistance r constant.

Reactance

static RCircle Reactance(double x)

Normalized reactance x constant (x ≠ 0).

Conductance

static RCircle Conductance(double g)

Normalized conductance g constant.

Susceptance

static RCircle Susceptance(double b)

Normalized susceptance b constant (b ≠ 0).

Q

static ValueTuple<RCircle, RCircle> Q(double q)

Constant Q, two circles: the arc of the positive reactances (upper half of the chart) has its center in −j/Q, the other in +j/Q.

OutputStability

static RCircle OutputStability(Complex s11, Complex s12, Complex s21, Complex s22)

The output stability circle: the loads ΓL where |Γin| = 1. Which side is stable: see OutputStableInside.

InputStability

static RCircle InputStability(Complex s11, Complex s12, Complex s21, Complex s22)

The input stability circle: the sources ΓS where |Γout| = 1.

OutputStableInside

static bool OutputStableInside(Complex s11, Complex s12, Complex s21, Complex s22)

Whether the stable loads are inside the output stability circle: the center of the chart (ΓL = 0, |Γin| = |S11|) is stable when |S11| < 1, and it tells on which side it lies.

InputStableInside

static bool InputStableInside(Complex s11, Complex s12, Complex s21, Complex s22)

Whether the stable sources are inside the input stability circle.

Rollett

static ValueTuple<double, double> Rollett(Complex s11, Complex s12, Complex s21, Complex s22)

The Rollett factor K and |Δ|: unconditionally stable when K > 1 and |Δ| < 1.

UnilateralGain

static RCircle UnilateralGain(Complex s, double gainDb)

A constant gain circle of a unilateral amplifier (S12 = 0) on one side: s is S11 for the source, S22 for the load; gainDb is the gain of that side, which at most is 1/(1 − |s|²).

Noise

static RCircle Noise(double fDb, double fminDb, double rn, Complex gammaOpt, double z0 = 50)

The constant noise figure circle: the sources with noise figure fDb, from the noise parameters Fmin (dB), Rn (ohm) and Γopt.

RCircle

sealed class RCircle

A circle of the plane of the reflection coefficient.

Constructors

RCircle

RCircle(Complex center, double radius)

A circle with its center and radius.

Properties

Center

Complex Center { get; }

The center.

Radius

double Radius { get; }

The radius.

Methods

Contains

bool Contains(Complex gamma)

Whether a point is inside the circle.

ToString

string ToString()

The center and the radius, as a line.

RPolarChart

sealed class RPolarChart : Control

The polar chart of complex curves and radiation patterns.

Constructors

RPolarChart

RPolarChart()

The empty chart.

Properties

Series

List<RComplexSeries> Series { get; }

The curves.

Max

double Max { get; set; }

The magnitude (or dB) at the edge; NaN: from the data, rounded up.

Decibels

bool Decibels { get; set; }

Whether the distance is 20·log10|z| (radiation patterns).

Range

double Range { get; set; }

With Decibels, how many dB from the edge to the center (40).

ZeroAngle

double ZeroAngle { get; set; }

Where the angle zero is, degrees counterclockwise from the right (0).

Clockwise

bool Clockwise { get; set; }

Whether the angles grow clockwise (false: as in the complex plane).

AngleStep

double AngleStep { get; set; }

The step of the rays, degrees (30).

Culture

CultureInfo Culture { get; set; }

How the numbers are written (invariant: the point).

BackgroundKey

string BackgroundKey { get; set; }

The theme resource of the background.

GridKey

string GridKey { get; set; }

The theme resource of the grid.

InkKey

string InkKey { get; set; }

The theme resource of the texts and of the edge.

TextSize

double TextSize { get; set; }

The size of the texts.

Edge

double Edge { get; }

The value at the edge used in the last drawing (magnitude, or dB).

Circle

ValueTuple<double, double, double> Circle { get; }

The center and the radius of the edge, pixels.

Methods

PixelOf

Point PixelOf(Complex z)

The point of the control of a complex number.

SavePng

void SavePng(string path, double widthCm = 12, double dpi = 300)

Saves the chart as PNG, square, the given centimetres wide at the given dpi (RImage).

Render

void Render(DrawingContext ctx)

Draws the circles of the magnitude, the rays of the angle, the curves.

RBarChart

sealed class RBarChart : Control

A bar chart drawn by hand.

Constructors

RBarChart

RBarChart()

An empty chart.

Properties

Categories

List<string> Categories { get; }

The names under the groups of bars.

Series

List<RBarSeries> Series { get; }

The series, one color each.

Stacked

bool Stacked { get; set; }

Whether the bars of a category stand one on the other.

ShowValues

bool ShowValues { get; set; }

Whether each bar writes its value (true).

TitleY

string TitleY { get; set; }

The title of the axis, above it.

Unit

string Unit { get; set; }

The unit after the values on the bars (with the SI prefix).

Fill

double Fill { get; set; }

The part of a category taken by its bars (0.75).

Culture

CultureInfo Culture { get; set; }

How the numbers are written (invariant: the point).

BackgroundKey

string BackgroundKey { get; set; }

The theme resource of the background.

GridKey

string GridKey { get; set; }

The theme resource of the grid.

InkKey

string InkKey { get; set; }

The theme resource of the texts and of the axis.

TextSize

double TextSize { get; set; }

The size of the texts.

PlotArea

Rect PlotArea { get; }

The area of the bars in the last drawing.

Methods

BarRect

Rect BarRect(int series, int category)

The rectangle of a bar in the last drawing (empty if there is none).

SavePng

void SavePng(string path, double widthCm = 14, double heightCm = 8, double dpi = 300)

Saves the chart as PNG, the given centimetres wide and high at the given dpi (RImage).

Render

void Render(DrawingContext ctx)

Draws grid, axis, bars, values, categories and legend.

RBarSeries

sealed class RBarSeries

A set of bars of one color, a value per category.

Constructors

RBarSeries

RBarSeries(string name, double[] values, int color = 0)

The values with a name; the color is the i-th of RColor.Palette.

Properties

Name

string Name { get; }

The name, in the legend.

Values

double[] Values { get; }

A value per category (NaN: no bar).

Brush

IBrush Brush { get; set; }

The color.

RHeatMap

sealed class RHeatMap : Control

A color map of a matrix of values, with axes and color bar.

Constructors

RHeatMap

RHeatMap()

An empty map.

Properties

Scale

RColorScale Scale { get; set; }

The color scale (Viridis).

Min

double Min { get; set; }

The value of the first color (NaN: the least of the data).

Max

double Max { get; set; }

The value of the last color (NaN: the largest of the data).

Smooth

bool Smooth { get; set; }

Whether the colors are blended between the values (false: squares).

TitleX

string TitleX { get; set; }

The title of the horizontal axis.

TitleY

string TitleY { get; set; }

The title of the vertical axis.

Unit

string Unit { get; set; }

The unit of the values, on the color bar.

Culture

CultureInfo Culture { get; set; }

How the numbers are written (invariant: the point).

BackgroundKey

string BackgroundKey { get; set; }

The theme resource of the background.

GridKey

string GridKey { get; set; }

The theme resource of the grid.

InkKey

string InkKey { get; set; }

The theme resource of the texts and the frame.

TextSize

double TextSize { get; set; }

The size of the texts.

PlotArea

Rect PlotArea { get; }

The area of the map in the last drawing.

Size

ValueTuple<int, int> Size { get; }

How many rows and columns.

Methods

SetValues

void SetValues(double[,] values, double x0, double x1, double y0, double y1)

The values [row, column], the rows from y0 at the bottom to y1 at the top, the columns from x0 to x1 (the edges of the matrix).

Limits

ValueTuple<double, double> Limits()

The ends of the scale: Min and Max, or those of the data.

ValueAt

double ValueAt(double x, double y)

The value at a point of the plane (NaN outside the matrix).

ColorOf

static Color ColorOf(double t, RColorScale scale)

The color of a fraction from 0 to 1 of a scale.

SavePng

void SavePng(string path, double widthCm = 14, double heightCm = 9, double dpi = 300)

Saves the map as PNG, the given centimetres wide and high at the given dpi (RImage).

Render

void Render(DrawingContext ctx)

Draws the map, the axes, the color bar and the value under the pointer.

RColorScale

enum RColorScale

The color scales of RHeatMap.

Values

Viridis

Viridis = 0

From dark blue through green to yellow: readable, also in gray.

Heat

Heat = 1

From black through red and yellow to white: heat.

BlueRed

BlueRed = 2

Blue, white, red: values around a middle (an error, a phase).

Gray

Gray = 3

From white to black.

RImage

static class RImage

Controls drawn into bitmaps.

Methods

Render

static RenderTargetBitmap Render(Control c, double width, double height, double dpi = 96)

The control drawn at width × height dip and the given dpi (96 for the screen, 300 for print).

SavePng

static RenderTargetBitmap SavePng(Control c, string path, double width, double height, double dpi = 96)

The control saved as PNG; returns the bitmap.

SetDpi

static void SetDpi(string path, double dpi)

Writes the resolution into a PNG file (its pHYs chunk, in pixels per metre), replacing the one that is there: page layout programs then place the figure at its true size.

Dpi

static double Dpi(string path)

The resolution written in a PNG (NaN if it has no pHYs in metres).

Dip

static double Dip(double cm)

The width in dip of a figure that prints cm centimetres wide.

RFormat

static class RFormat

Numbers with SI prefixes, written and read back.

Methods

Si

static string Si(double value, string unit = "", int digits = 4, CultureInfo? culture = null)

The number with the SI prefix that leaves 1 to 999 before the point, digits significant digits at most, and the unit after a space (none if unit is empty and the prefix is empty).

Round

static double Round(double value, int digits)

The number rounded to the given significant digits.

Parse

static double Parse(string text, string unit = "")

Reads «1.5p», «4k7», «10 MHz» (the unit after the prefix is ignored when unit says what it is), «2.2e-3», «5%».

TryParse

static bool TryParse(string text, double value, string unit = "")

Parse without exceptions: false if the text is not a number. A text that does not begin as a number («C1», «ceramic») is refused at once, so that a column of a hundred thousand names costs no exception (sorting RVirtualTable asks this of every cell).

RColor

static class RColor

Color conversions and the palette of the series.

Fields

Palette

static readonly Color[] Palette

The colors of the series, in order.

Methods

Mix

static Color Mix(Color a, Color b, double t)

The color between a and b: 0 gives a, 1 gives b (opacity included).

Lighten

static Color Lighten(Color c, double amount)

The color mixed with white by the given amount (0-1).

Darken

static Color Darken(Color c, double amount)

The color mixed with black by the given amount (0-1).

WithOpacity

static Color WithOpacity(Color c, double opacity)

The same color with the given opacity (0-1).

Hex

static string Hex(Color c)

The color as HTML text: «#1a7fb5», or «#801a7fb5».

Luminance

static double Luminance(Color c)

The relative luminance (0 black, 1 white) of WCAG 2: whether a text on this color should be dark or light.

Series

static IBrush Series(int i)

The brush of the i-th series (the palette repeats).

RCsv

static class RCsv

CSV text written and read back.

Methods

Write

static string Write(IReadOnlyList<string> headers, params double[][] columns)

The CSV of the given columns, all of the same length, with the header on the first line.

static string Write(string headerX, IReadOnlyList<RSeries> series)

The CSV of the curves of a chart: the abscissas of the first one, then one column for each curve, interpolated where its abscissas are different.

static string Write(RTable table)

The CSV of a table: its headers and its rows as they are.

Read

static List<string[]> Read(string text)

The rows of a CSV text, cells unquoted.

RLog

static class RLog

The log of the application: one for the whole program.

Properties

Level

static RLogLevel Level { get; set; }

The least important level written (Info: no Debug, no Trace).

Console

static bool Console { get; set; }

Whether the lines go also to the console.

Colors

static bool Colors { get; set; }

Whether the console lines are colored: the time dimmed, the level and the text in their colors (true).

TrueColor

static bool TrueColor { get; set; }

Whether the console shows the exact colors (ANSI 24 bit) instead of the nearest of its 16: true by itself in Windows Terminal and in the terminals that set COLORTERM=truecolor.

File

static string File { get; }

The log file ("" for none).

MaxBytes

static long MaxBytes { get; set; }

The size beyond which the file rotates, bytes (10 MB).

MaxFiles

static int MaxFiles { get; set; }

How many files are kept, the current one included (5).

RecentLines

static int RecentLines { get; set; }

How many lines Recent keeps (2000).

Running

static bool Running { get; }

Whether the log has been started and not stopped.

Events

Written

static event Action<RLogEntry>? Written

Every line written, on the thread of the log (not the UI thread: a window moves it with the Dispatcher, as RLogView does).

Methods

Start

static void Start(string app, string version, string? file = null)

Starts the log: the thread that writes, the file (created with its folder; null or "" for none) and the first line with name, version, computer, operating system, .NET and process id.

StartLine

static string StartLine(string app, string version)

The line that opens every run of a program in the log.

Stop

static void Stop()

Writes what is left in the queue, then closes the file.

Flush

static void Flush(int timeoutMs = 5000)

Waits until every line logged so far is written (tests, before a crash dump).

CatchUnhandled

static void CatchUnhandled()

Also logs the exceptions nobody catches: those of any thread (AppDomain) and those of tasks whose result nobody reads.

Error

static void Error(string text)

A line of level Error.

static void Error(string text, Exception e)

A line of level Error with the exception and its stack.

Warning

static void Warning(string text)

A line of level Warning.

Info

static void Info(string text)

A line of level Info.

static void Info(string text, Color color)

A line of level Info in a color of its own (a phase, a device, a result).

static void Info(string text, string color)

A line of level Info in an HTML color: «#2b8a3e».

Debug

static void Debug(string text)

A line of level Debug.

static void Debug(string text, Color color)

A line of level Debug in a color of its own.

Trace

static void Trace(string text)

A line of level Trace.

static void Trace(string text, Color color)

A line of level Trace in a color of its own.

Enabled

static bool Enabled(RLogLevel level)

Whether a line of this level would be written (to skip building costly texts).

Add

static void Add(RLogLevel level, string text, Color? color = null)

A line of the given level. Before Start, or after Stop, the line goes only to Recent and to the debugger output: nothing is lost silently.

Recent

static RLogEntry[] Recent()

The last lines (at most RecentLines), oldest first.

ClearRecent

static void ClearRecent()

Forgets the lines kept in memory (the file stays).

Nearest

static ConsoleColor Nearest(Color c)

The console color nearest to an RGB color (for consoles without 24 bit colors).

Numbered

static string Numbered(string file, int n)

The name of the n-th old file: «log/app.log», 2 → «log/app.2.log».

RLogLevel

enum RLogLevel

How important a log line is, from the most to the least.

Values

Error

Error = 0

Something failed: the user lost an operation.

Warning

Warning = 1

Something unexpected that the program could handle.

Info

Info = 2

What the program does: start, files opened, connections.

Debug

Debug = 3

Details for whoever looks for a defect.

Trace

Trace = 4

Everything, values included: only while debugging.

RLogEntry

sealed class RLogEntry

One line of the log.

Constructors

RLogEntry

RLogEntry(RLogLevel level, string text, Color? color = null)

A line written now by the calling thread, with its own color if given.

Properties

Number

long Number { get; }

The progressive number of the line in this run (1, 2, 3...): who has seen a line can skip it.

Time

DateTime Time { get; }

When it was written (local time).

Level

RLogLevel Level { get; }

How important it is.

Thread

int Thread { get; }

The managed id of the thread that wrote it.

Text

string Text { get; }

The text (with the exception, if there was one).

Color

Color? Color { get; }

The color chosen for the text (null: the color of the level).

TextColor

Color? TextColor { get; }

The color the text is shown in: its own, or that of the level (null for Info: the normal ink).

Methods

LevelColor

static Color LevelColor(RLogLevel level)

The color of a level, readable on a white and on a dark background: red errors, orange warnings, blue info, grey debug and trace.

Tag

static string Tag(RLogLevel level)

The three letters of the level: ERR, WRN, INF, DBG, TRC.

ToString

string ToString()

«2026-11-06 15:04:05.123 INF [1] text», as in the file.

RLogView

sealed class RLogView : UserControl

The application log shown live, with a level filter.

Constructors

RLogView

RLogView()

An empty view; the lines already in memory arrive when it enters a window, then the new ones.

Properties

MaxLines

int MaxLines { get; set; }

How many lines the view keeps (5000).

Level

RLogLevel Level { get; set; }

The least important level shown.

Count

int Count { get; }

How many lines are shown now.

Methods

Clear

void Clear()

Empties the view (the file of the log stays).

RTheme

static class RTheme

The theme of the application: light, dark or as the system.

Properties

Mode

static RThemeMode Mode { get; set; }

The choice in use; setting it changes the theme of the application.

IsDark

static bool IsDark { get; }

Whether the theme on the screen now is dark (also when chosen by the system).

Events

Changed

static event Action<RThemeMode>? Changed

After the theme has changed, with the new choice.

Methods

Toggle

static void Toggle()

Light ↔ dark, from the theme on the screen (a System choice becomes the other).

Remember

static void Remember(RSettings s, string key = "ui.theme", RThemeMode def = System)

Reads the choice from the settings (the default if missing), applies it, and writes it there at every change.

Fill

static void Fill(MenuItem menu)

Fills a menu with the three choices (texts of RLang, «raval.theme.*»), the one in use ticked.

Button

static Button Button()

A flat button with sun or moon that toggles light and dark.

RThemeMode

enum RThemeMode

The theme chosen by the user.

Values

Light

Light = 0

Always light.

Dark

Dark = 1

Always dark.

System

System = 2

As the operating system, changing when it changes.

RLang

static class RLang

The texts of the application in the language chosen, changed live.

Properties

Folder

static string? Folder { get; }

The folder of the language files (null: only the defaults of the code).

Language

static string Language { get; }

The language in use, a code as «it», «en», «de» («en» before Open).

Extension

static string Extension { get; set; }

The extension of new language files: «.json» or «.ini» (.json).

BoundCount

static int BoundCount { get; }

How many controls are bound now (the dead ones are dropped at the next change).

Events

Changed

static event Action? Changed

After the language has changed (the bound controls are already updated).

Methods

Open

static void Open(string folder, string language = "")

Uses the language files of a folder (created if missing) and the given language («»: the language of the system, as «it»).

Use

static void Use(string language)

Changes the language: reads its file, if there is one, updates every bound control and the texts of RAVAL, then tells Changed.

Languages

static List<string> Languages()

The languages with a file in the folder, by code.

T

static string T(string key, string def)

The text of a key in the language in use: from its file, else from the texts of RAVAL already translated, else the default (which is then written into the file, to be translated).

static string T(string key, string def, params object[] values)

The text of a key with values put in its {0}, {1}... (the invariant culture).

Save

static void Save()

Writes the texts added to the file now (it is saved by itself anyway).

Bind

static void Bind(AvaloniaObject o, AvaloniaProperty p, string key, string def)

Binds a property of a control to a key: set now, and again at every change of language.

Tr

static T Tr<T>(this T c, string key, string def) where T : AvaloniaObject

The text of a control bound to a key: Text of a TextBlock, Header of a menu item or an expander, Title of a window, PlaceholderText of a text box, Content of a button or a check box.

RSettings

abstract class RSettings

The settings of an application, read and written in a file.

Properties

Path

string Path { get; }

The file of the settings.

AddMissing

bool AddMissing { get; set; }

Whether a key read and not found is written with its default (true).

AutoSave

bool AutoSave { get; set; }

Whether the file is saved by itself after a change (true).

SaveDelayMs

int SaveDelayMs { get; set; }

How long after the last change the file is saved, milliseconds (500).

Dirty

bool Dirty { get; }

Whether there are changes not yet written.

Events

Changed

event Action<string>? Changed

After Set has changed a value, with its key (on the thread that called Set).

Methods

Open

static RSettings Open(string path)

The settings of a file, already read: INI for «.ini», JSON for every other extension. A missing file is not an error: it is created at the first save.

Folder

static string Folder(string app)

The folder of the settings of an application, created if missing: %APPDATA%\app on Windows, ~/.config/app on Linux and macOS (what .NET gives for ApplicationData).

GetString

string GetString(string key, string def)

A text value (the default if the key is missing).

GetInt

int GetInt(string key, int def)

An integer value (the default if missing or not a number).

GetDouble

double GetDouble(string key, double def)

A real value, written with the point (the default if missing or not a number).

GetBool

bool GetBool(string key, bool def)

A yes/no value: true, yes, on, 1 and false, no, off, 0 (the default otherwise).

GetList

List<string> GetList(string key)

A list of texts (empty if the key is missing; a missing list is not added).

Contains

bool Contains(string key)

Whether the key is in the file.

Set

void Set(string key, string value)

Writes a text value.

void Set(string key, int value)

Writes an integer value.

void Set(string key, double value)

Writes a real value, with the point and all its digits.

void Set(string key, bool value)

Writes a yes/no value.

SetList

void SetList(string key, IEnumerable<string> values)

Writes a list of texts.

Remove

void Remove(string key)

Removes a key (value or list); nothing if it is not there.

Keys

List<string> Keys()

The keys of the values in the file, with their full path, in file order.

Load

bool Load()

Reads the file again, forgetting what is not saved; false if it was damaged.

Save

void Save()

Writes the file now, if something changed (a temporary file, then renamed).

RJsonSettings

sealed class RJsonSettings : RSettings

Settings in a JSON file.

Constructors

RJsonSettings

RJsonSettings(string path)

Settings in the given JSON file, still to be read (RSettings.Open reads it).

RIniSettings

sealed class RIniSettings : RSettings

Settings in an INI file.

Constructors

RIniSettings

RIniSettings(string path)

Settings in the given INI file, still to be read (RSettings.Open reads it).

RWindowMemory

static class RWindowMemory

Windows that remember position and size in the settings.

Methods

Remember

static void Remember(this RSettings s, Window w, string name)

Gives the window the position and size saved under name and saves them again when they change. Call it before Show.

Visible

static bool Visible(IReadOnlyList<Screen> screens, PixelPoint p)

Whether a window with its top left corner at p would show at least its title bar (a 100 × 30 pixel corner) on one of the screens.

RRecentFiles

sealed class RRecentFiles

The list of the last files, saved in the settings.

Constructors

RRecentFiles

RRecentFiles(RSettings s, string key = "recent")

The list kept under key of the settings.

Properties

Max

int Max { get; set; }

How many files are kept (10).

Items

List<string> Items { get; }

The files, newest first.

Events

Opened

event Action<string>? Opened

When a file of the menu is chosen, with its path.

Methods

Add

void Add(string path)

Puts a file at the top of the list.

Remove

void Remove(string path)

Takes a file out of the list (it was moved or deleted).

Clear

void Clear()

Empties the list.

Fill

void Fill(MenuItem menu)

Fills the menu with one item per file («1 name.prj», the full path in the tooltip), and keeps it filled when the list changes; disabled when empty.

RServer

sealed class RServer

JSON API server on Kestrel: each path calls a method of the program.

Constructors

RServer

RServer(int port = 0)

The server on the given port; 0 = a free port chosen by the system (see Addresses).

Properties

Port

int Port { get; }

The requested port (0 = chosen by the system at start).

AllInterfaces

bool AllInterfaces { get; }

true if it listens on every network interface, false only on this computer (127.0.0.1).

UiThread

bool UiThread { get; }

true if the methods run on the user interface thread.

Json

JsonSerializerOptions Json { get; }

How JSON is written and read: camelCase, like JsonSerializerDefaults.Web. It can be changed before StartAsync.

Started

bool Started { get; }

true after StartAsync and until StopAsync.

Addresses

IReadOnlyList<string> Addresses { get; }

The addresses it answers on, with the real port (for instance «http://127.0.0.1:51234»); empty if not started.

Methods

Get

RServer Get(string path, Func<RRequest, object?> method)

GET: read. The path can have parameters in braces: «/api/machines/{id}».

Post

RServer Post(string path, Func<RRequest, object?> method)

POST: create or run an action, usually with a JSON body.

Put

RServer Put(string path, Func<RRequest, object?> method)

PUT: replace a resource.

Delete

RServer Delete(string path, Func<RRequest, object?> method)

DELETE: delete a resource.

GetAsync

RServer GetAsync(string path, Func<RRequest, Task<object?>> method)

GET with an asynchronous method (that reads a database, calls another service...).

PostAsync

RServer PostAsync(string path, Func<RRequest, Task<object?>> method)

POST with an asynchronous method.

OnAllInterfaces

RServer OnAllInterfaces()

Listens on every network interface: the server can be reached from other computers or from a phone.

OnUiThread

RServer OnUiThread()

Runs the methods on the user interface thread, so they can read and change the controls.

Start

void Start()

Starts the server and returns when it is listening. For those who do not use async/await yet.

Stop

void Stop()

Stops the server and frees the port. For those who do not use async/await yet.

Run

void Run()

Starts the server and stays here until another thread calls Stop: the classic way, with a dedicated thread. new Thread(server.Run).Start() in a program with windows, or Run() at the end of the Main of a console program that is only a server.

WaitStarted

bool WaitStarted(TimeSpan timeout)

Waits (at most for the given time) until the server is listening: for those who started it with Run in another thread.

StartAsync

Task StartAsync()

Starts Kestrel with the registered paths; returns when the server is listening.

StopAsync

Task StopAsync()

Stops the server and frees the port; it can be called even if it is not started. The requests in progress have at most 5 seconds to finish: with OnUiThread a request waiting for the user interface thread, while the interface waits for Stop, does not block the program forever.

Dispose

void Dispose()

Like Stop: to use the server with using.

DisposeAsync

ValueTask DisposeAsync()

Like StopAsync: to use the server with await using.

RRequest

sealed class RRequest

An HTTP request received by RServer, with the body already read.

Constructors

RRequest

RRequest(HttpContext context, string body, JsonSerializerOptions json)

The request created by RServer, with the body already read as text.

Properties

Context

HttpContext Context { get; }

The ASP.NET Core context, for whoever needs something that is not here.

Method

string Method { get; }

The method: GET, POST, PUT, DELETE...

Path

string Path { get; }

The requested path, for instance «/api/machines/3».

Text

string Text { get; }

The body of the request as text («» if there is none).

Methods

Param

string? Param(string name)

A parameter: first those of the path («/api/machines/{id}»), then those after the ? («?filter=red»). null if missing.

Int

int Int(string name)

An integer parameter; if missing or not a number it throws RHttpError 400, which becomes the response.

Header

string? Header(string name)

A header of the request (null if missing).

Body

T? Body<T>()

The body read as an object from JSON. If the body is missing or is not valid JSON for that type it throws RHttpError 400, which becomes the response: the program's method always gets a real object.

RResponse

sealed class RResponse

The response of a method with an HTTP status other than 200, or an error with its message.

Constructors

RResponse

RResponse(int status, object? body)

A status and an object to send as JSON.

Properties

Status

int Status { get; }

The HTTP status (200, 201, 404...).

Body

object? Body { get; }

The object to send as JSON; null = response without a body.

Methods

Created

static RResponse Created(object? body)

201: created, with the new object.

NotFound

static RResponse NotFound(string message)

404 with the message: { "error": "..." }.

Error

static RResponse Error(int status, string message)

An error with its status and message: { "error": "..." }.

RHttpError

sealed class RHttpError : Exception

An error that the program's method throws to answer with an HTTP status (400, 404, 409...): RServer turns it into the response { "error": message }.

Constructors

RHttpError

RHttpError(int status, string message)

The status and the message.

Properties

Status

int Status { get; }

The HTTP status of the response.

RErrorMessage

sealed class RErrorMessage

The JSON body of every error: { "error": "message" }.

Constructors

RErrorMessage

RErrorMessage(string error)

The error with its message.

Properties

Error

string Error { get; }

The message.