Skip to content

Building an application

Daniel Frantík edited this page Nov 25, 2026 · 2 revisions

Building an application

How to put tik4net into a program that runs for days: a service, a web API, a monitor. Four decisions matter — where the setup lives, how many connections to hold, what to do when one is lost, and how to log — and this page gives each one's answer. The complete runnable version is the service command of the sample app, a .NET generic-host BackgroundService.

using System;
using System.Threading;
using System.Threading.Tasks;
using tik4net;
using tik4net.Objects;
using tik4net.Objects.TikSystem;

// one setup for the application, from configuration; the password is a reference, not the password
var setup = TikConnectionSetup.FromConnectionString("transport=Api;host=192.168.88.1;user=monitor;password=env:ROUTER_PW");
using var stop = new CancellationTokenSource();
ITikConnection? connection = null;

while (!stop.IsCancellationRequested)
{
    try
    {
        connection ??= await setup.CreateAsync(stop.Token);                     // one long-lived connection
        var resource = await connection.LoadSingleAsync<SystemResource>(stop.Token);
        Console.WriteLine($"cpu {resource.CpuLoad.Value} %");
        await Task.Delay(TimeSpan.FromSeconds(10), stop.Token);
    }
    catch (Exception ex) when (ex is TikConnectionNotOpenException or TikConnectionSessionClosedException
                                   or TikCommandFatalException or TikConnectionReceiveTimeoutException)
    {
        connection?.Dispose();                                                  // the session is gone: start a new one
        connection = null;
        await Task.Delay(TimeSpan.FromSeconds(5), stop.Token);
    }
}
connection?.Dispose();

The setup is a singleton

TikConnectionSetup holds the router, the credentials, the transport and the options, and no connection. Build it once at start-up and hand it to whatever needs a connection — in a .NET host, register it as a singleton:

builder.Services.AddSingleton(TikConnectionSetup.FromConnectionString(builder.Configuration["Router"]!));
builder.Services.AddHostedService<RouterMonitorService>();
  • Keep the connection string in configuration, with the password as a reference: password=env:ROUTER_PW, password=file:/run/secrets/router_pw, or password=dpapi:… on Windows — see Keeping the password out of the configuration.
  • setup.ToString() is the connection string with the password written as ***, safe to log.
  • The setup has no locking: fill it in on one thread, then create connections from any.

One connection per router

Open one connection per router and keep it. It is safe to call from several threads on every transport; on Api, Rest and WinBox native the commands even run at the same time — see Threading. More connections are not faster: the router's command rate is shared by all of them, so a pool only reaches its limit sooner. Pace bulk work rather than spreading it.

A connection opens in setup.Create / setup.CreateAsync, and Dispose closes it.

When the connection is lost

A router reboots, a link flaps, a session times out. These exceptions mean the session is over — dispose the connection and open a new one with the same setup:

Exception Means
TikConnectionNotOpenException the connection was closed, or closed under the command
TikConnectionSessionClosedException the session stopped answering; the command did not run
TikCommandFatalException the router ended the session (!fatal), or the connection ended while the command waited
TikConnectionReceiveTimeoutException no answer within ReceiveTimeout
System.Net.Sockets.SocketException from the open: nothing answers at the address

Every other exception — a trap, a missing row, a field the menu lacks — is about the command, and the connection stays usable.

A write interrupted this way is unknown, not failed. The router may have run it before the connection went. A read can simply be repeated; before repeating a write, read back whether it happened, or make it idempotent (a list merge is). The full table is on Exception handling.

Logging

The connection raises OnWriteRow and OnReadRow for every word, which is a ready-made bridge to ILogger:

connection.OnWriteRow += (_, e) => logger.LogTrace(">> {Word}", e.Word);
connection.OnReadRow  += (_, e) => logger.LogTrace("<< {Word}", e.Word);
  • On the binary API these carry the login password in clear text; do not persist them unfiltered. TikWireTrace redacts the credential and covers every transport.
  • The handlers run on transport threads, concurrently: keep them thread-safe and short.
  • For drift between RouterOS versions — values a read could not parse, fields no row carried — attach connection.SetEntityDiagnostics(...): see Checking what a load met.

Timeouts for a slow router

ConnectTimeout (15 s) bounds the open and ReceiveTimeout (30 s) each answer. A busy or distant router, or a command that takes long by nature (/system/package/update, a large print over a MAC-layer transport), needs a larger ReceiveTimeout on the setup; pass a CancellationToken to the async calls for your own deadline. See Options and Async and cancellation.

Testing

Code that takes an ITikConnection runs against TikFakeConnection from tik4net.testing, without a router — see Unit testing without a router.

See also

Clone this wiki locally