Tutorial: Task plugin
A task plugin is an entry in the device context menu. The user selects devices, picks the entry, fills a dialog, and OADM runs the work on the server, one task per device. Each task shows in the tasks pane with its steps and log, so one device that fails never marks the others as failed.
In this tutorial you create Set UPnP name: it gives devices a new UPnP name (the name Windows shows in its network list). It has everything a real task needs: a dialog with validation, a read of the current value, a check of the device’s API, named steps, a check after the write, and tests that run without a camera.
1. Create it
Section titled “1. Create it”You need the .NET 10 SDK and an editor. Run:
dotnet new install Oadm.Plugin.Templatesdotnet new oadm-task -n MyCoolPlugincd MyCoolPlugindotnet tool restoredotnet buildThis creates the tutorial’s plugin under your name. It builds, its tests pass, and it runs. The code below is the
original; in your copy every UpnpName reads MyCoolPlugin and the id is community.my-cool-plugin (choose your own
with --id acme.my-cool-plugin).
DirectoryMyCoolPlugin/
- MyCoolPlugin.slnx
DirectoryMyCoolPlugin/ the server part: does the work on the devices
- MyCoolPlugin.csproj
- MyCoolPlugin.cs the payload and the rules both parts share
- MyCoolPluginTaskPlugin.cs the task
DirectoryMyCoolPlugin.Client/ the client part: the dialog
- MyCoolPlugin.Client.csproj
- MyCoolPluginDialog.cs
- MyCoolPluginViewModel.cs
- MyCoolPluginWindow.axaml
- MyCoolPluginWindow.axaml.cs
DirectoryMyCoolPlugin.Tests/
- MyCoolPluginTaskPluginTests.cs
Directory.oadm/plugins/community.my-cool-plugin/ after a build: the plugin folder OADM loads
- …
2. How a task runs
Section titled “2. How a task runs”flowchart LR
M["Context menu<br/>CanRun per device"] --> D["Dialog<br/>QueryAsync reads,<br/>returns the payload"]
D --> S["Server<br/>one task per device"]
S --> E["ExecuteAsync<br/>named steps"]
E --> R(["Done, Done with warnings<br/>or Failed"])
- The user selects devices and picks your entry. The entry is greyed out with a reason for devices it cannot run on.
- Your dialog opens on the user’s computer. It may read the current state from a device, then returns a payload: a small JSON text with what the user chose.
- The server creates one task per device and runs your
ExecuteAsyncfor each, up to 16 at a time. It hands you a VAPIX client that is already logged in to the device; the password never reaches your code. - Every request and every wait is a step with a name. The user sees the steps live, and which one failed.
- Returning means Done, an exception means Failed with its message, a warning means Done with warnings.
The server part never shows UI, the client part never talks to a device.
3. The project files
Section titled “3. The project files”Both projects use the plugin project SDK Oadm.Plugin.Sdk (the template writes the version you installed). It compiles
against the OADM SDK but never copies it: OADM itself provides it at runtime. The server project’s properties become the
plugin’s plugin.json: the OadmPluginId is the plugin’s key everywhere (folder, settings, permissions) and never
changes, the display name and description are its row on the Plugins page.
<Project Sdk="Oadm.Plugin.Sdk/x.y.z"> <!-- The server part: UpnpName.Server.dll and its plugin.json, written from these properties. --> <PropertyGroup> <OadmPluginId>acme.upnp-name</OadmPluginId> <Version>1.0.0</Version> <OadmDisplayName>Set UPnP name</OadmDisplayName> <OadmDescription>Sets the name devices show in the network list of Windows.</OadmDescription> </PropertyGroup></Project>Add <OadmEnabledByDefault>false</OadmEnabledByDefault> to keep the plugin off until an administrator turns it on.
The client project names the same plugin id, and references the server project to share its payload record. The SDK adds the client SDK and Avalonia (the UI framework).
<Project Sdk="Oadm.Plugin.Sdk/x.y.z"> <!-- The client part: UpnpName.Client.dll in the same plugin folder as the server part. --> <PropertyGroup> <OadmPluginId>acme.upnp-name</OadmPluginId> </PropertyGroup>
<ItemGroup> <ProjectReference Include="..\UpnpName\UpnpName.csproj" /> </ItemGroup></Project>After each build both parts land in .oadm/plugins/<id>/: the plugin folder OADM loads.
4. What both parts share
Section titled “4. What both parts share”The dialog and the task must agree on the payload and on what a valid name is. Writing that once, in the server project, keeps them from drifting apart.
using System.Text.Json;
namespace UpnpName;
/// <summary>What the dialog sends and the query answers. Shared by the server and the client part.</summary>public sealed record UpnpNamePayload(string Name);
public static class UpnpName{ public const string PluginId = "acme.upnp-name"; public const string Parameter = "Network.UPnP.FriendlyName"; public const int MaxLength = 64;
public static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
/// <summary>Why the name cannot be used, or null. The dialog and the task use the same rule.</summary> public static string? Problem(string? name) { var text = name?.Trim() ?? ""; if (text.Length == 0) { return "Enter a name."; }
if (text.Length > MaxLength) { return $"Use at most {MaxLength} characters."; }
return text.Any(char.IsControl) ? "The name cannot contain control characters." : null; }}5. The task
Section titled “5. The task”This is the heart of the plugin. Read it from top to bottom:
DisplayName,Group,IconKey: the entry in the context menu, here Network > Set UPnP name.CanRundecides from what OADM already knows (status, the device’s API list) whether the entry is enabled. It must be fast: it runs for every selected device while the menu opens.NotSupportedReasonis the tooltip of a greyed entry.GetTaskNameis the name in the tasks pane: what this task does (“Set UPnP name Entrance”), never a password.ExecuteAsyncruns once per device:- it checks the input before anything is sent;
PlanStepsshows all steps as pending;- each
StepAsync/BeginStepis one named step; a step that does not apply is skipped with a reason; - before the first write it asks the device for its API list again and stops with “Nothing was changed” when the API is missing;
- it reads the value back after writing and warns when the device did not take it.
QueryAsync(ctx, caller, device, ...)answers the dialog. It only reads; changing a device here is not allowed. OADM checks that the user seesdeviceand logsctx.Vapixin to it. A user may be limited to a device group: a query that reads another device goes throughcaller.Devicesandcaller.Vapix. The overload withoutcallerstays only because the interface needs it.- The task itself touches only its own device, through
ctx.Vapix.
using System.Text;using System.Text.Json;
using Oadm.Sdk.Devices;using Oadm.Sdk.Plugins;using Oadm.Sdk.Vapix;
namespace UpnpName;
public sealed class UpnpNameTaskPlugin : ITaskPlugin, ITaskPluginQuery{ private const string StepCheck = "Check compatibility"; private const string StepRead = "Read the current name"; private const string StepSet = "Set the name"; private const string StepVerify = "Verify the name";
public string Id => UpnpName.PluginId; public string DisplayName => "Set UPnP name"; public string? IconKey => "edit"; public string Group => TaskGroups.Network; public bool ShowInToolbar => false; public bool RequiresDialog => true;
// Cached data only: the status and the API list of the last full refresh. public bool CanRun(IDeviceInfo device) => device.Status is DeviceStatus.Ok or DeviceStatus.Unknown && device.Apis.Supports("param-cgi", "1.0");
public string? NotSupportedReason(IDeviceInfo device) => TaskSupportReasons.ForStatus(device) ?? TaskSupportReasons.NeedsApi("the parameter API", device);
public string GetTaskName(string? payloadJson) { var payload = Read(payloadJson); return payload is null ? DisplayName : "Set UPnP name " + payload.Name.Trim(); }
public async Task ExecuteAsync(ITaskExecutionContext ctx, IDeviceInfo device, string? payloadJson, CancellationToken ct) { // Validate everything before the first request. var name = Read(payloadJson)?.Name.Trim(); if (UpnpName.Problem(name) is { } problem) { throw new ArgumentException(problem + " Nothing was changed."); }
ctx.PlanSteps(StepCheck, StepRead, StepSet, StepVerify);
await ctx.StepAsync(StepCheck, async _ => (await ctx.Vapix.GetApiListAsync(ct)).Require("param-cgi", "1.0"));
var current = await ctx.StepAsync(StepRead, async step => { var value = await ReadNameAsync(ctx.Vapix, ct); step.Complete(value.Length == 0 ? "No name" : value); return value; });
if (current == name) { ctx.SkipStep(StepSet, "The device already has this name"); ctx.SkipStep(StepVerify, "Nothing was changed"); return; }
await ctx.StepAsync(StepSet, _ => WriteNameAsync(ctx.Vapix, name!, ct));
using var verify = ctx.BeginStep(StepVerify); var after = await ReadNameAsync(ctx.Vapix, ct); if (after == name) { verify.Complete(after); } else { verify.Warn($"The device reports \"{after}\" after the change."); } }
// Read-only: the dialog shows the current name of the first selected device. OADM checks that the user sees the // device and logs ctx.Vapix in to it; any other device would be read through caller. public async Task<string?> QueryAsync(ITaskQueryContext ctx, ICallContext caller, IDeviceInfo device, string method, string? payloadJson, CancellationToken ct) => method switch { "current" => JsonSerializer.Serialize(new UpnpNamePayload(await ReadNameAsync(ctx.Vapix, ct)), UpnpName.Json), _ => throw new ArgumentException("Unknown query " + method), };
// OADM calls the query above, with the user's call. public Task<string?> QueryAsync(ITaskQueryContext ctx, IDeviceInfo device, string method, string? payloadJson, CancellationToken ct) => throw new NotSupportedException("The query needs the user's call.");
private static async Task<string> ReadNameAsync(IVapixClient vapix, CancellationToken ct) { var values = await vapix.ListParametersAsync([UpnpName.Parameter], ct); return values.TryGetValue(UpnpName.Parameter, out var value) ? value : ""; }
private static async Task WriteNameAsync(IVapixClient vapix, string name, CancellationToken ct) { // Values go in the POST body, never in the URL. var body = "action=update&" + Uri.EscapeDataString(UpnpName.Parameter) + "=" + Uri.EscapeDataString(name); using var request = new HttpRequestMessage(HttpMethod.Post, "/axis-cgi/param.cgi") { Content = new StringContent(body, Encoding.UTF8, "application/x-www-form-urlencoded"), }; using var response = await vapix.SendAsync(request, ct); var text = await response.Content.ReadAsStringAsync(ct); if (!response.IsSuccessStatusCode || !text.TrimStart().StartsWith("OK", StringComparison.Ordinal)) { throw new InvalidOperationException("The device refused the name: " + text.Trim()); } }
private static UpnpNamePayload? Read(string? json) { try { return string.IsNullOrEmpty(json) ? null : JsonSerializer.Deserialize<UpnpNamePayload>(json, UpnpName.Json); } catch (JsonException) { return null; } }}6. The dialog
Section titled “6. The dialog”The client loader finds the class that implements ITaskPluginDialog with your plugin id. ShowAsync opens the
window, prefills it through your query (the dialog works without it too) and returns the payload, or null when the user
cancels.
using System.Text.Json;
using Avalonia.Controls;
using Oadm.Sdk.Client;using Oadm.Sdk.Devices;
namespace UpnpName.Client;
/// <summary>Found by the client loader: opens before the task runs and returns the payload (null = cancelled).</summary>public sealed class UpnpNameDialog : ITaskPluginDialog{ public string PluginId => UpnpName.PluginId;
public async Task<string?> ShowAsync(ITaskDialogContext ctx, IReadOnlyList<IDeviceInfo> devices, Window owner) { var model = new UpnpNameViewModel(devices.Count); var window = new UpnpNameWindow { DataContext = model };
// Prefill with the name of the first device; the dialog works without it. using var cts = new CancellationTokenSource(); _ = model.LoadAsync(token => ctx.QueryAsync(devices[0].Id, "current", null, token), cts.Token);
var ok = await window.ShowDialog<bool>(owner); await cts.CancelAsync(); return ok ? JsonSerializer.Serialize(new UpnpNamePayload(model.Name.Trim()), UpnpName.Json) : null; }}The view model holds the form. It derives from ValidatingViewModel: each rule returns an error text or null, the
error shows directly below the field once the user typed or left it, and OK stays disabled while there is one.
using System.Text.Json;
using CommunityToolkit.Mvvm.ComponentModel;using CommunityToolkit.Mvvm.Input;
using Oadm.Sdk.Client.Validation;
namespace UpnpName.Client;
public sealed partial class UpnpNameViewModel : ValidatingViewModel{ public UpnpNameViewModel(int deviceCount) { Intro = deviceCount == 1 ? "The name the device shows in the network list." : $"The name {deviceCount} devices show in the network list."; Validation.Rule(nameof(Name), () => UpnpName.Problem(Name)); Validation.Validate(); }
public string Intro { get; }
[ObservableProperty] public partial string Name { get; set; } = "";
/// <summary>The window closes with true (OK) or false (Cancel).</summary> public event Action<bool>? CloseRequested;
public async Task LoadAsync(Func<CancellationToken, Task<string?>> query, CancellationToken ct) { try { var json = await query(ct); if (Name.Length == 0 && json is not null && JsonSerializer.Deserialize<UpnpNamePayload>(json, UpnpName.Json) is { } current) { Name = current.Name; Validation.Reset(nameof(Name)); // a prefilled value shows no error yet } } catch (Exception ex) when (ex is not OutOfMemoryException) { // No prefill: the user types the name. } }
[RelayCommand(CanExecute = nameof(IsFormValid))] private void Apply() => CloseRequested?.Invoke(true);
[RelayCommand] private void Cancel() => CloseRequested?.Invoke(false);
protected override void OnValidationChanged() => ApplyCommand.NotifyCanExecuteChanged();}The window uses the shared parts of every OADM dialog: the title bar with its X, a form field with the label left and the error below the input, and the footer with Cancel and one accent button. Use them and your dialog looks like the rest of the app in dark and light, without any colors or sizes of its own.
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:ui="using:Oadm.Sdk.Client.Controls" xmlns:vm="using:UpnpName.Client" x:Class="UpnpName.Client.UpnpNameWindow" x:DataType="vm:UpnpNameViewModel" Title="Set UPnP name" Width="500" SizeToContent="Height" CanResize="False" WindowStartupLocation="CenterOwner" ShowInTaskbar="False" WindowDecorations="BorderOnly"> <Grid RowDefinitions="Auto,Auto,Auto"> <ui:DialogTitleBar Grid.Row="0" Text="Set UPnP name" />
<Border Grid.Row="1" Classes="dialogBody"> <StackPanel Classes="form"> <TextBlock Classes="secondary" Text="{Binding Intro}" TextWrapping="Wrap" /> <ui:FormField Label="Name"> <TextBox Text="{Binding Name}" /> </ui:FormField> </StackPanel> </Border>
<ui:DialogFooter Grid.Row="2" CancelCommand="{Binding CancelCommand}"> <Button Classes="primary" Content="OK" Command="{Binding ApplyCommand}" IsDefault="True" ToolTip.Tip="{Binding FormError}" ToolTip.ShowOnDisabled="True" /> </ui:DialogFooter> </Grid></Window>using Avalonia.Controls;using Avalonia.Markup.Xaml;
namespace UpnpName.Client;
public sealed partial class UpnpNameWindow : Window{ public UpnpNameWindow() => AvaloniaXamlLoader.Load(this);
protected override void OnDataContextChanged(EventArgs e) { base.OnDataContextChanged(e); if (DataContext is UpnpNameViewModel model) { model.CloseRequested += ok => Close(ok); } }}7. The tests
Section titled “7. The tests”The tests need no camera. The package Oadm.Sdk.Testing has what they use: FakeCamera answers parameter reads and
writes and the API list, FakeDevice is the device as OADM knows it, FakeTaskContext records the steps, and StepRun
ends the task the way the server does (it adds the final step Completed on success).
Test the normal run step by step, a value that is already set, a device without the API, invalid input, what the
menu shows and the dialog’s query. FakeCoreContext runs the query like OADM, as CallAsGroup([ids]) or
CallAsAllDevices(). The canary (PluginCanary with TaskPluginCanaryHost) starts the task as a user whose group
holds one device and checks that a device outside the group is refused like an unknown one
(Device groups):
using Oadm.Sdk.Devices;using Oadm.Sdk.Testing;using Oadm.Sdk.Vapix;
namespace UpnpName.Tests;
public sealed class UpnpNameTaskPluginTests{ private readonly UpnpNameTaskPlugin _plugin = new();
/// <summary>A camera with the UPnP name parameter (Oadm.Sdk.Testing answers param.cgi list and update).</summary> private static FakeCamera Camera() => new() { Parameters = { [UpnpName.Parameter] = "AXIS P3265-V - B8A44F631339" } };
/// <summary>A managed device whose cached API list has param.cgi.</summary> private static FakeDevice Device(DeviceStatus status = DeviceStatus.Ok) => new() { Status = status, Apis = [new("param-cgi", "1.0")] };
[Fact] public async Task Sets_and_verifies_the_name() { var camera = Camera(); var ctx = new FakeTaskContext(camera);
await StepRun.RunAsync(ctx.Steps, () => _plugin.ExecuteAsync(ctx, Device(), """{"name":"Entrance"}""", CancellationToken.None));
Assert.Equal("Entrance", camera.Parameters[UpnpName.Parameter]); Assert.Equal( ["Check compatibility: Done", "Read the current name: Done", "Set the name: Done", "Verify the name: Done", "Completed: Done"], StepRun.Lines(ctx.Steps)); }
[Fact] public async Task The_same_name_is_not_written_again() { var camera = Camera(); camera.Parameters[UpnpName.Parameter] = "Entrance"; var ctx = new FakeTaskContext(camera);
await StepRun.RunAsync(ctx.Steps, () => _plugin.ExecuteAsync(ctx, Device(), """{"name":"Entrance"}""", CancellationToken.None));
Assert.Equal(0, camera.Writes); Assert.Equal("Set the name: Skipped", StepRun.Lines(ctx.Steps)[2]); }
[Fact] public async Task A_device_without_the_API_is_not_changed() { var camera = Camera(); camera.Apis = []; var ctx = new FakeTaskContext(camera);
await Assert.ThrowsAsync<DeviceNotCompatibleException>(() => StepRun.RunAsync(ctx.Steps, () => _plugin.ExecuteAsync(ctx, Device(), """{"name":"Entrance"}""", CancellationToken.None)));
Assert.Equal(0, camera.Writes); Assert.Equal("Check compatibility: Failed", StepRun.Lines(ctx.Steps)[0]); }
[Fact] public async Task An_empty_name_fails_before_any_request() { var camera = Camera(); var ctx = new FakeTaskContext(camera);
var error = await Assert.ThrowsAsync<ArgumentException>(() => _plugin.ExecuteAsync(ctx, Device(), """{"name":" "}""", CancellationToken.None));
Assert.Contains("Nothing was changed", error.Message, StringComparison.Ordinal); Assert.Equal(0, camera.Writes); }
[Fact] public void The_menu_entry_says_why_it_cannot_run() { Assert.True(_plugin.CanRun(Device())); Assert.False(_plugin.CanRun(Device(DeviceStatus.Unreachable))); Assert.Equal("The device does not answer", _plugin.NotSupportedReason(Device(DeviceStatus.Unreachable))); Assert.False(_plugin.CanRun(Device() with { Apis = [] })); }
[Fact] public void The_task_name_says_what_happens() => Assert.Equal("Set UPnP name Entrance", _plugin.GetTaskName("""{"name":"Entrance"}"""));
[Fact] public async Task The_dialog_reads_the_current_name() { var server = new FakeCoreContext(); var device = server.Add(Device(), Camera());
var answer = await server.QueryAsync(_plugin, server.CallAsGroup([device.Id]), device, "current", null);
Assert.Equal("""{"name":"AXIS P3265-V - B8A44F631339"}""", answer); }
/// <summary>A user limited to a device group that holds only "inside" can start the task only there.</summary> [Fact] public async Task No_call_reaches_a_device_outside_the_users_group() { var server = new FakeCoreContext(); var inside = server.Add(Device(), Camera()); var outside = server.Add(Device(), Camera());
await new PluginCanary(server, new TaskPluginCanaryHost([_plugin]), inside, outside) .Method(TaskPluginCanaryHost.Run, $$"""{"pluginId":"{{UpnpName.PluginId}}","deviceIds":["{inside}","{device}"]}""") .RunAsync(); }}8. Run it
Section titled “8. Run it”dotnet testdotnet oadm dev startdev start runs an OADM server for development in this terminal, with its own data in .oadm/, and loads your plugin;
a new build restarts it. In a second terminal, dotnet oadm dev client opens the client against it: create the
administrator on the first start and add a camera. Select it, right-click, and open Network > MyCoolPlugin. The tasks
pane shows one task per device; Details shows its steps and log.
9. Make it yours
Section titled “9. Make it yours”Change one thing at a time and keep the tests green:
- Name and place:
DisplayName(at most 32 characters, no “…”),Group,IconKey. - Which devices:
CanRunandNotSupportedReason. Check the API your task uses withdevice.Apis.Supports("api-id", "1.0"). - What the user chooses: the payload record, the dialog’s fields and their rules.
- What happens on the device: the steps in
ExecuteAsync, one named step per request. Name steps as short commands with the article: “Read the users”, “Wait for the device to come back”. - The task name:
GetTaskNamesays exactly what one task does. - The tests: one per path through
ExecuteAsync.
10. Share it
Section titled “10. Share it”dotnet oadm deploy --installed puts it into the OADM installed on your computer; dotnet oadm pack writes the
.oadmplugin file for others. Both are explained in Develop with the .NET SDK.
To ship it with OADM, open a pull request on GitHub with the plugin, its tests and a README.md in its folder that says
what it does and on which device and AXIS OS you tried it.