High level API with O R mapper - danikf/tik4net GitHub Wiki
Third option is to use High-level API with strongly typed entities. This API uses internal O/R mapper to map mikrotik repose sentences to prepared (or yours) objects. This API is in separate dll - so you should reference tik4net.objects.dll.
All methods of this API are implemented as extensions of ITikConnection and ITikCommand. That means that ADO.NET like API and High-level API could be used together.
NOTE: do not forget to put using tik4net.Objects;
to your class header.
The main entry point is mikrotik router connection object (ITikConnection). Instance of connection object should be instancied via factory (ConnectionFactory). Command instance should be created via ITikConnection methods.
using tik4net;
using tik4net.Objects;
// ...
connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, HOST, USER, PASS);
var interfaces = Connection.LoadAll<Interface>();
- Data entities
- Reading data entities
- Create, update, delete entities
- Andvanced scenarios
- How to create custom entity
- How to use provided tools to create custom entities
// SCRIPT equivalent: interface set comment=test [/interface find name=ether1]
private static void ChangeCommentOnInterfaceWithName(ITikConnection connection, string interfaceName, string newComment)
{
// Load by name (filter)
var iface = connection.LoadByName<Objects.Interface.Interface>(interfaceName);
// modify iface object + write changes to mikrotik
iface.Comment = newComment;
connection.Save(iface);
}
// SCRIPT equivalent: interface set comment=test [/interface find default-name=ether1]
private static void ChangeCommentOnInterfaceWithDefraultName(ITikConnection connection, string defaultName, string newComment)
{
// Load by default-name (filter)
var iface = connection.LoadSingle<Objects.Interface.Interface>(connection.CreateParameter("default-name", defaultName));
// modify iface object + write changes to mikrotik
iface.Comment = newComment;
connection.Save(iface);
}
Notes - how to find single item
- Use
LoadByName
where name is unique - Mark item by custom
comment
and use filter to find (REMARKS: prefix/suffix/regex are not supported by mikrotik API) - Use
LoadAll
and C# lookup in collection for more complicated scenarios (be carefull when reading bunch of rows) - Create custom small entity for handling large resultsets
private static void CreateOrUpdateAddressList(ITikConnection connection)
{
var existingAddressList = connection.LoadList<FirewallAddressList>(
connection.CreateParameter("list", "TEST-LIST"),
connection.CreateParameter("address", "192.168.88.1"))
.SingleOrDefault();
if (existingAddressList == null)
{
//Create
var newAddressList = new FirewallAddressList()
{
Address = "192.168.88.1",
List = "TEST-LIST",
};
connection.Save(newAddressList);
}
else
{
//Update
existingAddressList.Comment = "Comment update: " + DateTime.Now.ToShortTimeString();
connection.Save(existingAddressList);
}
}