Skip to content

TikListMerge

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

Support for merging expected state with state on mikrotik router

  • Easy to use
  • Support for re-ordering collections
  • Usefull for large configurations - minimum DML actions (changes in router configuration) performed

##Main idea

  • Prepare expected configuration in memory list
  • Load configuration from mikrotik router
  • Use TikListMerge class to handle all modifications

##Trivial Example

  • There is list in /ip/firewall/address-list named 'MY-LIST'
  • It contains large number of items
  • We have list of IPs, that should be in address-list named 'MY-LIST' (with comments)
  • Configuration of mikrotik should be changed with minimum DML operations
  • Trivial solution is delete-all / insert-all, but with TikListMerge class we have better solution.
// Example is taken from MikrotikManager code (commercial ISP solution) and was simplified
private void UpdateMyList()
{
  // read expected state from database
  List<FirewallAddressList> inDatabaseItems = LoadItemsFromDatabase();
  using (var tikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
  {
    tikConnection.Open(_host, /*tikPort,*/ _user, _pass);

    // read actual state from router configuration
    var onRouterItems = tikConnection.LoadList<FirewallAddressList>(tikConnection.CreateParameter("list", "MY-LIST")).ToList();
   
    //setup merge object
    var merge = tikConnection.CreateMerge(inDatabaseItems, onRouterItems )
      //key fields
      .WithKey(a => a.Address) //items are the same, if they have the same IP address

      //defaults (these values are used just for insert, not for update or compare)
      .JustForInsertField(a => a.Address)
      .JustForInsertField(a => a.Disabled) 
      .JustForInsertField(a => a.List)

      //fields (if comment is different, than row is updated - not deleted/inserted)
      .Field(a => a.Comment);

    merge.Save(); //perform DML - change mikrotik configuration
}