Skip to content

High level API advanced

Daniel Frantik edited this page Mar 8, 2016 · 4 revisions

Trivial usage of LoadAll and Save methods is not sometimes sufficient. This page show you some more advanced techniques:

  • Loading with filter
  • Loading with custom advanced filter
  • Savig list (saving differences)
  • Asynchronous loading
  • Merging lists

##Loading with filter Printing all connections from 192.168.1.2 address:

var command = connection.CreateCommandAndParameters("/ip/firewall/connection/print",
     "src-address", "192.168.3.103");
var list = command.ExecuteList();

###Loading with custom advanced filter Usage of custom filter (search for ether OR wlan interface). For details about filtering see mikrotik API wiki page.

var cmd = Connection.CreateCommandAndParameters(@"/interface/print
      ?type=ether
      ?type=wlan
      ?#|");
var list = cmd.ExecuteList();

###Savig list (saving differences) The main idea is to remember unmodified list, do some changes and save only differences.

var existingAddressList = connection.LoadList<FirewallAddressList>().ToList(); // imagine that returns 10 rows
var listClonedBackup = existingAddressList.CloneEntityList(); //creates clone of all entities in list

existingAdressList.RemoveAt(0); //remove first item
existingAddressList.Add(new FirewallAddressList() {Address="192.168.1.1", List="MY-LIST" }); //add new one
existingAddressList[0].Comment = "New comment";

//save differences into mikrotik  (existingAddressList=modified, listClonedBackup=unmodified)
connection.SaveListDifferences(existingAddressList, listClonedBackup); //performs 1 delete, 1 insert and 1 update

###Asynchronous loading The main reason is that sometimes you can not wait for result (it never ends). For example with torch, scan, sniffer, ... Than you have to start listening, handle responses asynchronously and finaly cancel running operation.

REMARKS: if you want to propagate loaded values to GUI, you should use some kind of synchronization or Invoke, because callbacks are called from non-ui thread.

ITikCommand torchCmd = connection.CreateCommand("/tool/torch", 
    connection.CreateParameter("interface", "ether1"), 
    connection.CreateParameter("port", "any"),
    connection.CreateParameter("src-address", "0.0.0.0/0"),
    connection.CreateParameter("dst-address", "0.0.0.0/0")
);
torchCmd.ExecuteAsync(response => Console.WriteLine("Row: " + response.GetResponseField("tx")));

Console.WriteLine("Press ENTER"); //torch command is running in different thread
Console.ReadLine();
torchCmd.CancelAndJoin(); //stop torch thread

###Merging lists The main idea is that you can prepare expected state on mikrotik router (for example from database) and than you want to somehow update mikrotik to be on the same state. But you want to do it with minimal number of operations. There merge support could help. See this wiki page for details.

Clone this wiki locally