Community discussions

MikroTik App
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

C# API - tik4net on GitHub

Fri Aug 28, 2015 12:54 am

I have just published my API client for .NET. It implements execution of parallel queries which are easily handled due to ADO.NET-like interface + O/R mapper like extensions to provide strong-typed experience (it supports both single entity and list of entities).

Please leave message in this thread if you need some feature to be implemented or if you have any relevant question.

Repository: https://github.com/danikf/tik4net
Wiki: https://github.com/danikf/tik4net/wiki
How to use: https://github.com/danikf/tik4net/wiki/ ... et-library
nuget package: https://www.nuget.org/packages/tik4net/
Releases (usage of nuget package is recommended):
tik4net-3.5.0.zip
tik4net-3.4.0.zip
Features:
  • ITikConnection lowlevel API (send command / read response, async commands)
  • ADO.NET like api (ITikCommand + various Execute... methods)
  • O/R mapper to/from entity classes. (connection.LoadList<Log>())
  • Release also contains C# entity code generators to support semi-automatic generation of custom entities from running mikrotik router and from mikrotik wiki site (from oficial documentation)
  • API-SSL support
  • New mikrotik (from v. 6.43) login process support
  • Dlls builded for .NET 3.5, 4.0, 4.5.x, 4.6.x, netcoreapp1.1, netcoreapp2.0, netstandart1.3, netstandard1.4, netstandard1.6
  • Functional with xamarin and other .NET runtimes based on Mono
Reference downloaded dlls only if you are not able to use nuget package or GitHub sources.
Examples
For read/write examples see API comparison CRUD examples wiki page.

Read and print mikrotik router identity
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
{
  connection.Open(HOST, USER, PASS);
  ITikCommand cmd = connection.CreateCommand("/system/identity/print");
  Console.WriteLine(cmd.ExecuteScalar());
}
Example of async Torch command
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
{
  connection.Open(HOST, USER, PASS);
  var loadingContext = connection.LoadAsync<ToolTorch>(
    torchItem => Console.WriteLine(torchItem.ToString()),
    error => Console.WriteLine(error.ToString()),                                                
    connection.CreateParameter("interface", interfaceName),   
    connection.CreateParameter("port", "any"),
    connection.CreateParameter("src-address", "0.0.0.0/0"),
    connection.CreateParameter("dst-address", "0.0.0.0/0"));

  Console.ReadLine();
  loadingContext.Cancel();
}
read all log entries
var logs = connection.LoadList<Log>();
foreach (Log log in logs)
{
    Console.WriteLine("{0}[{1}]: {2}", log.Time, log.Topics, log.Message);
}
firewall management
//find first firewall rule
var firstFirewallRule = connection.LoadAll<FirewallFilter>().First();

// create new firewall rule as first rule in list
var firewallFilter = new FirewallFilter()
{
   Chain = FirewallFilter.ChainType.Forward,
   Action = FirewallFilter.ActionType.Accept,
};
connection.Save(firewallFilter);
connection.Move(firewallFilter, firstFirewallRule);
NOTE: please do not use deprecated 0.9.7 incompatible version of tik4net from https://code.google.com/p/mikrotik4net/.
You do not have the required permissions to view the files attached to this post.
Last edited by danikf on Wed Jan 01, 2020 5:18 pm, edited 30 times in total.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Aug 28, 2015 1:04 am

Chupaka - thank you for inspiration how to handle paralel queries.

D
BTW: both your and mine code are not realy thread-safe ;-)
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Wed Sep 16, 2015 8:31 pm

Released new version with updates. Added versions for .NET 3.5, .NET 4.0 and .NET 4.5.2
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun Sep 20, 2015 3:29 pm

Released new version 1.2.0.0 with enum support (as field values) and with C# entity code generators.

Enjoy,
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Tue Sep 22, 2015 11:45 pm

Example of highlevel API usage (dev branch on GitHub):
// renew IP on dhcp-client interface
connection.LoadAll<IpDhcpClient>().First().Release(connection);
 
MarkLFT
just joined
Posts: 22
Joined: Mon Apr 23, 2012 7:22 am

Re: C# API - tik4net on GitHub

Wed Sep 30, 2015 10:49 am

This looks like a great project, and one that would be very useful. Thanks for sharing it with us.

I have just downloaded it and spent some time going through the samples and classes, but I did not notice anything to do with Hotspot, in particular creating and deleting user accounts. Is this functionality available in the library? If not, is it something you will be adding anytime soon?

Again, many thanks.

Mark
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Wed Sep 30, 2015 10:20 pm

Hello,

I am going to import hotspot objects very soon (one week?), but I need betatesters, becase I am not using this feature. If you wold participate in betatesting, your help will be appreciated.

Or you can create your own classes (see TikEntity and TikProperty attributes) and use it with O/R mapper like extensions.

Or you can use ADO like api - handle hotspot management via standard "Execute" command interface like other libraries :-)

D
Last edited by danikf on Thu Oct 01, 2015 12:24 am, edited 1 time in total.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Thu Oct 01, 2015 12:15 am

Released new version 1.2.2.0 with hotspot user entities (beta).
using tik4net.Objects;
using tik4net.Objects.Ip.Hotspot;
var user = new HotspotUser()
{
    Name = "TEST",
    LimitUptime = "1:00:00",
    Password = "secretpass"
};
_connection.Save(user);
Enjoy,
D
 
MarkLFT
just joined
Posts: 22
Joined: Mon Apr 23, 2012 7:22 am

Re: C# API - tik4net on GitHub

Thu Oct 01, 2015 8:43 am

We have a test facility in our office here, and use the Hotspot functionality quite extensively, so would be happy to help test it for you.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Oct 16, 2015 11:32 pm

Published version 1.3.0.0.

New highlevel entities:
* Hotspot users
* Interface (eth/wlan)
var list = Connection.LoadAll<InterfaceWireless.WirelessRegistrationTable>();
Enjoy,
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Wed Oct 28, 2015 12:54 am

Version 1.4.0.0 released:

* Fixed word length calculation (credits: h44z)
* Hotspot user management fixed
* Async API refactoring (cleaning)

Enjoy,
D
 
normangon
just joined
Posts: 18
Joined: Thu Oct 16, 2008 8:06 pm
Location: Venezuela
Contact:

Re: C# API - tik4net on GitHub

Fri Dec 18, 2015 10:49 am

Impressive work :D I made use of the older deprecated version but this is awesome hands down! Now Testing!
 
geraneto
just joined
Posts: 3
Joined: Sat Dec 19, 2015 2:27 am

Re: C# API - tik4net on GitHub

Sat Dec 19, 2015 2:32 am

good evening...
Must capture all connections from an IP address /ip/firewall/connections/print where src-address ~192.168.2.2 . How could perform it? thank you
 
geraneto
just joined
Posts: 3
Joined: Sat Dec 19, 2015 2:27 am

Re: C# API - tik4net on GitHub

Mon Dec 21, 2015 1:21 am

good evening...
I can not run /IP/firewall/connection/print where src-address ~ "192.168.2.2".
I need to capture the dst -address.

Obrigado .
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Mon Dec 21, 2015 8:50 pm

Hi,

there are many ways how to handle this task:
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
{
  connection.Open(HOST, USER, PASS);
1) Via direct API call (low-level access):
  string[] command = new string[]
  {
    "/ip/firewall/connection/print",
    "?src-address=192.168.3.103"
  };
  var result = connection.CallCommandSync(command);
2) Via ADO.NET like API:
  var command = connection.CreateCommandAndParameters("/ip/firewall/connection/print",
    "src-address", "192.168.3.103");
  var result = command.ExecuteList();
3) Via highlevel O/R mapper like API:
  // This class will be part of the next release, but you can just put it in your code
    [TikEntity("ip/firewall/connection")]
    public class FirewallConnection
    {
        [TikProperty(".id", IsReadOnly = true, IsMandatory = true)]
        public string Id { get; private set; }

        [TikProperty("connection-mark", IsReadOnly = true)]
        public string ConnectionMark { get; private set; }

        [TikProperty("connection-type", IsReadOnly = true)]
        public string ConnectionType { get; private set; }

        [TikProperty("dst-address", IsReadOnly = true)]
        public string DstAddress { get; private set; }

        [TikProperty("protocol", IsReadOnly = true)]
        public string Protocol { get; private set; }

        [TikProperty("src-address", IsReadOnly = true)]
        public string SrcAddress { get; private set; }

        [TikProperty("tcp-state", IsReadOnly = true)]
        public string TcpState { get; private set; }

        [TikProperty("timeout", IsReadOnly = true)]
        public string Timeout { get; private set; }
    }

  // And the code:
  using tik4net.Objects;
  ...
  var result = connection. LoadList<FirewallConnection>(
    connection.CreateParameter("src-address", "192.168.3.103"));
4) You can skip filtering part, select all connection items and filter them via C# code (LINQ?). Slow, but simple...

Enjoy,
D
 
geraneto
just joined
Posts: 3
Joined: Sat Dec 19, 2015 2:27 am

Re: C# API - tik4net on GitHub

Tue Dec 22, 2015 12:53 pm

good Morning...
I performed a test as follows

using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
{
connection.Open(HOST, USER, PASS);
var command = connection.CreateCommandAndParameters("/ip/firewall/connection/print","src-address","192.168.3.69");
var result = command.ExecuteList();

foreach (var c in result)
{
listBox1.Items.Add(c);
}
}

however I have no result
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Tue Dec 22, 2015 6:55 pm

Probably there is no active connection from ip 192.168.3.69 to router (or connection tracking is switched off in mikrotik configuration).

Try to load all connections without filter:
var command = connection.CreateCommandAndParameters("/ip/firewall/connection/print"); 
var result = command.ExecuteList();
Enjoy,
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Jan 01, 2016 8:21 pm

Released new version 1.5.0.0.

Whats new:
* TikListMerge ferature - see https://github.com/danikf/tik4net/wiki/TikListMerge
* FirewallConnection.ConnectionTracking entity
* Bug fixies

Enjoy,
D
 
tmak
just joined
Posts: 7
Joined: Mon Jan 25, 2010 3:07 pm

Re: C# API - tik4net on GitHub

Wed Jan 27, 2016 1:06 pm

Hi danikf
Good work man, Thanks for sharing it.
I am using your dll in vb.net project, can you explain how to set ?#operations by CreateCommandAndParameters to applies operations to the values in the stack.
Example to execute this query.
/interface/print
?type=ether
?type=vlan
?#|
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Thu Jan 28, 2016 10:27 am

Hi,
I have just updated github sources (update will be part of the next release). With updated version you can simply format command text with filter.

Untyped version:
            var cmd = Connection.CreateCommandAndParameters(@"/interface/print
                            ?type=ether
                            ?type=wlan
                            ?#|");
            var list = cmd.ExecuteList();
Strong-typed version
            var cmd = Connection.CreateCommandAndParameters(@"/interface/print
                            ?type=ether
                            ?type=wlan
                            ?#|");
            var list = cmd.LoadList<Interface>();
The main reasson why parameters stack is not supported is that it will bring high complexity into API (expression trees?). So, I will decide (for this time) not to support this construction via parameters (may be in the future).

Enjoy,
D
 
tmak
just joined
Posts: 7
Joined: Mon Jan 25, 2010 3:07 pm

Re: C# API - tik4net on GitHub

Fri Jan 29, 2016 1:17 am

Thanks, for the fast update.
 
tmak
just joined
Posts: 7
Joined: Mon Jan 25, 2010 3:07 pm

Re: C# API - tik4net on GitHub

Sun Jan 31, 2016 11:48 am

Hi,
Can you add Bridge Filter object in next update to manipulate Bridge Filter Rules just like we can do on high level of Firewall Filters with your code.
Thanks
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Tue Feb 02, 2016 12:04 am

I have committed Alpha version of Bridge entities to GitHub. I'll appreciate your feed-back.
            var filter = new InterfaceBridge.BridgeFilter()
            {
                Chain = InterfaceBridge.BridgeFilter.ChainType.Forward,
                Action = InterfaceBridge.BridgeFilter.ActionType.Accept,
            };
            Connection.Save(filter);
You can still create your own classes and use them with my extension methods (see post abbove). Just use the right attributes ...

Enjoy,
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Tue Feb 02, 2016 8:10 pm

Published new version 1.6.0.0

Whats new:
* Added support for formated commands
* Added Bridge entities (InterfaceBridge, BridgeNat, BridgeFilter)
            var nat = new InterfaceBridge.BridgeNat()
            {
                Chain = InterfaceBridge.BridgeFirewallBase.ChainType.Forward,
                Action = InterfaceBridge.BridgeNat.ActionType.Accept,
            };
            Connection.Save(nat);
Enjoy,
D
 
tmak
just joined
Posts: 7
Joined: Mon Jan 25, 2010 3:07 pm

Re: C# API - tik4net on GitHub

Wed Feb 03, 2016 1:18 pm

Hi Daniel Frantik,

I am using your dll in VB.net project to edit bridge filters in ROS by API. New update is also working fine,

It make easy my work. Please add some more examples in VB about new future you add in your project. It will make working easy for new persons.

Thanks.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Feb 05, 2016 11:11 pm

api-ssl support added (github sources).
https://github.com/danikf/tik4net/wiki/SSL-connection
    using (var conection = ConnectionFactory.OpenConnection(TikConnectionType.ApiSsl, host, user, pass))
    {
      // do something usefull
    }
Looking for betatesters !!!

Enjoy,
D
 
meizoel
just joined
Posts: 7
Joined: Thu Feb 18, 2016 7:31 am

Re: C# API - tik4net on GitHub

Thu Feb 18, 2016 7:36 am

Hai dani :D

i have test your tik4net and i have add and modified some object on tik4net object..

btw i have success implement n reference it on my visual studio project 2012 for desktop and web c#...
the software created by me using tik4net dll has running from 1 februari 2015...

but i have some question can you sent me your email and if you give me some permission to upload tik4net modify i will upload it to tik4net github but of course i need your permisiion :D...
api-ssl support added (github sources).
https://github.com/danikf/tik4net/wiki/SSL-connection
    using (var conection = ConnectionFactory.OpenConnection(TikConnectionType.ApiSsl, host, user, pass))
    {
      // do something usefull
    }
Looking for betatesters !!!

Enjoy,
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Thu Feb 18, 2016 12:26 pm

Hi,

your help would be welcome.

1) Fork projekt on github
2) Do some changes & commit them
3) Send pull request

See https://guides.github.com/activities/co ... en-source/

D
 
meizoel
just joined
Posts: 7
Joined: Thu Feb 18, 2016 7:31 am

Re: C# API - tik4net on GitHub

Thu Feb 18, 2016 2:30 pm

Hi,

your help would be welcome.

1) Fork projekt on github
2) Do some changes & commit them
3) Send pull request

See https://guides.github.com/activities/co ... en-source/

D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Thu Feb 18, 2016 3:27 pm

Released new version 1.8.0.0.

Whats new:
* API-SSL support (alpha)
* Additional hotspot classes (credits: D-Bullock)
* Mikrotik time helper class (credits: D-Bullock)
* nuget support

Enjoy,
D
 
meizoel
just joined
Posts: 7
Joined: Thu Feb 18, 2016 7:31 am

Re: C# API - tik4net on GitHub

Wed Feb 24, 2016 10:23 am

Hai Dany...

i have some trouble installing .dll file of tik4net...

when i running the application with referrence of tik4net.dll on pc with visual studio 2012 there are no error code...
but when i running it on pc without visual studio 2012 there are show error related for tik4net.dll the error message say there are missing dependecy "api-ms-win-core.dll" file for tik4net...

can you help me :D

best regards
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Wed Feb 24, 2016 6:28 pm

Hi,

according to http://stackoverflow.com/questions/1702 ... l-problems - I am expecting that there is some dependency on VS redistributable package in your custom code - not in tik4net ...

tik4net, tik4net.objects references only: mscorlib.dll, system.dll, system.core.dll

I am 100% sure that I am using tik4net in project hosted on computer with WinXp without visual studio at all.

NOTE: do you have installed .NET redistributable on that computer?

D
 
diegotormes
Frequent Visitor
Frequent Visitor
Posts: 64
Joined: Wed Feb 15, 2006 11:45 pm

Re: C# API - tik4net on GitHub

Wed Feb 24, 2016 7:34 pm

Released new version 1.8.0.0.

Whats new:
* API-SSL support (alpha)
* Additional hotspot classes (credits: D-Bullock)
* Mikrotik time helper class (credits: D-Bullock)
* nuget support

Enjoy,
D

Congrats, you guys are doing a great job on this library!

Diego.
 
Spring
just joined
Posts: 17
Joined: Mon Aug 01, 2011 8:14 pm

Re: C# API - tik4net on GitHub

Fri Mar 04, 2016 11:17 am

Hello everyone..!

I'm currently using tik4net 1.8.0 with VB...
I tried to populate all interfaces into a listbox and it's done pretty simple with this:
Dim iface = con.CreateCommand("/interface/print")
Dim show = iface.ExecuteList()
        For Each eth In show
            lb1.Items.Add(eth)
        Next eth
and it returned:

ApiReSentence:.id=*1|name=ether1|type=ether|mtu=1500|dynamic=false|running=true|disabled=false
ApiReSentence:.id=*2|name=ether2|type=ether|mtu=1500|dynamic=false|running=true|disabled=false
ApiReSentence:.id=*3|name=ether3|type=ether|mtu=1500|dynamic=false|running=true|disabled=false


So, how do I view only specific properties, such as; only MTU value or only Type value as simple as in version 0.9.2 where I can use GetStringValueOrNull("xxxx", True) where "xxxx" is the item's name?

anyway, great work danikf.. thank you so much... :)
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Mar 04, 2016 8:46 pm

Hi,

there are many possibilities how to manage it.

If you want to use this ADO like api, you should look at ITikReSentence interface (ExecuteList method returns IEnumerable<ITikReSentence>).

So your code will be (for example):
Dim iface = con.CreateCommand("/interface/print")
Dim show = iface.ExecuteList()
        For Each eth In show
            lb1.Items.Add(eth.GetResponseField("name"))
        Next eth
But I would recommend you to use higlevel API:
using tik4net.Objects;
using tik4net.Objects.Interface;

Dim show = con.LoadAll<Interface>()
        For Each eth In show
            lb1.Items.Add(eth.Name)
        Next eth
Enjoy,
D
 
Spring
just joined
Posts: 17
Joined: Mon Aug 01, 2011 8:14 pm

Re: C# API - tik4net on GitHub

Sat Mar 05, 2016 5:37 am

Both is tested and returned everything I need.. :D

I just need to edit this:
Dim show = con.LoadAll<Interface>()
into:
Dim show = con.LoadAll(Of [Interface])()
your examples saved my time from more deadly googling...
once again, thank you very much, danikf... you rock, man!! :) :)
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Mar 05, 2016 3:06 pm

 
Spring
just joined
Posts: 17
Joined: Mon Aug 01, 2011 8:14 pm

Re: C# API - tik4net on GitHub

Mon Mar 07, 2016 4:29 pm

Hi dani..
more question now.. :)

How do I code this winbox terminal using your libs:
/interface set ether2 name=LAN 
with highlevel API I found a clause "Where" but I never find a way how to use it... :(
and with ADO Like, I have no idea how to pick which interface to be changed using CreateCommand or CreateCommandAndParameters

more examples will be very helpful... ;)
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Tue Mar 08, 2016 1:17 am

Hi,

just load the entity which is representing the eth1 interface, update its property 'Name' and save it via connection.

Naive highevel api code:
var list = Connection.LoadAll<Interface>();
var eth = list.Where(iface => iface.DefaultName == "ether1").Single();
eth.Name = "newName";
Connection.Save(eth);
or use Execute scalar command in mikrotik API notation (see mikrotik wiki page for details: http://wiki.mikrotik.com/wiki/Manual:API)
var cmd = Connection.CreateCommand("/interface/set");
cmd.AddParameter(TikSpecialProperties.Id, "ether1");
cmd.AddParameter("name", "newName");
cmd.ExecuteNonQuery();
Which calls this command to mikrotik:
/interface/set
.id=ether1
name=newName
REMARKS: using names in place of .id is allowed only for some entities.
See http://wiki.mikrotik.com/wiki/API_command_notes.

Enjoy,
D
 
Spring
just joined
Posts: 17
Joined: Mon Aug 01, 2011 8:14 pm

Re: C# API - tik4net on GitHub

Tue Mar 15, 2016 6:38 am

Hi dani...
thx for the last response.. it works.. :)

I'm so sorry because I really not familiar to C# so the github docs was useless for me..

here's another question of mine...
this gave me what I need...
    Public Sub IPread()
        Dim ipList = con.LoadList(Of Ip.IpAddress)().ToArray
        dgvIP.DataSource = ipList

        Me.dgvIP.Columns(3).HeaderText = "Interface"
        Me.dgvIP.Columns(2).HeaderText = "Address"
        Me.dgvIP.Columns(1).Visible = False
        Me.dgvIP.Columns(0).Visible = False
        Me.dgvIP.Columns(4).Visible = False
        Me.dgvIP.Columns(5).Visible = False
        Me.dgvIP.Columns(6).Visible = False
        Me.dgvIP.Columns(7).Visible = False
        Me.dgvIP.Columns(8).Visible = False
        Me.dgvIP.Columns(9).Visible = False
        Me.dgvIP.Columns(10).Visible = False
    End Sub 
... but when I tried to do the same for dns and route, nothing appeared in the dgv or listbox...
Public Sub dnsRead()
Dim dnsList = con.LoadList(Of Ip.IpDns)().ToArray
dgvDNS.DataSource = dnsList
End Sub
or
Public Sub dnsRead()
        Dim dnsList = con.LoadList(Of Ip.IpDns)().ToArray
        For Each dns In dnsList
            lbDNS.Items.Add(dns.Servers)
        Next
End Sub
and for the ip/route... I didnt find it in object.ip so I tried to use con.createcommand(ip/route/print) but I don't know how to put the result into an array so they can be viewed in rows of dgv or listbox...

more help, please.. :)
 
meizoel
just joined
Posts: 7
Joined: Thu Feb 18, 2016 7:31 am

Re: C# API - tik4net on GitHub

Sun May 22, 2016 4:40 pm

Hai Danny,

i have succesfully integration tik4net to my desktop and web application

if you want to see you can cek on this https://youtu.be/UjYQQqzNrjk

btw i have one more question, i want to show interface ethernet to that website , but the rx and tx data must be update every 5 second,,

how to solve this case :D
 
jeroenp
Member Candidate
Member Candidate
Posts: 159
Joined: Mon Mar 17, 2014 11:30 am
Location: Amsterdam
Contact:

Re: C# API - tik4net on GitHub

Tue May 24, 2016 10:15 pm

480p makes it very hard to read. Can you re-render at a higher resolution?

--jeroen
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri May 27, 2016 4:46 pm

Hi,

nice work!

what about using javascript (JQuery?) and loading current RX/TX state per 5 seconds?

D
 
meizoel
just joined
Posts: 7
Joined: Thu Feb 18, 2016 7:31 am

Re: C# API - tik4net on GitHub

Sat May 28, 2016 8:26 am

Hi,

nice work!

what about using javascript (JQuery?) and loading current RX/TX state per 5 seconds?

D
can you show me the code if using from javascript, i have done with the sync command
 string[] command = new string[]
            {
                "/interface/monitor-traffic",
                "=interface=ether5-hotspot",
                "=once="
            };
                    var result = connection.CallCommandSync(command);
but i need it solve with async command , can you help me danniel :D
 
meizoel
just joined
Posts: 7
Joined: Thu Feb 18, 2016 7:31 am

Re: C# API - tik4net on GitHub

Sat May 28, 2016 8:27 am

480p makes it very hard to read. Can you re-render at a higher resolution?

--jeroen
oke next i will create on higher resolution, but it need time..
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat May 28, 2016 12:03 pm

Hi,

easy soulution is to call your code per 5 sec (via JQuery) and show response in web UI.

Or you can use async code and store responses (somehow) in memor. When you do that, you can resturn more than one row to your JQuery request. But you have to be familiar with multithread code.
 List<ITikReSentence> responses = new List<ITikReSentence>();
 // ....
 var cmd = Connection.CreateCommandAndParameters("/interface/monitor-traffic", "interface", "ether1");
 cmd.ExecuteAsync(re => responses.Add(re));
 
 // ....
 cmd.CancelAndJoin(); //stops the interface monitoring
Enjoy,
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat May 28, 2016 12:10 pm

Hi,

easy soulution is to call your code per 5 sec (via JQuery) and show response in web UI.

Or you can use async code and store responses (somehow) in memory (on you application server). When you do that, you can resturn more than one row to your JQuery request. But you have to be familiar with multithread code.
 List<ITikReSentence> responses = new List<ITikReSentence>();
 // ....
 var cmd = Connection.CreateCommandAndParameters("/interface/monitor-traffic", "interface", "ether1");
 cmd.ExecuteAsync(re => responses.Add(re));
 
 // ....
 cmd.CancelAndJoin(); //stops the interface monitoring
Enjoy,
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat May 28, 2016 4:11 pm

I have just published version 2.0.0.0.

Whats new:
* Encoding support
* Refactoring - nested classes removed (breaking change!)
* Bug fixies
* DNS objects added
* Ping object
const string HOST = "127.0.0.1";
const int MAX_CNT = 100;

List<ToolPing> responseList = new List<ToolPing>();
Exception responseException = null;

ITikCommand pingCommand = Connection.LoadAsync<ToolPing>(
  ping => responseList.Add(ping), //read callback
  exception => responseException = exception, //exception callback
  Connection.CreateParameter("address", HOST), Connection.CreateParameter("count", MAX_CNT.ToString()), Connection.CreateParameter("size", "64"));
// ...
Thread.Sleep(3 * 1000);
Connection.Close();
Enjoy,
D
 
meizoel
just joined
Posts: 7
Joined: Thu Feb 18, 2016 7:31 am

Re: C# API - tik4net on GitHub

Sun May 29, 2016 6:29 am

oke dani i will try this ..
Hi,

easy soulution is to call your code per 5 sec (via JQuery) and show response in web UI.

Or you can use async code and store responses (somehow) in memor. When you do that, you can resturn more than one row to your JQuery request. But you have to be familiar with multithread code.
 List<ITikReSentence> responses = new List<ITikReSentence>();
 // ....
 var cmd = Connection.CreateCommandAndParameters("/interface/monitor-traffic", "interface", "ether1");
 cmd.ExecuteAsync(re => responses.Add(re));
 
 // ....
 cmd.CancelAndJoin(); //stops the interface monitoring
Enjoy,
D
btw i have another question how to make this code
 ITikCommand cmdhotspot = conn.CreateCommand("/ip/hotspot/user/disable",
                                   conn.CreateParameter(".id", IserverHotspot._IDUser));
be static function that include on tik4net.objects , so if i want disable hotspot user i only call command like this
var listdisableduserwifi = conn.LoadList<HotspotUser>().Where(p => p.Name == IserverHotspot._NameUser).SingleOrDefault();
 listdisableduserwifi.Disableduser();
and same when i will enabled the hotspot user..

and what should i do for adding userman object to tik4net.object ?
is it add the folder into tik4net.object and add userman.cs , without add some note for tell the visual studio project that i add new object on related project...

thanks for your time dhani , i hope you will answer it...
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Jul 08, 2016 5:46 pm

Hi all,

version 2.1.0.0 (just .NET 4.6 support added) has been published (github/nuget). I will publish binaries in this phorum as soon as the error with attachment upload will be fixed. In this time I just get "HTTP Error". Any idea?

Update 2016-07-16: dlls published (upload has been fixed)

Stay tuned,
D
Last edited by danikf on Sat Jul 16, 2016 11:15 am, edited 1 time in total.
 
kristaps
Member Candidate
Member Candidate
Posts: 272
Joined: Mon Jan 27, 2014 1:37 pm

Re: C# API - tik4net on GitHub

Fri Jul 08, 2016 7:30 pm

We will fix attachment issue. 

Thanks for this API, Keep the good work. 
 
santolag
just joined
Posts: 2
Joined: Thu Jul 21, 2016 8:57 am

Re: C# API - tik4net on GitHub

Wed Jul 27, 2016 8:42 am

Hi,

Great codes,
I'm just here to learn a lot about API via C#
I'm currently trying about PPPoE and stuffs at Firewall,
Any suggestion where to start the code or tricks?

Thanks,
Martin
 
klhsu
just joined
Posts: 2
Joined: Wed Nov 30, 2016 5:25 pm

Re: C# API - tik4net on GitHub

Wed Nov 30, 2016 6:03 pm

Hi danikf

At first I like to say thank you for developed this good api for managing routerOS very easily.
I have an issue as following, hope you can help me how to do.

I've created some accounts for VPN user accounts,I write some code for a function to disable ppp user account, I have test in terminal console in my routerOS as
ppp secret set [find name=username] disable=yes
It works fine after command executed in terminal console.

my c# code with tik4net command as bellow:
ITikCommand cmd = connection.CreateCommandAndParameters("/ppp/secret/set find[name=" + username + "] disable=yes"); 
cmd.ExecuteNonQuery();
the username is a variable for ppp user name that I want to disable with.

but the message be shown after execute command : no such command.

Do you have any idea to tell how to perform the command by CreateCommand() method ?

I really appreciate your instructions.

Albert Hsu
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Wed Nov 30, 2016 9:53 pm

API supports query operator only in print command.

http://wiki.mikrotik.com/wiki/Manual:API#Query_word

You could split the getting and setting of secret, e.g.:
// Retrieve the secret.
ITikReSentence secret = conn.CreateCommandAndParameters("/ppp/secret/print", "name", username).ExecuteSingleRow();

// Disable the secret.
conn.CreateCommandAndParameters("/ppp/secret/set", ".id", secret.Words[".id"], "disabled", "true").ExecuteNonQuery();
For multiple secrets:
// Retrieve pptp secrets.
IEnumerable<ITikReSentence> secrets = conn.CreateCommandAndParameters("/ppp/secret/print", "service", "pptp").ExecuteList();

foreach (var secret in secrets)
{
  // Disable the secret.
  conn.CreateCommandAndParameters("/ppp/secret/set", ".id", secret.Words[".id"], "disabled", "true").ExecuteNonQuery();
}
Note that this way your parameter values are separated from the actual commands, which will lead to a more secure application (less vulnerable to command injection).
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun Dec 11, 2016 8:02 pm

Hi all,
just created wiki example page for all CRUD scenarios for all APIs.

https://github.com/danikf/tik4net/wiki/ ... r-all-APIs

In hope you can see the flexibility of higlevel API,
D

BTW: thanks nescafe2002 for supporting other users :-)
 
anishpsla
Frequent Visitor
Frequent Visitor
Posts: 74
Joined: Mon Aug 25, 2014 9:16 am

Re: C# API - tik4net on GitHub

Wed Jan 18, 2017 6:39 pm

Any information of adding .net core support ?
 
mveselic
just joined
Posts: 8
Joined: Sun Jan 29, 2017 9:14 am

Re: C# API - tik4net on GitHub

Sun Jan 29, 2017 9:17 am

is it possible to send sms messages via this API?
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun Feb 05, 2017 3:55 pm

Hi,
probably yes - in general. You can perform every operation which you can script in mikrotik API :-) I don't have GSM modem connected to mikrotik so I can't test it.

The code could be (not tested):
ITikCommand smsCmd = connection.CreateCommand("/tool/sms/send", 
    connection.CreateParameter("port", "usb3"), 
    connection.CreateParameter("channel", "3"), 
    connection.CreateParameter("phone-number", "00420777123456"), // or "dst" instead of "phone-number" - depends on tik version ???
    connection.CreateParameter("message", "Test message.")    
);
smsCmd.ExecuteNonQuery();
SMS documentation (warning - it is documentation for console, not for API - syntax will be a little bit different):
http://wiki.mikrotik.com/wiki/Manual:Tools/Sms

Other usefull links:
https://aacable.wordpress.com/2012/11/2 ... gsm-modem/
http://forum.mikrotik.com/viewtopic.php ... it=sms+api


Remarks: you have to install advanced-tools package and have gsm modem connected to mikrotik.

Let me know if it works,
D
 
MarkLFT
just joined
Posts: 22
Joined: Mon Apr 23, 2012 7:22 am

Re: C# API - tik4net on GitHub

Tue Feb 28, 2017 6:23 am

I have come across a problem, and would like some advice. We have been using this API for a while, and it is very useful. The problem I have is when we create hotspot users, some of the users names or passwords include non Latin characters, i.e. umlauts etc. Our software stores these names correctly, but when we try to send the name to the router, it seems to arrive as a /?

How can we send the correct characters to the router? As a number of users complain the hotspot is not working, but actually it is because their name contains non-Latin characters.

Many thanks, and keep up the good work.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Tue Feb 28, 2017 2:36 pm

Hi,
take a look at connection.Encoding parameter of connection.

See https://github.com/danikf/tik4net/wiki/ ... characters for details.

D
 
lucianozem
just joined
Posts: 2
Joined: Wed Mar 08, 2017 3:32 pm

Re: C# API - tik4net on GitHub

Wed Mar 08, 2017 4:06 pm

Hi danikf,

I wold like to verify the traffic packets in the router, more specifically the RTP protocol. Can i do this?
and the another question, can i connect two routers in same time?
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Mar 10, 2017 12:31 pm

Hi,

RTP is usualy based on UDP - so you can monitor the traffic (see tik4net.torch example project: https://github.com/danikf/tik4net/tree/ ... 4net.torch). If you want to examine every packet (sniffer?), may be you can use sniffer feature, but it will be IMHO very bad idea. It will be better to use mikrotik sniffer streaming feature (without API). Basically - you can do every operation with this API which you can perform via pure API calls :-)

To connect two routers at the same time just create two ITikConnection connections.

D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Apr 01, 2017 4:21 pm

Hi,

just published new version 2.2.0.0 of tik4net library.

Whats new:
* API update to meet CRUD examples
* multiline response (script) fix. Credits: pmishka
* Adding CapsManRegistrationTable entity and support TimeSpan convertion. Credits: sebastienwarin

Updates for .NET Core will be (hopefully) in the next release.

Enjoy,
D
 
Centauri
Frequent Visitor
Frequent Visitor
Posts: 50
Joined: Sun Jun 06, 2010 8:51 pm

Re: C# API - tik4net on GitHub

Thu Apr 06, 2017 10:58 pm

Any chances that ther would come a VB.NET example on how to use the DLL.
I have worked with it for some time now without any luck.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Thu Apr 06, 2017 11:26 pm

What about using some online converter?

This is result of http://converter.telerik.com/ converter for projects root page examples:

1) Add references:
* tik4net.dll
* tik4net.objects.dll

2) Try to modify this example:
Imports tik4net
Imports tik4net.Objects
Imports tik4net.Objects.Ip.Firewall

Namespace Test
	Public Class MyTest
		Public Sub TestMikrotik()	
			Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
				connection.Open(HOST, USER, PASS)

				Dim cmd As ITikCommand = connection.CreateCommand("/system/identity/print")
				Dim identity = cmd.ExecuteScalar()
				Console.WriteLine("Identity: {0}", identity)

				Dim logs = connection.LoadList(Of Log)()
				For Each log As Log In logs
					Console.WriteLine("{0}[{1}]: {2}", log.Time, log.Topics, log.Message)
				Next

				Dim fwf = New FirewallFilter() With { _
					.Chain = FirewallFilter.ChainType.Forward, _
					.Action = FirewallFilter.ActionType.Accept _
				}
				connection.Save(fwf)
			End Using
		End Sub
	End Class
End Namespace
UPDATE: fixed as recommended bellow.

D
Last edited by danikf on Sun Apr 09, 2017 10:11 pm, edited 3 times in total.
 
Centauri
Frequent Visitor
Frequent Visitor
Posts: 50
Joined: Sun Jun 06, 2010 8:51 pm

Re: C# API - tik4net on GitHub

Sun Apr 09, 2017 11:52 am

have newer have much luck with such converts.
It also gives some errors withe the lines

Dim logs = connection.LoadList(Of Log)()
Error BC30456 'LoadList' is not a member of 'ITikConnection'.

Dim firewallFilter = New FirewallFilter() With {
Error BC30002 Type 'FirewallFilter' is not defined.

connection.Save(firewallFilter)
Error BC30456 'Save' is not a member of 'ITikConnection'.

I just need to make a simple program to read all users for userman and be able to create new users.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun Apr 09, 2017 3:49 pm

Hi,

you must reference tik4net.objects.dll and import (use) namespace with tik4net extensions. I've updated previous example to full example class.

Hope it helps,
D
 
Centauri
Frequent Visitor
Frequent Visitor
Posts: 50
Joined: Sun Jun 06, 2010 8:51 pm

Re: C# API - tik4net on GitHub

Sun Apr 09, 2017 9:14 pm

It all most works
.
Key.Chain = firewallFilter.ChainType.Forward,
Error BC30451 'Key' is not declared. It may be inaccessible due to its protection level.
Error BC30980 Type of 'firewallFilter' cannot be inferred from an expression containing 'firewallFilter'.

Just in case you want to update yor code, can see you also have posted it on your Wiki

But all i need is to be able to get the user and profile list for
tool/user-manager/user/print
tool/user-manager/profile/print

I have managed to do it with the following code, don't know if its the best way to do it but it works the i just have to filter out the informations i need like id username and password.
Just in case others could make use if it.
Imports tik4net
Imports tik4net.Objects


Namespace Test
   Public Class MyTest
      Public Sub TestMikrotik()   
         Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
            connection.Open(HOST, USER, PASS)

            Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/tool/user-manager/user/print")
            Dim results = cmd.ExecuteList()

            For Each users In results
                Console.WriteLine(users)
            Next users

         End Using
      End Sub
   End Class
End Namespace
 
clarksheng
just joined
Posts: 5
Joined: Sat Sep 29, 2012 12:07 am

Re: C# API - tik4net on GitHub

Tue Apr 11, 2017 10:05 am

HI got 2 problems with tik4net.
1. I generated new entity at "/ip/hotspot/profiles/print" by entitygenerator, but tik4net keeps telling me unknow command.
the following is the newly generated entity,
        
        /// <summary>
        /// /ip/hotspot/profile/print: 
        /// </summary>
        [TikEntity("/ip/hotspot/profile/print")]
        public class ServerProfile
        {
            /// <summary>
            /// .tag: 
            /// </summary>
            [TikProperty(".tag")]
            public long Tag { get; set; }

            /// <summary>
            /// .id: 
            /// </summary>
            [TikProperty(".id", IsReadOnly = true, IsMandatory = true)]
            public string Id { get; private set; }

            /// <summary>
            /// name: 
            /// </summary>
            [TikProperty("name", IsMandatory = true)]
            public string Name { get; set; }

            /// <summary>
            /// hotspot-address: 
            /// </summary>
            [TikProperty("hotspot-address")]
            public string HotspotAddress { get; set; }

            /// <summary>
            /// html-directory: 
            /// </summary>
            [TikProperty("html-directory")]
            public string HtmlDirectory { get; set; }

            /// <summary>
            /// http-proxy: 
            /// </summary>
            [TikProperty("http-proxy")]
            public string HttpProxy { get; set; }

            /// <summary>
            /// smtp-server: 
            /// </summary>
            [TikProperty("smtp-server")]
            public string SmtpServer { get; set; }

            /// <summary>
            /// login-by: 
            /// </summary>
            [TikProperty("login-by")]
            public string LoginBy { get; set; }

            /// <summary>
            /// split-user-domain: 
            /// </summary>
            [TikProperty("split-user-domain")]
            public bool SplitUserDomain { get; set; }

            /// <summary>
            /// use-radius: 
            /// </summary>
            [TikProperty("use-radius")]
            public bool UseRadius { get; set; }

            /// <summary>
            /// default: 
            /// </summary>
            [TikProperty("default")]
            public bool Default { get; set; }

        }
2. With the above new entity doesn't work, I try to use the command to edit hotspot server profile by the following code:
            ITikCommand cmd = connection.CreateCommand("/ip/hotspot/profile/edit");
            cmd.AddParameter(TikSpecialProperties.Id, "0");
            cmd.AddParameter("name", "helloworld");
            cmd.ExecuteNonQuery();
however, tik4net keeps telling me unknow parameters.
Please help with either one, personally thinking the second problem is related to ".id" or "number" which I don't know what I should use as correct parameter. Thanks.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Tue Apr 11, 2017 10:25 pm

Hi,

ad 1:
Please remove "/print" sufix -> [TikEntity("/ip/hotspot/profile")]
See https://github.com/danikf/tik4net/wiki/ ... m-entities for details.

ad 2:
You have to use .id property in format "*A"
See https://github.com/danikf/tik4net/wiki/ ... e-entities for details.

You have to know .id of the row to edit. You can read it via some kind of load (with/without filter).
See https://github.com/danikf/tik4net/wiki/ ... d-entities
Or nescafe2002's aswer (above this post): viewtopic.php?f=9&t=99954&start=50#p570685

Note: for some entities it is possible to use "name" in position of ".id", but not in this case. Numbers are not supported by API at all. For example of this usage see Eth1 test in tik4net.test project:
https://github.com/danikf/tik4net/blob/ ... aceTest.cs

Enjoy,
D
 
Centauri
Frequent Visitor
Frequent Visitor
Posts: 50
Joined: Sun Jun 06, 2010 8:51 pm

Re: C# API - tik4net on GitHub

Sat Apr 15, 2017 12:48 am

Hi i have a problem with the API and creating parameters.

When i do it manuel via the command line i use
tool user-manager user add customer= admin username="test007" password="nigher"
tool user-manager user create-and-activate-profile test007 profile=Always customer=admin

Via the API i can create the user with the following
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/tool/user-manager/user/add", "customer", "admin", "username", "test007", "password", "12345678")
cmd.ExecuteNonQuery()
But i have a problem setting the Profile since the API expect a parameter name but the command have no name like username when i create the user the first thing i have to enter her in the actual username and the API dosent support a blank parameter name like this.
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/tool/user-manager/user/create-and-activate-profile", "", "test007", "profile", "Always", "customer", "admin")
cmd.ExecuteNonQuery()
Any idea how i cn solve that ?
 
neoprogger
just joined
Posts: 15
Joined: Tue May 10, 2016 7:55 pm

Re: C# API - tik4net on GitHub

Thu Apr 20, 2017 4:36 pm

Hi,
Thanks for your Project.
Whenever I try to add a mac-based-vlan rule I can see the new rule, but every value is populated with 0.

Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/interface/ethernet/switch/mac-based-vlan/add", "src-mac-address=112233445566", "new-customer-vid=15")
same with
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/interface/ethernet/switch/mac-based-vlan/add", "src-mac-address=11:22:33:44:55:66", "new-customer-vid=14")
and with
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/interface/ethernet/switch/mac-based-vlan/add","src-mac-address=11:22:33:44:55:66" "new-customer-vid", "15")

What is my fault?

Thanks

Alex
 
Centauri
Frequent Visitor
Frequent Visitor
Posts: 50
Joined: Sun Jun 06, 2010 8:51 pm

Re: C# API - tik4net on GitHub

Sat Apr 22, 2017 3:53 pm

Try this
Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/interface/ethernet/switch/mac-based-vlan/add", "src-mac-address","11:22:33:44:55:66", "new-customer-vid","14")
 
irghost
Member
Member
Posts: 300
Joined: Sun Feb 21, 2016 1:49 pm

Re: C# API - tik4net on GitHub

Tue Jun 27, 2017 9:48 am

Hi all
I'm looking for something that's helps me with "/PPP active"
with High Level
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Tue Jun 27, 2017 10:47 am

Please follow instructions on https://github.com/danikf/tik4net/wiki/ ... I-entities

Example:
void Main()
{
  using (var conn = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", "mypassword"))
  {
    var list = conn.LoadAll<PppActive>();
  }
}

[TikEntity("/ppp/active", IncludeDetails = true)]
public class PppActive
{
  [TikProperty(".id")]
  public string Id { get; private set; }

  [TikProperty("name")]
  public string Name { get; private set; }

  [TikProperty("service")]
  public string Service { get; private set; }

  [TikProperty("caller-id")]
  public string CallerId { get; private set; }

  [TikProperty("address")]
  public string Address { get; private set; }

  [TikProperty("uptime")]
  public string Uptime { get; private set; }

  [TikProperty("encoding")]
  public string Encoding { get; private set; }

  [TikProperty("session-id")]
  public string SessionId { get; private set; }

  [TikProperty("limit-bytes-in")]
  public int LimitBytesIn { get; private set; }

  [TikProperty("limit-bytes-out")]
  public int LimitBytesOut { get; private set; }

  [TikProperty("radius")]
  public bool Radius { get; private set; }
}
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Dec 30, 2017 5:23 pm

I have just published version 3.0.0

Whats new:
* BETA: Support for NetCoreApp and NetStandard (functional with Xamarin on Android devices etc.)
* Some bug fixies and updates

Enjoy,
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Tue Jan 02, 2018 6:46 pm

Just published 3.0.1 version on nuget (*.zip is too large for this site).

Whats new:
*.xml documentation for visual studio.
 
MarkLFT
just joined
Posts: 22
Joined: Mon Apr 23, 2012 7:22 am

Re: C# API - tik4net on GitHub

Mon Mar 05, 2018 12:44 pm

I have found this library to very helpful, we use the hotspot features a lot. But we are now looking to expand to use User Manager, do you have any plans to allow users and profiles etc. to be created using objects the same at the Hotspot users.

I have been tasked with setting up a MUM server for different departments to use, so each dept will have their own set of users and profiles. Although I am not 100% certain that is possible.

Many thanks and keep up the good work.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun Apr 01, 2018 11:36 am

Hi Mark,
tik4net is just API - it allows you to perform all operations you are able to do with mikrotik API (and almost 100% operations you could achieve with mikrotik console). If you are missing some highlevel objects, you could ask someone/me for creating them or you could create classes by yourself. See wiki links how to do it:
https://github.com/danikf/tik4net/wiki/ ... I-entities
https://github.com/danikf/tik4net/wiki/ ... m-entities

I am not super expert in mikrotik, so your question should be answered by someone else :-)

Enjoy,
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun Apr 01, 2018 6:13 pm

Hi,
version 3.1.0.0 published.

Whats new:
* XML documentation embeded also in *.zip
* Connection open timeout support
* WOL support
* small improovements

Enjoy,
D
 
User avatar
az1984
newbie
Posts: 28
Joined: Thu Sep 14, 2017 3:58 pm
Location: Germany

Re: C# API - tik4net on GitHub

Thu Apr 26, 2018 10:16 am

First of all: Great work!

I just started to play around with tik4net and C#, but I got a little trouble.

If I use your examples and create a WindowsConsoleApplication everything works as it should. Problems are starting when I try to do the same within a WindowsFormApplication. I use exactly the same code and paste it within action for a button on a form:
private void button1_Click(object sender, EventArgs e)
        {
            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
            {
                connection.Open("192.168.77.xxx", "admin", "pass");

                ITikCommand certcmd = connection.CreateCommand("/certificate/add",
                    connection.CreateParameter("name", "test"),
                    connection.CreateParameter("common-name", "test.com"),
                    connection.CreateParameter("key-size", "2048"),
                    connection.CreateParameter("key-usage", "crl-sign,key-cert-sign"),
                    connection.CreateParameter("days-valid", "365"));
                
                certcmd.ExecuteAsync(response =>
                {
                    Console.WriteLine(response.GetResponseField(""));
                });
                Console.WriteLine("Certificate created - press ENTER");
                Console.ReadLine();
            }
        }
If I run my application now, I got an "Exception not handled error" saying no connection possible.

Guess I need some help here.
 
hardwarematik
just joined
Posts: 3
Joined: Thu May 03, 2018 12:26 am

Re: C# API - tik4net on GitHub

Tue May 08, 2018 12:39 am

First of all: Great work!

I just started to play around with tik4net and C#, but I got a little trouble.

If I use your examples and create a WindowsConsoleApplication everything works as it should. Problems are starting when I try to do the same within a WindowsFormApplication. I use exactly the same code and paste it within action for a button on a form:
private void button1_Click(object sender, EventArgs e)
        {
            using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api))
            {
                connection.Open("192.168.77.xxx", "admin", "pass");

                ITikCommand certcmd = connection.CreateCommand("/certificate/add",
                    connection.CreateParameter("name", "test"),
                    connection.CreateParameter("common-name", "test.com"),
                    connection.CreateParameter("key-size", "2048"),
                    connection.CreateParameter("key-usage", "crl-sign,key-cert-sign"),
                    connection.CreateParameter("days-valid", "365"));
                
                certcmd.ExecuteAsync(response =>
                {
                    Console.WriteLine(response.GetResponseField(""));
                });
                Console.WriteLine("Certificate created - press ENTER");
                Console.ReadLine();
            }
        }
If I run my application now, I got an "Exception not handled error" saying no connection possible.

Guess I need some help here.
Hi I had same problem than and I solve deleteing the tik4net 3.10 unit on Visual Studio (Nuget) and installing 3.0.1 and works fine, for some errors maybe 3.10 the last at this moment have this error of timeout still no solve at least for me on Mikrotik 5.20, using Api port NOT ApiSSL port. I hope to help you
 
User avatar
saputra19
just joined
Posts: 9
Joined: Fri Mar 23, 2018 3:11 pm
Location: indonesia
Contact:

Re: C# API - tik4net on GitHub

Mon May 21, 2018 4:54 pm

Hi Danikf
how to perform command below?
/ip hotspot user profile delete [find name=BLABLABLA]

its work perfectly in terminal, but when i am use it in vb.net, it says " no such command"
I really appreciate your instructions
 
User avatar
saputra19
just joined
Posts: 9
Joined: Fri Mar 23, 2018 3:11 pm
Location: indonesia
Contact:

Re: C# API - tik4net on GitHub

Wed May 23, 2018 4:48 pm

Hi Danikf
how to perform command below?
/ip hotspot user profile delete [find name=BLABLABLA]

its work perfectly in terminal, but when i am use it in vb.net, it says " no such command"
I really appreciate your instructions
hi
i have found solution about my question, this is my code on vb.net and its work perfectly
Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
            connection.Open(Form2.HostTB.Text, Form2.LoginTB.Text, Form2.PassTB.Text)
            Dim cmd As ITikCommand = connection.CreateCommandAndParameters("/ip/hotspot/user/profile/remove")
            cmd.AddParameter(TikSpecialProperties.Id, CBdelprof.Text)
            cmd.ExecuteNonQuery()
            MessageBox.Show("Profile Deleted")
now, i have problem with counting expired users. this code work in terminal
/ip hotspot user print count-only where comment=expired.user
how to perform this command in tik4net?
thanks
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Jun 30, 2018 3:01 pm

It is API related question :-)

The naive way (without using count-only) could be something like:
connection.LoadAll<UserProfile>().Where(u=>u.Comment="expired.user").Count();
D
Last edited by danikf on Sat Jul 07, 2018 2:34 pm, edited 2 times in total.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Jul 06, 2018 12:32 am

Hi,

new version 3.2.0.0 was released.

Whats new:
* Connection.Open fixed (mentioned by az1984, hardwarematik)
* New 6.43 login process supported (credits:DaveSchmid)

D
 
ww1977
just joined
Posts: 1
Joined: Wed Jul 25, 2018 8:02 am

Re: C# API - tik4net on GitHub

Wed Jul 25, 2018 8:11 am

Hi
On the device, the API port is changed from the standard 8728 to the other. How do I specify the port when connecting?
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Wed Jul 25, 2018 9:18 pm

Use ConnectionFactory.OpenConnection/connection.Open method overload with port.
connection.Open(HOST, PORT, USER, PASS);
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Aug 10, 2018 6:24 pm

Question (posted as Github issue):
To obtain the Rx and Tx values ​​of the interface, in which way it is done, thank you in advance.
Answer:
var ethIface = Connection.LoadSingle<Interface>(Connection.CreateParameter("name", "ether1"));
var rx = ethIface.RxByte;
D
 
hreynaldoh
just joined
Posts: 1
Joined: Wed Aug 08, 2018 3:40 am

Re: C# API - tik4net on GitHub

Sun Aug 12, 2018 3:40 am

Question (posted as Github issue):
To obtain the Rx and Tx values ​​of the interface, in which way it is done, thank you in advance.
Answer:
var ethIface = Connection.LoadSingle<Interface>(Connection.CreateParameter("name", "ether1"));
var rx = ethIface.RxByte;
D
Rx o Tx in real time of each interfcace not RxByte of interface?
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun Aug 12, 2018 2:14 pm

Hi,
you can wait for next release or use this code (taken from its code base).

D
        /// <summary>
        /// Gets snapshot of actual traffic RX/TX values for given <paramref name="interfaceName"/>.
        /// </summary>
        public static InterfaceMonitorTraffic GetInterfaceMonitorTrafficSnapshot(ITikConnection connection, string interfaceName)
        {
            var cmd = connection.CreateCommand("/interface/monitor-traffic",
                connection.CreateParameter("interface", interfaceName, TikCommandParameterFormat.NameValue),
                connection.CreateParameter("once", "", TikCommandParameterFormat.NameValue));
            var result = cmd.LoadList<InterfaceMonitorTraffic>().Single();

            return result;
        }
     
And the InterfaceMonitorTraffic class:

    /// <summary>
    /// /interface/monitor-traffic
    /// NOTE: use <see cref="InterfaceMonitorTraffic.GetSnapshot"/> or with some kind of bulk/async load
    /// </summary>
    [TikEntity("/interface", IncludeDetails = true, IsReadOnly = true)]
    public class InterfaceMonitorTraffic
    {
        /// <summary>
        /// name
        /// </summary>
        [TikProperty("name", IsMandatory = true, IsReadOnly = true)]
        public string Name { get; private set; }

        /// <summary>
        /// rx-packets-per-second
        /// </summary>
        [TikProperty("rx-packets-per-second", IsMandatory = true, IsReadOnly = true)]
        public string RxPacketsPerSecond { get; private set; }

        /// <summary>
        /// rx-bits-per-second
        /// </summary>
        [TikProperty("rx-bits-per-second", IsMandatory = true, IsReadOnly = true)]
        public string RxBitsPerSecond { get; private set; }

        /// <summary>
        /// rx-drops-per-second
        /// </summary>
        [TikProperty("rx-drops-per-second", IsMandatory = true, IsReadOnly = true)]
        public string RxSropsPerSecond { get; private set; }

        /// <summary>
        /// rx-errors-per-second
        /// </summary>
        [TikProperty("rx-errors-per-second", IsMandatory = true, IsReadOnly = true)]
        public string RxErrorsPerSecond { get; private set; }        

        /// <summary>
        /// tx-packets-per-second
        /// </summary>
        [TikProperty("tx-packets-per-second", IsMandatory = true, IsReadOnly = true)]
        public string TxPacketsPerSecond { get; private set; }

        /// <summary>
        /// tx-bits-per-second
        /// </summary>
        [TikProperty("tx-bits-per-second", IsMandatory = true, IsReadOnly = true)]
        public string TxBitsPerSecond { get; private set; }

        /// <summary>
        /// tx-drops-per-second
        /// </summary>
        [TikProperty("tx-drops-per-second", IsMandatory = true, IsReadOnly = true)]
        public string TxSropsPerSecond { get; private set; }

        /// <summary>
        /// tx-errors-per-second
        /// </summary>
        [TikProperty("tx-errors-per-second", IsMandatory = true, IsReadOnly = true)]
        public string TxErrorsPerSecond { get; private set; }
    }
 
User avatar
saputra19
just joined
Posts: 9
Joined: Fri Mar 23, 2018 3:11 pm
Location: indonesia
Contact:

Re: C# API - tik4net on GitHub

Fri Aug 31, 2018 2:56 pm

hi daniel,
can you add loadlist of ppp
-ppp active
-ppp profile
-ppp secret

like hotspot command
connection.LoadList(Of HotspotUser)()
its very easy to use. Hope you can add for ppp

thank you very much

P.S i am using vb.net
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Sep 01, 2018 11:17 pm

 
User avatar
saputra19
just joined
Posts: 9
Joined: Fri Mar 23, 2018 3:11 pm
Location: indonesia
Contact:

Re: C# API - tik4net on GitHub

Mon Sep 03, 2018 10:26 am

:D :D :D :D thank you !!!!
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Mon Sep 03, 2018 7:40 pm

Hi,

new version 3.3.0 released. Upgrade is recommended!

Whats new:
  • Support for own tag sent to sync commands in commandText
  • Native support for entities loaded in different way than /print
  • Connection.LoadByName extension
  • Connection extension methods for entity static methods
  • Connection .ExecuteNonQuery, .ExecuteScalar extensions
  • ApiCommand onDoneCallback for LoadAsync
  • Connection.SendTagWithSyncCommand option
New classes:
  • InterfaceMonitorTraffic
  • WirelessChannels, WirelessSniffer ( (c) AsafMag)
  • PPP objects
Fixed:
  • Exception from conncetion.Close
  • Typo in InterfaceWireless
  • Correct behavior when connection was forced to close
  • Parallel async commands cancel fix
Enjoy,
D
 
User avatar
saputra19
just joined
Posts: 9
Joined: Fri Mar 23, 2018 3:11 pm
Location: indonesia
Contact:

Re: C# API - tik4net on GitHub

Sat Sep 22, 2018 2:13 pm

Hi daniel
thanks for upgrade. its awesome!!
but i got some problem in InterfaceMonitorTraffic object. If i use this object to RB 750Gr3, it says "Missing Word with name rx-drops-per-second". but working excellent in RB951Ui-2nD.
and this SS of interface monitor on terminal were 750Gr3 not contains rx-drops-per-second
https://ibb.co/nyY9K9

what should i do?
thanks
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun Sep 23, 2018 3:51 pm

Hi,
fixed in dev branch: https://github.com/danikf/tik4net/commi ... ffeea6cb00

You can fix issues like this manually by creating new copy of entity and making some fields optional (IsMandatory=false) or by deleting them. Than just use your type in the same place as original one.

BTW - I believe that it is more likely problem of routeros version than problem of different HW.

D
PS: see this tutorial for custom objects:
https://github.com/danikf/tik4net/wiki/ ... m-entities
https://github.com/danikf/tik4net/wiki/ ... -API-tools
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Wed Sep 26, 2018 9:56 pm

Version 3.4. released.

https://github.com/danikf/tik4net/releases/tag/v3.4

Whats new:
tool/traceroute entity + helpers
tool/ping helpers
Command.ExecuteWithDuration fix
InterfaceMonitorTraffic fix

D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Mon Oct 01, 2018 6:29 pm

of course ...
...
... if you are able to read previous posts ...
var user = new HotspotUser()
{
    Name = "TEST",
    LimitUptime = "1:00:00",
    Password = "secretpass"
};
_connection.Save(user);
 
User avatar
saputra19
just joined
Posts: 9
Joined: Fri Mar 23, 2018 3:11 pm
Location: indonesia
Contact:

Re: C# API - tik4net on GitHub

Thu Oct 04, 2018 12:48 pm

Version 3.4. released.

https://github.com/danikf/tik4net/releases/tag/v3.4

Whats new:
tool/traceroute entity + helpers
tool/ping helpers
Command.ExecuteWithDuration fix
InterfaceMonitorTraffic fix

D
great update!! thank you daniel.
now i have a small request.
can you add ip bindings object?

thank you very much
 
phamthinh2707
just joined
Posts: 5
Joined: Thu Sep 27, 2018 6:04 am

Re: C# API - tik4net on GitHub

Wed Oct 10, 2018 6:55 am

To make the setup process faster I writting c# Winforms Application base on you tik4net API call Mikrotik Controller right now.
When you reset no default the Mikrotik router(951Ui), it IP will become "0.0.0.0".
So there is no other way for me to configure the router via MAC address.
Any solution for me, thank you so much.
 
giguard
newbie
Posts: 35
Joined: Mon Oct 01, 2018 7:10 pm

Re: C# API - tik4net on GitHub

Thu Oct 11, 2018 4:59 pm

Hi,

I really need help on this bit of code.
            ITikCommand printcmd = connection.CreateCommand("/ip/ipsec/remote-peer/print");
            IEnumerable<ITikReSentence> userlist = printcmd.ExecuteList();
Running it will return Exception: 'no such command prefix'

What have I done wrong?
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Thu Oct 11, 2018 5:08 pm

/ip/ipsec/remote-peer is not valid.
/ip/ipsec/remote-peers is.
 
giguard
newbie
Posts: 35
Joined: Mon Oct 01, 2018 7:10 pm

Re: C# API - tik4net on GitHub

Thu Oct 11, 2018 5:34 pm

wow. Of all this time I ran that command without 's'.
Terminal is much more forgiving than API huh? :lol:

Feeling very silly now.
Thank you. You've been a GREAT help. :D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Thu Oct 11, 2018 6:03 pm

now i have a small request.
can you add ip bindings object?
Hi,
what are you meaning by "ip binding object". Is it different from IpAddress object?

D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Thu Oct 11, 2018 6:06 pm

When you reset no default the Mikrotik router(951Ui), it IP will become "0.0.0.0".
So there is no other way for me to configure the router via MAC address.
Hi,
mac-telnet is complicated protocol - I have tried to find some libraries, but without success (.NET libraries :-) ). Not sure, but you can try to manage it by connection to neigbor router and use its mac-telnet function ....
Sorry, but I don't have any better solution ...
D
 
giguard
newbie
Posts: 35
Joined: Mon Oct 01, 2018 7:10 pm

Re: C# API - tik4net on GitHub

Thu Oct 11, 2018 6:25 pm

After that little incident with missing 's', I was humming along just fine.
However, while performing disconnection on one connection made by Android phone program failed and returned Exception.
See below.
Unhandled Exception: tik4net.TikSentenceException: Duplicit key 'port' with deffirent values '4500' vs. '59061'
at tik4net.Api.ApiSentence..ctor(IEnumerable`1 words)
at tik4net.Api.ApiConnection.ReadSentence()
at tik4net.Api.ApiConnection.GetOne(String tag)
at tik4net.Api.ApiConnection.<GetAll>d__60.MoveNext()
at System.Collections.Generic.List`1.AddEnumerable(IEnumerable`1 enumerable)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at tik4net.Api.ApiConnection.CallCommandSync(String[] commandRows)
at tik4net.Api.ApiCommand.ExecuteSingleRow()
First line of the exception talks about 4500 vs 59061
It turns out 4500 is the local port and 59061 is the remote port.
See below.
[admin@<HOST>] > /ip ipsec remote-peers print detail
Flags: R - responder, N - natt-peer
0 RN id="blah" local-address=X.X.X.X port=4500
remote-address=Y.Y.Y.Y port=59061 state=established
side=responder dynamic-address=172.29.58.92 uptime=46s last-seen=46s
Now, What I'm wondering is.. why on earth would this cause exception such as above?
Duplicate key with different value?
So I went back and looked at the ones I was able to disconnect successfully and for those ones two of the local and remote ports were both reading 4500.
See below.
[admin@<HOST>] > /ip ipsec remote-peers print detail
Flags: R - responder, N - natt-peer
0 RN id="blah" local-address=X.X.X.X port=4500
remote-address=Y.Y.Y.Y port=4500 state=established side=responder
uptime=7m20s last-seen=1m19s
Now, I don't think I can do anything about Android phone using different remote port so how should I handle this case from the code?
 
giguard
newbie
Posts: 35
Joined: Mon Oct 01, 2018 7:10 pm

Re: C# API - tik4net on GitHub

Thu Oct 11, 2018 6:28 pm

In case any one wondering what caused that execption,
            ITikReSentence id = connection.CreateCommandAndParameters("/ip/ipsec/remote-peers/print", "id", username).ExecuteSingleRow();
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Thu Oct 11, 2018 6:53 pm

xxxxxxx/print command returns more than one =port=xxxx row in one !re sentence (this behavior was not expected and also not supported).
IMHO problem is, that there are two "port" fields - same name, different values. Works somehow because of their order ...

I would preffer this "stupid" behavior to be fixed by mikrotik guys (e.q. local-port, remote-port), but workaround could be also implemented in tik4net core - It will return port and port2 in this case.

Issue: https://github.com/danikf/tik4net/issues/51
Workarounded in dev branch: https://github.com/danikf/tik4net/commi ... 1cf91e24dd

As workaround (if you don't need port values) you can use .proplist filter (see API specification on mikrotik wiki) to return subset of fields you need.

D
 
giguard
newbie
Posts: 35
Joined: Mon Oct 01, 2018 7:10 pm

Re: C# API - tik4net on GitHub

Fri Oct 12, 2018 9:41 am

Thank you for the workaround. I didn't try the dev version of the api since proplist did the job.
BTW, Is there document on how to go about using the dev version?
Would this be possible with nuget?
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Fri Oct 12, 2018 10:57 am

BTW, Is there document on how to go about using the dev version?
Would this be possible with nuget?
Hi,

just download sources from github (Git clone or *.zip download), reference them as projects and rebuild your application. This scenario is usefull for debuging non-trivial problems and also for understandig how tik4net works inside :-) All code updates (an usually new tik object classes) can be pushed back to the main branch via pull request feature ...

https://help.github.com/articles/cloning-a-repository/

D
 
javierur10
just joined
Posts: 2
Joined: Mon Jun 25, 2018 4:26 pm

Re: C# API - tik4net on GitHub

Mon Oct 15, 2018 6:49 am

Hello, Why this error?

Exception in System.Net.Sockets.SocketException
No connection could be made because the target machine actively refused it 12.12.12.1:8728
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Mon Oct 15, 2018 12:11 pm

Your router is not accepting api connections. Go to IP > Services and check if api is enabled. Also check firewall and add appropriate input rule, e.g.:
/ip firewall filter
add chain=input dst-port=8728 in-interface-list=LAN protocol=tcp src-address=192.168.88.0/24
 
User avatar
saputra19
just joined
Posts: 9
Joined: Fri Mar 23, 2018 3:11 pm
Location: indonesia
Contact:

Re: C# API - tik4net on GitHub

Mon Oct 15, 2018 2:06 pm

now i have a small request.
can you add ip bindings object?
Hi,
what are you meaning by "ip binding object". Is it different from IpAddress object?

D
ip bindings from
ip/hotspot/ip-binding
 
khisrav
just joined
Posts: 3
Joined: Wed Oct 24, 2018 4:14 pm

tik4net, SSL connection exception

Wed Oct 24, 2018 5:18 pm

Hello guys!

First of all, thanks a lot for author for such incredible API library.
Had any one problems with ApiSsl connection? 'TikConnectionType.Api' works fine, but if I try 'TikConnectionType.ApiSsl' I have exception like this:

-------------
System.Security.Authentication.AuthenticationException
HResult=0x80131501
Message=Failed to call SSPI, see the internal exception
Source=tik4net
Arborescence des appels de procédure :
at tik4net.Api.ApiConnection.Open(String host, Int32 port, String user, String password) dans D:\Downloads\tik4net-master\tik4net-master\tik4net\Api\ApiConnection.cs :line 182
at tik4net.Api.ApiConnection.Open(String host, String user, String password) dans D:\Downloads\tik4net-master\tik4net-master\tik4net\Api\ApiConnection.cs :line 148
at tik4net.ConnectionFactory.OpenConnection(TikConnectionType connectionType, String host, String user, String password) dans D:\Downloads\tik4net-master\tik4net-master\tik4net\ConnectionFactory.cs :line 49
at tik4net.tests.ConnectionTest.OpenConnectionWillNotFail() dans D:\Downloads\tik4net-master\tik4net-master\tik4net.tests\ConnectionTest.cs :line 17

Internal exception: The received message was unexpected or incorrectly formatted
-------------

I googled problem and find several solutions, but no one works in my case. Any help will be appreciated. Thanks a lot.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Thu Oct 25, 2018 12:12 pm

Is your mikrotik router properly configured? Which version of routeros do you use?

https://github.com/danikf/tik4net/wiki/SSL-connection

D
 
khisrav
just joined
Posts: 3
Joined: Wed Oct 24, 2018 4:14 pm

Re: C# API - tik4net on GitHub

Thu Oct 25, 2018 12:43 pm

Is your mikrotik router properly configured? Which version of routeros do you use?

https://github.com/danikf/tik4net/wiki/SSL-connection

D
Hello! Thank you very much, all is working fine! Have a nice day! :)
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Oct 27, 2018 7:10 pm

ip bindings from
ip/hotspot/ip-binding
Here you are (and also commited in dev branch).
Enjoy,
D
namespace tik4net.Objects.Ip.Hotspot
{
    /// <summary>
    /// ip/hotspot/ip-binding
    /// 
    /// IP-Binding HotSpot menu allows to setup static One-to-One NAT translations, allows to bypass specific HotSpot clients without any authentication, and also allows to block specific hosts and subnets from HotSpot network 
    /// </summary>
    [TikEntity("ip/hotspot/ip-binding")]
    public class HotspotIpBinding
    {
        /// <summary>
        /// .id: primary key of row
        /// </summary>
        [TikProperty(".id", IsReadOnly = true, IsMandatory = true)]
        public string Id { get; private set; }

        /// <summary>
        /// address: The original IP address of the client
        /// </summary>
        [TikProperty("address", DefaultValue = "")]
        public string/*IP Range*/ Address { get; set; }

        /// <summary>
        /// mac-address: MAC address of the client
        /// </summary>
        [TikProperty("mac-address", DefaultValue = "")]
        public string/*MAC*/ MacAddress { get; set; }

        /// <summary>
        /// server
        /// Name of the HotSpot server.
        ///  all - will be applied to all hotspot servers
        /// </summary>
        [TikProperty("server", DefaultValue = "all")]
        public string/*string | all*/ Server { get; set; }

        /// <summary>
        /// to-address: New IP address of the client, translation occurs on the router (client does not know anything about the translation)
        /// </summary>
        [TikProperty("to-address", DefaultValue = "")]
        public string/*IP*/ ToAddress { get; set; }

        /// <summary>
        /// type
        /// Type of the IP-binding action
        ///  regular - performs One-to-One NAT according to the rule, translates address to to-address
        ///  bypassed - performs the translation, but excludes client from login to the HotSpot
        ///  blocked - translation is not performed and packets from host are dropped
        /// </summary>
        [TikProperty("type", DefaultValue = "")]
        public string/*blocked | bypassed | regular*/ Type { get; set; }
    }
}
 
shaun12
just joined
Posts: 2
Joined: Sat Nov 10, 2018 12:17 pm

Re: C# API - tik4net on GitHub

Sat Nov 10, 2018 12:23 pm

Hi, Danik
im strugling to get into 1 router from another would you mind telling me what im doing wrong?

ITikConnection initconnection = ConnectionFactory.CreateConnection(TikConnectionType.Api);
initconnection.Open("10.255.107.2", "admin", xxxx");
ITikCommand mac_telnetCmd = initconnection.CreateCommand("/tool/mac-telnet",
initconnection.CreateParameter("host", "64:D1:54:22:71:37"),
initconnection.CreateParameter("Login", "admin"),
initconnection.CreateParameter("Password", "xxxx"));
initconnection.CreateCommand("/ip/address/add/",
initconnection.CreateParameter("address", "192.168.9.1/24"),
initconnection.CreateParameter("network", "192.168.8.0"),
initconnection.CreateParameter("interface", "wlan2"));
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Sat Nov 10, 2018 3:38 pm

Sorry, this is an unsupported feature:

https://wiki.mikrotik.com/wiki/API_comm ... e_commands
interactive command examples that will not work in API are:

/system telnet
/system ssh
/tool mac-telnet
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Nov 10, 2018 6:17 pm

Sorry, this is an unsupported feature:
Hi,

I must agree with nescafe2002. (IMHO RoMon telnet/ssh is unsupported either). I tried to workaround it (by some trick) but was not successfull.
Some links to read:
viewtopic.php?t=99953
viewtopic.php?t=71262
Janisk (from mikrotik) citation: everything that looks suspiciously interactive, like ssh login or telnet login will not work if ran from scheduler or script.
I saw also some sample bash script (from some mikrotik guy) which uses ssh to neighbour machine to perform changes on another machine via RoMon/mactelnet internal feature (but I cant find it anymore).

Finaly I end up with wrapping mactelnet application (classic mikrotik windows neigbour app) and using it to play prepared script on selected machine. I have plan to release it as library, but it will take time ...
https://www.mikrotik.com/download/neighbour.zip

D
 
murdochs
just joined
Posts: 3
Joined: Mon Nov 12, 2018 10:01 am

Re: C# API - tik4net on GitHub

Tue Nov 13, 2018 1:37 am

Hi, thanks for this great api.
I am using the command "ITikCommand cmd = connection.CreateCommandAndParameters("/tool/user-manager/user/print", "?username", sUser);" to see if the user already exist.
and if so, I want to get the value of "Actual-profile" by using "vResult.GetResponseField("actual-profile")". If the user has already used their alooted usage, then "Actual-profile" does not exist in the sentence. How can I check if the value exist before get response ?
thanks
Sean
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Tue Nov 13, 2018 1:09 pm

You can use GetResponseFieldOrDefault to have a default value as response or check the Words dictionary directly.

E.g.
var profile = vResult.GetResponseFieldOrDefault("actual-profile", "(none)");

or

if (vResult.Words.ContainsKey("actual-profile"))
{
  // Do something
}
 
murdochs
just joined
Posts: 3
Joined: Mon Nov 12, 2018 10:01 am

Re: C# API - tik4net on GitHub

Tue Nov 13, 2018 11:47 pm

thank-you. Was trying "GetResponseFieldOrDefault" but didn't have the second parameter.
 
BigTrumpet
Frequent Visitor
Frequent Visitor
Posts: 53
Joined: Thu Feb 07, 2008 7:46 pm

Re: C# API - tik4net on GitHub

Fri Nov 16, 2018 10:51 pm

Hi all,
I would need to get the real "speed rate" of an ethernet interface.

Using OS CLI I would type something like:
/interface ethernet monitor ether3 once
and response is something like that:
                      name: eth3-AP-AC-45
                    status: link-ok
          auto-negotiation: done
                      rate: 1Gbps
               full-duplex: yes
           tx-flow-control: no
           rx-flow-control: no
               advertising: 10M-half,10M-full,100M-half,100M-full,1000M-half,1000M-full
  link-partner-advertising: 10M-half,10M-full,100M-half,100M-full,1000M-half,1000M-full
I am interested in "rate" field.
How can I do with tik4net? I don't find this data using Interface or InterfaceMonitorTraffic objects.

Thank you.
Massimo
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Nov 17, 2018 12:25 pm

Hi all,
I would need to get the real "speed rate" of an ethernet interface.
Here you are (also commited to DEV branch).

D
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace tik4net.Objects.Interface.Ethernet
{
    /// <summary>
    /// /interface ethernet monitor: command prints out current link, rate and duplex status of an interface. 
    /// </summary>
    [TikEntity("/interface/ethernet/monitor", LoadCommand = "", LoadDefaultParameneterFormat = TikCommandParameterFormat.NameValue, IncludeDetails = false, IsReadOnly = true)]
    public class EthernetMonitor
    {
        /// <summary>
        /// name
        /// </summary>
        [TikProperty("name", IsMandatory = true, IsReadOnly = true)]
        public string Name { get; private set; }

        /// <summary>
        /// auto-negotiation
        /// Current auto negotiation status:
        ///  done - negotiation completed
        ///  incomplete - negotiation failed or not yet completed
        /// </summary>
        [TikProperty("auto-negotiation")]
        public string/*done | incomplete*/ AutoNegotiation { get; set; }

        /// <summary>
        /// default-cable-settings
        /// Default cable length setting (only applicable to NS DP83815/6 cards)
        ///  short - support short cables 
        ///  standard - support standard cables
        /// </summary>
        [TikProperty("default-cable-settings")]
        public string/*short | standard*/ DefaultCableSettings { get; set; }

        /// <summary>
        /// full-duplex: Whether transmission of data occurs in two directions simultaneously
        /// </summary>
        [TikProperty("full-duplex")]
        public bool FullDuplex { get; set; }

        /// <summary>
        /// rate: Actual data rate of the connection.
        /// </summary>
        [TikProperty("rate")]
        public string/*10Mbps | 100Mbps | 1Gbps*/ Rate { get; set; }

        /// <summary>
        /// status
        /// Current link status of an interface
        ///  link-ok - the card is connected to the network
        ///  no-link - the card is not connected to the network
        ///  unknown - the connection is not recognized (if the card does not report connection status)
        /// </summary>
        [TikProperty("status")]
        public string/*link-ok | no-link | unknown*/ Status { get; set; }

        /// <summary>
        /// tx-flow-control: Whether TX flow control is used
        /// </summary>
        [TikProperty("tx-flow-control")]
        public string TxFlowControl { get; set; }

        /// <summary>
        /// rx-flow-control: Whether RX flow control is used
        /// </summary>
        [TikProperty("rx-flow-control")]
        public string RxFlowControl { get; set; }

        /// <summary>
        /// sfp-module-present: Whether SFP module is in cage
        /// </summary>
        [TikProperty("sfp-module-present")]
        public bool SfpModulePresent { get; set; }

        /// <summary>
        /// sfp-rx-lose: 
        /// </summary>
        [TikProperty("sfp-rx-lose")]
        public bool SfpRxLose { get; set; }

        /// <summary>
        /// sfp-tx-fault: 
        /// </summary>
        [TikProperty("sfp-tx-fault")]
        public bool SfpTxFault { get; set; }

        /// <summary>
        /// sfp-connector-type: 
        /// </summary>
        [TikProperty("sfp-connector-type")]
        public string SfpConnectorType { get; set; }

        /// <summary>
        /// sfp-link-length-copper: Detected link length when copper SFP module is used
        /// </summary>
        [TikProperty("sfp-link-length-copper")]
        public string SfpLinkLengthCopper { get; set; }

        /// <summary>
        /// sfp-vendor-name: Vendor of the SFP module
        /// </summary>
        [TikProperty("sfp-vendor-name")]
        public string SfpVendorName { get; set; }

        /// <summary>
        /// sfp-vendor-part-number: SFP module part number
        /// </summary>
        [TikProperty("sfp-vendor-part-number")]
        public string SfpVendorPartNumber { get; set; }

        /// <summary>
        /// sfp-vendor-revision: SFP module revision number
        /// </summary>
        [TikProperty("sfp-vendor-revision")]
        public string SfpVendorRevision { get; set; }

        /// <summary>
        /// sfp-vendor-serial: SFP module serial number
        /// </summary>
        [TikProperty("sfp-vendor-serial")]
        public string SfpVendorSerial { get; set; }

        /// <summary>
        /// sfp-manufacturing-date: SFP module manufacturing date
        /// </summary>
        [TikProperty("sfp-manufacturing-date")]
        public string SfpManufacturingDate { get; set; }

        /// <summary>
        /// eeprom: EEPROM of an SFP module
        /// </summary>
        [TikProperty("eeprom")]
        public string Eeprom { get; set; }

        /// <summary>
        /// Gets snapshot of actual values for given <paramref name="interfaceName"/>.
        /// </summary>
        public static EthernetMonitor GetSnapshot(ITikConnection connection, string interfaceName)
        {
            return EthernetMonitorConnectionExtensions.GetEthernetMonitorSnapshot(connection, interfaceName);
        }

    }

    /// <summary>
    /// Connection extension class for <see cref="InterfaceMonitorTraffic"/>
    /// </summary>
    public static class EthernetMonitorConnectionExtensions
    {
        /// <summary>
        /// Gets snapshot of actual values for given <paramref name="interfaceName"/>.
        /// </summary>
        public static EthernetMonitor GetEthernetMonitorSnapshot(this ITikConnection connection, string interfaceName)
        {
            var result = connection.LoadSingle<EthernetMonitor>(
                connection.CreateParameter("numbers", interfaceName, TikCommandParameterFormat.NameValue),
                connection.CreateParameter("once", "", TikCommandParameterFormat.NameValue));

            return result;
        }
    }
}
 
BigTrumpet
Frequent Visitor
Frequent Visitor
Posts: 53
Joined: Thu Feb 07, 2008 7:46 pm

Re: C# API - tik4net on GitHub

Sun Nov 18, 2018 9:31 pm

Hi all,
I would need to get the real "speed rate" of an ethernet interface.
Here you are (also commited to DEV branch).

D
Thank you very much Danikf!
 
murdochs
just joined
Posts: 3
Joined: Mon Nov 12, 2018 10:01 am

Re: C# API - tik4net on GitHub

Tue Nov 20, 2018 1:26 am

Good Morning, I am trying to replicate create-and-activate-profile customer="admin" profile="1G" test which works in winbox.

In c#, I have

ITikCommand cmd = connection.CreateCommandAndParameters("/tool/user-manager/user/create-and-activate-profile", "profile", comboBox1.Text, "customer", "admin", textBox8.Text);

I get an error message "missing word with 'ret'.". I tried a view combinations, but other error was "unknown parameter".

Can anyone please help ?

edit - ("/tool/user-manager/user/create-and-activate-profile", "numbers",textBox8.Text,"profile", comboBox1.Text, "customer", "admin");

The above worked by putting in the name "numbers" and I can see that the user got the new profile, but it still gave me error message "missing word with 'ret'."
Sean


edit 2 :) - got it to work, was using executescalar instead of executenonquery.
 
BigTrumpet
Frequent Visitor
Frequent Visitor
Posts: 53
Joined: Thu Feb 07, 2008 7:46 pm

Re: C# API - tik4net on GitHub

Sat Dec 01, 2018 11:52 pm

Hello
is it possibile to get link down properties of the interfaces?
e.g. via CLI the command:
/interface print detail
returns:
name="eth10-myName" default-name="ether10" type="ether" mtu=1500 
       actual-mtu=1500 l2mtu=1598 max-l2mtu=9498 mac-address=D4:CA:6D:CC:BB:AA 
       last-link-down-time=nov/30/2018 17:25:50 
       last-link-up-time=nov/30/2018 17:25:51 link-downs=1 
Thank you.
Massimo
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Mon Dec 03, 2018 11:12 pm

Yes, just take a copy of https://github.com/danikf/tik4net/blob/ ... terface.cs and include the properties:

[TikProperty("last-link-down-time")]
public string LastLinkDownTime { get; set; }

[TikProperty("last-link-up-time")]
public string LastLinkUpTime { get; set; }
You do not have the required permissions to view the files attached to this post.
 
ValiSXP
just joined
Posts: 2
Joined: Thu Jan 10, 2019 5:45 pm

Re: C# API - tik4net on GitHub

Thu Jan 10, 2019 5:48 pm

Hi

There is a way to find out the statistics of a Firewall Rule?

Thank you

Valentin
 
ValiSXP
just joined
Posts: 2
Joined: Thu Jan 10, 2019 5:45 pm

Re: C# API - tik4net on GitHub

Fri Jan 11, 2019 1:09 pm

Hi

Does anyone knows why the ConnectionBytes property of a FirewallFilter object always returns 0?

Thank you
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Jan 12, 2019 1:26 pm

Does anyone knows why the ConnectionBytes property of a FirewallFilter object always returns 0?
Hi,

ConnectionBytes is value from Avanced tab. If you want to read statistic of rule, you need "bytes", not "connection-bytes". I have added these values to source (will be part of the next release).
        /// <summary>
        /// Statistics - bytes
        /// </summary>
        [TikProperty("bytes", IsReadOnly = true)]
        public long Bytes { get; private set; }

        /// <summary>
        /// Statistics - packets
        /// </summary>
        [TikProperty("packets", IsReadOnly = true)]
        public long Packets { get; private set; }
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Jan 12, 2019 1:38 pm

Yes, just take a copy of https://github.com/danikf/tik4net/blob/ ... terface.cs and include the properties:
Thanks - added to code base. Will be part ot the next release.

D
 
shooka
just joined
Posts: 1
Joined: Sat Apr 29, 2017 6:27 am

Re: C# API - tik4net on GitHub

Thu Feb 14, 2019 1:50 pm

hi ;
I want to connect to mikrotik router by mobile app and after confirm connect to internet.
please suggest me solution
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Mon Feb 18, 2019 10:10 pm

Off topic?
Anyway:
* For android app: https://play.google.com/store/apps/deta ... oid.tikapp
* For app created by this API: https://visualstudio.microsoft.com/cs/xamarin/ (+ .NET core project)
D
 
fbritop
just joined
Posts: 3
Joined: Sat Jul 08, 2017 3:34 am

Re: C# API - tik4net on GitHub

Tue Jun 11, 2019 10:20 pm

Is there a way or which is the correct way to avoid the issue with Single response sentence expected.
The SMS gets sent correctly, but the tik4net connection hangs for a long time, then it outputs:
Single response sentence expected.
COMMAND: /tool/sms/send
port=lte Format: Default
phone-number=56943415754 Format: Default
message=Test message.11-06-2019 15:13:05 Format: Default
RESPONSE:
ApiReSentence:
ApiDoneSentence:

Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
	connection.Open("10.0.1.207", "admin", "12345")

    Dim smsCmd As ITikCommand = connection.CreateCommand("/tool/sms/send", 
	connection.CreateParameter("port", "lte"),
	connection.CreateParameter("phone-number", "5694341XXXX"), 
	connection.CreateParameter("message", "Test message." & dateTime.now().toString()))
	smsCmd.ExecuteNonQuery()	
End using
Hi,
probably yes - in general. You can perform every operation which you can script in mikrotik API :-) I don't have GSM modem connected to mikrotik so I can't test it.

The code could be (not tested):
ITikCommand smsCmd = connection.CreateCommand("/tool/sms/send", 
    connection.CreateParameter("port", "usb3"), 
    connection.CreateParameter("channel", "3"), 
    connection.CreateParameter("phone-number", "00420777123456"), // or "dst" instead of "phone-number" - depends on tik version ???
    connection.CreateParameter("message", "Test message.")    
);
smsCmd.ExecuteNonQuery();
SMS documentation (warning - it is documentation for console, not for API - syntax will be a little bit different):
http://wiki.mikrotik.com/wiki/Manual:Tools/Sms

Other usefull links:
https://aacable.wordpress.com/2012/11/2 ... gsm-modem/
http://forum.mikrotik.com/viewtopic.php ... it=sms+api


Remarks: you have to install advanced-tools package and have gsm modem connected to mikrotik.

Let me know if it works,
D
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Tue Jun 11, 2019 11:23 pm

The API returns a result which is not expected by ExecuteNonQuery.

Try this instead, ExecuteSingleRows assumes parameters are query words by default so you'll have to supply parameterformat NameValue:
Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)

  connection.Open("10.0.1.207", "admin", "12345")

  Dim smsCmd As ITikCommand =
    connection.CreateCommandAndParameters(
      "/tool/sms/send",
      TikCommandParameterFormat.NameValue,
      "port", "lte",
      "phone-number", "5694341XXXX",
      "message", "Test message." & DateTime.Now.ToString())

  smsCmd.ExecuteSingleRow()

End Using
 
fbritop
just joined
Posts: 3
Joined: Sat Jul 08, 2017 3:34 am

Re: C# API - tik4net on GitHub

Wed Jun 12, 2019 12:11 am

I did try that one before the one I posted, but the the logs (and .NET), complains that there is no SMS Body data. Now I have verified with the TikCommandParameterFormat.NameValue option and in runs perfect. Thanks!
The API returns a result which is not expected by ExecuteNonQuery.

Try this instead, ExecuteSingleRows assumes parameters are query words by default so you'll have to supply parameterformat NameValue:
Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)

  connection.Open("10.0.1.207", "admin", "12345")

  Dim smsCmd As ITikCommand =
    connection.CreateCommandAndParameters(
      "/tool/sms/send",
      TikCommandParameterFormat.NameValue,
      "port", "lte",
      "phone-number", "5694341XXXX",
      "message", "Test message." & DateTime.Now.ToString())

  smsCmd.ExecuteSingleRow()

End Using
 
warez
just joined
Posts: 17
Joined: Tue Jun 28, 2011 1:44 pm

Re: C# API - tik4net on GitHub

Thu Jun 13, 2019 3:40 pm

Hello! Help please, how i can make execute simple line in C# for remove all sms in inbox
/tool sms inbox remove [find]
i do
ITikCommand cmd = connection.CreateCommand("/tool/sms/inbox/remove");
connection.CreateParameter("numbers", "[find]");
cmd.ExecuteNonQuery();
or
ITikCommand cmd = connection.CreateCommand("/tool/sms/inbox/remove [find]");
cmd.ExecuteNonQuery();
but nothing deleted.
Library don't have Wrapper for Tool/sms/inbox for use extension DeleteAll<>
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Thu Jun 13, 2019 4:47 pm

Your [find] example doesn't work because the API does not support composite CLI statements.

Fetch the list of ids and then remove one-by-one:
using (var conn = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", ""))
{
  var list =
    conn.CreateCommandAndParameters(
      "/tool/sms/inbox/print",
      TikCommandParameterFormat.NameValue,
      ".proplist", ".id"
    ).ExecuteList();

  foreach (var item in list)
  {
    conn.CreateCommandAndParameters(
      "/tool/sms/inbox/remove",
      ".id", item.Words[".id"]
    ).ExecuteNonQuery();
  }
}

You could also create a small class to support the sms natively:
void Main()
{
  using (var conn = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", ""))
  {
    conn.DeleteAll<ToolSmsInbox>();
  }
}

[TikEntity("/tool/sms/inbox")]
public class ToolSmsInbox
{
  [TikProperty(".id")]
  public string Id { get; private set; }

  [TikProperty("phone")]
  public string Phone { get; private set; }

  [TikProperty("type")]
  public string Type { get; private set; }

  [TikProperty("timestamp")]
  public string Timestamp { get; private set; }

  [TikProperty("message")]
  public string Message { get; private set; }
}
 
MarkLFT
just joined
Posts: 22
Joined: Mon Apr 23, 2012 7:22 am

Re: C# API - tik4net on GitHub

Wed Jul 10, 2019 2:25 pm

I have read that the latest version of the Routerboard firmware changes passwords, will this have an impact on this API? And in particular the creation of hotspot users?
 
User avatar
saputra19
just joined
Posts: 9
Joined: Fri Mar 23, 2018 3:11 pm
Location: indonesia
Contact:

Re: C# API - tik4net on GitHub

Wed Jul 24, 2019 10:14 am

Hi Daniel,
can you please update for new api login method on ROS V.6.45xx
What's new in 6.45.2 (2019-Jul-17 10:04):

Important note!!!
Due to removal of compatibility with old version passwords in this version, downgrading to any version prior to v6.43 (v6.42.12 and older) will clear all user passwords and allow password-less authentication. Please secure your router after downgrading.
Old API authentication method will also no longer work, see documentation for new login procedure:
https://wiki.mikrotik.com/wiki/Manual:API#Initial_login
thanks :D
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Wed Jul 24, 2019 11:21 am

Use TikConnectionType.Api_v2:

using (var conn = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, "192.168.88.1", "admin", ""))
{
  var cmd = conn.CreateCommand("/system/identity/print");
  var result = cmd.ExecuteSingleRow();
  Console.WriteLine(result.Words["name"]);
}
 
supportingit
just joined
Posts: 12
Joined: Sat Sep 11, 2010 5:09 pm

Re: C# API - tik4net on GitHub

Sat Sep 14, 2019 11:03 am

So I want to send a series of config changes to be executed sequentially, and I would do this in a script by surrounding the commands with { and } so they execute one after the other, even if the connection is broken, because I change the ip or reset the macs etc.

How can I do something similar with Tik4Net?

Code: Select all

string[] command = new string[] { @"{\r\ \n/system identity set name=" + _siteName + @"\r\ "
+ @"\n/ip pool set [find name=default-dhcp] ranges=" + _ipAddress + @".101-" + _ipAddress + @".254\r\ "
+ @"\n/ip dhcp-server network set [find comment=\""default configuration\""] address=" + _ipAddress + @".0/24 gateway=" + _ipAddress + @".1 ntp-server=10.9.0.1," + _ipAddress + @".1\r\ "
+ @"\n/interface sstp-client set [find name=sstp-manage] password=" + _managePassword + @" user=" + _manageLogin + @"\r\ "
+ @"\n/interface sstp-client set [find name=vpn-out] password=" + _vpnPassword + @" user=" + _vpnLogin + @"\r\ "
+ @"\n/ip address set [find comment=\""LAN Address\""] address=" + _ipAddress + @".1/24 network=" + _ipAddress + @".0\r\ "
+ @"\n}"
};
Cheers.
 
User avatar
saputra19
just joined
Posts: 9
Joined: Fri Mar 23, 2018 3:11 pm
Location: indonesia
Contact:

Re: C# API - tik4net on GitHub

Sat Sep 21, 2019 6:27 pm

Use TikConnectionType.Api_v2:

using (var conn = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, "192.168.88.1", "admin", ""))
{
  var cmd = conn.CreateCommand("/system/identity/print");
  var result = cmd.ExecuteSingleRow();
  Console.WriteLine(result.Words["name"]);
}
only work until ROS 6.45.2
doesn't work for ROS above 6.45.2 :)
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sat Nov 09, 2019 5:12 pm

only work until ROS 6.45.2
doesn't work for ROS above 6.45.2 :)
Tested (and works OK) with my v6.45.6 RB493 (at least SSL version).
D
 
andreazanini
just joined
Posts: 2
Joined: Fri Nov 22, 2019 7:30 pm

Re: C# API - tik4net on GitHub

Fri Nov 22, 2019 7:37 pm

Hello,
sorry to bother you but is it possible to execute the command:
/interface pppoe-server remove [find user=ex]
i've searched on your github but couldn't understand if it is possible to drop an active pppoe-user.
I saw about using secrets but in my configuration i don't use/have them.
Many thanks
Andrea
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Sat Nov 23, 2019 4:35 pm

There are generally two ways to performs operations via Tik4Net.

Method 1. Use low level API

  using (var conn = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, "192.168.88.1", 8728, "admin", ""))
  {
    var command = conn.CreateCommand("/interface/pppoe-server/print");
    command.AddParameter(".proplist", ".id", TikCommandParameterFormat.NameValue);
    command.AddParameterAndValues("user", "ex");

    var list = command.ExecuteList();
  
    foreach (var item in list)
    {
      conn.CreateCommandAndParameters(
        "/interface/pppoe-server/remove",
        ".id", item.Words[".id"]
      ).ExecuteNonQuery();
    }
  }

Method 2. Use high-level API

void Main()
{
  using (var conn = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, "192.168.88.1", 8728, "admin", ""))
  {
    var list = conn.LoadList<PppoeServer>(conn.CreateParameter("user", "ex"));
    foreach (var item in list)
    {
      conn.Delete(item);
    }
  }
}

[TikEntity("/interface/pppoe-server")]
public class PppoeServer
{
  [TikProperty(".id")]
  public string Id { get; set; }

  [TikProperty("user")]
  public string User { get;set;}
}

Maybe "higher level" is a bit far stretched, as you're essentially only using the Id property.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Mon Dec 02, 2019 1:17 am

/interface pppoe-server remove [find user=ex]
Hi,
the question is so called ever-green. Thanks nescafe2002 for answering it again and again :-)

To make his life a little bit more easy, I have extended the wiki page about this scenario:
https://github.com/danikf/tik4net/wiki/ ... ific-value

D
 
andreazanini
just joined
Posts: 2
Joined: Fri Nov 22, 2019 7:30 pm

Re: C# API - tik4net on GitHub

Mon Dec 02, 2019 5:15 pm

Many thanks nescafe, this works perfectly. Sorry if I didn't find the answer before, but now it is better documented! :)
 
bumbatik
just joined
Posts: 4
Joined: Sat Dec 21, 2019 4:52 pm

Re: C# API - tik4net on GitHub

Sat Dec 21, 2019 5:04 pm

Hello Dakinf,

I had one small query. These dll and libraries can be used only in .Net console or also can be used in .net (.aspx) websites.
We have a project in hand and looking for some guidance on the same.

Thanks,
Saurabh.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun Dec 22, 2019 3:46 pm

Can be used everywhere with supported .NET/.NETCore version.
D
 
bumbatik
just joined
Posts: 4
Joined: Sat Dec 21, 2019 4:52 pm

Re: C# API - tik4net on GitHub

Mon Dec 23, 2019 8:28 am

Thanks a lot for the reply Danikf.

One more thing. I can see in your code:
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api_v2)) // Use TikConnectionType.Api for mikrotikversion prior v6.45
   {
      connection.Open(HOST, USER, PASS);
you have mentioned HOST, USER and PASS
USER means Username of the router, PASS means Password.
What does HOST mean and where can we get this value from?

Secondly, I am currently able to access a router using WINBOX only using the Mac Address and not the IP (may be bcz its setting is not that of static ip).
Can we through our code also access the router through Mac ID?
Can you kindly help with any code for the same.

Also are the DLL files for aspx separately available?

Thanks a lot in Advance.

Saurabh.
 
bumbatik
just joined
Posts: 4
Joined: Sat Dec 21, 2019 4:52 pm

Re: C# API - tik4net on GitHub

Tue Dec 24, 2019 9:07 pm

Hi Everyone.

I did some analysis and found that yes Danikf's package does work for websites as well.
It took some more time for me as I used to work in .Net long time back in 2011-2012.
Now, I am not having any hands on into it as professionally I am a SAP consultant.

So, the code which I wrote for .Net website is as follows. I hope it helps anyone who needs it.
protected void Login_Click(object sender, EventArgs e)
    {
        try
        {
            // Using Tik4Net connecion to Login
            ITikConnection connection = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, TextBox1.Text, TextBox2.Text, TextBox3.Text);

            // Now creating command string
            ITikCommand cmd = connection.CreateCommand("/system/identity/print");

            // Execute the command and add it in a string
            string identity = cmd.ExecuteScalar();

            // Print it on Website
            //Response.Write("Identity: " + identity);
            Mess.ForeColor = System.Drawing.Color.Green;
            Mess.Text = "Identity :" + identity; 
        } catch(Exception ex )
        {
            //Response.Write("Exception : " + ex.Message);
            Mess.ForeColor = System.Drawing.Color.Red;
            Mess.Text = ex.Message;
        }

    }
}

Thanks Everyone! :D :D

Saurabh.
 
bumbatik
just joined
Posts: 4
Joined: Sat Dec 21, 2019 4:52 pm

Re: C# API - tik4net on GitHub

Sun Dec 29, 2019 1:06 pm

Hello Everyone,

I have used the following code to access the Mikrotik router and get the system identity.
The connection = ConnectionFactory.OpenConnection works without any issues,
but when the ExecuteScalar command is exected, exception "Not Logged In" is being thrown.
Please help. How to get through this issue?
 protected void Login_Click(object sender, EventArgs e)
    {
        try
        {
            // Using Tik4Net connecion to Login
            ITikConnection connection = ConnectionFactory.OpenConnection(TikConnectionType.Api_v2, TextBox1.Text, TextBox2.Text, TextBox3.Text);

            // Now creating command string
            ITikCommand cmd = connection.CreateCommand("/system/identity/print");

            // Execute the command and add it in a string
            string identity = cmd.ExecuteScalar();

            // Print it on Website
            //Response.Write("Identity: " + identity);
            Mess.ForeColor = System.Drawing.Color.Green;
            Mess.Text = "Identity :" + identity; 
        } catch(Exception ex )
        {
            //Response.Write("Exception : " + ex.Message);
            Mess.ForeColor = System.Drawing.Color.Red;
            Mess.Text = ex.Message;
        }

    }
}
Thanks in Advance,
Saurabh.
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Sun Dec 29, 2019 1:28 pm

That function works fine here. Have you tried running it in a Console Application?

I ran the example using LINQPad: https://www.linqpad.net/

Script: http://share.linqpad.net/6i2986.linq
You do not have the required permissions to view the files attached to this post.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Wed Jan 01, 2020 5:21 pm

Hi everybody,

after more than one year - there is new version of tik4net.

Details:
https://github.com/danikf/tik4net/wiki/History

In hope it will be usefull,
D
 
iDeedz
just joined
Posts: 1
Joined: Mon Jan 13, 2020 12:00 pm

Re: C# API - tik4net on GitHub

Mon Jan 13, 2020 12:38 pm

Hi,

I've started playing with this library and have found that I am unable to retrieve the LTE info from the router.

I am using the following code to try and get information.
Dim connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, IP, u, p)
Dim loadCmd = connection.CreateCommandAndParameters("/interface/lte/info", "number", "0", "once", "")
Dim response = loadCmd.ExecuteList()
We have a working version for php to get the LTE info, but this will have to be ported to a vb.net application.

Not sure if I am doing something wrong, or perhaps something else I am missing?
 
RezaSix
just joined
Posts: 3
Joined: Wed Feb 19, 2020 11:14 am

Re: C# API - tik4net on GitHub

Thu Feb 20, 2020 10:48 am

Hi everybody,

after more than one year - there is new version of tik4net.

Details:
https://github.com/danikf/tik4net/wiki/History

In hope it will be usefull,
D
Hi.
I have a question.
I want to create a custom login page and the users can login with facebook api. the user log must save in db and admin can manage the users.
Can i do this with your library or a bit customization?
Thanks a lot.
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Sun May 31, 2020 12:40 pm

Hi.
I have a question.
I want to create a custom login page and the users can login with facebook api. the user log must save in db and admin can manage the users.
Can i do this with your library or a bit customization?
Thanks a lot.
Sorry to say that, but this type of question is out of the scope of the API support ... This API provides C# way to communication with mikrotik.
D
 
User avatar
danikf
Frequent Visitor
Frequent Visitor
Topic Author
Posts: 72
Joined: Mon Mar 14, 2011 8:57 am

Re: C# API - tik4net on GitHub

Mon Jun 08, 2020 11:28 pm

Hi,

I've started playing with this library and have found that I am unable to retrieve the LTE info from the router.

I am using the following code to try and get information.
Dim connection = ConnectionFactory.OpenConnection(TikConnectionType.Api, IP, u, p)
Dim loadCmd = connection.CreateCommandAndParameters("/interface/lte/info", "number", "0", "once", "")
Dim response = loadCmd.ExecuteList()
We have a working version for php to get the LTE info, but this will have to be ported to a vb.net application.

Not sure if I am doing something wrong, or perhaps something else I am missing?
Hi,
* do not use numbers (not working via API).
* Use .id or name.
* Not sure about once parameter.
* Try to specify parameter type explicitly (ExecuteList creates Filter parameter format, but you should use NameValue format)
* During debug, take a look at VisualStudio debug window to trace API communication

Take a look at:
https://github.com/danikf/tik4net/wiki/ ... O-R-mapper
https://github.com/danikf/tik4net/wiki/ ... I-advanced (asynchronous loading)

D
 
geoandroid
just joined
Posts: 2
Joined: Sun Oct 25, 2020 6:23 am

Re: C# API - tik4net on GitHub peer Disable

Sun Oct 25, 2020 6:32 am

Goodnight
I am trying to disable a peer by command
but it does not generate action

Send name peer
using (ITikConnection connection = ConnectionFactory.CreateConnection(TikConnectionType.Api_v2))
{
connection.Open("10.0.10.1", "x", "xxxx");
var updateCommand = connection.CreateCommandAndParameters("/ip/ipsec/policy/disable", "[find peer ='peer-TEST']");
updateCommand.ExecuteNonQuery();

}
 
perni
newbie
Posts: 30
Joined: Thu May 13, 2010 11:58 pm

Re: C# API - tik4net on GitHub

Mon Dec 14, 2020 6:16 pm

Hello

I have tried to use the tik4net library to get the actual link speed of an interface.
From cli i would use /interface ethernet monitor ether2

I tried the following
ITikCommand monitor = connection.CreateCommandAndParameters("/interface/ethernet/monitor", "interface", "ether3");
monitor.ExecuteAsync(re => responses.Add(re));
System.Threading.Thread.Sleep(5000);
monitor.CancelAndJoin();
This does not give me nay responses.

Trying a similar commnad
monitor = connection.CreateCommandAndParameters("/interface/monitor-traffic", "interface", "ether3");
gives me some responses .

I guess i have missed something.
Does someone have an explanation why /interface/ethernet/monitor does not return values and what I should do instead?
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Mon Dec 14, 2020 6:37 pm

monitor.ExecuteAsync(re => responses.Add(re));
This does not give me nay responses.

It does give a response in the error callback:

monitor.ExecuteAsync(
  re => responses.Add(re),
  e => Console.WriteLine(e.ToString()));

Error:

ApiTrapSentence:.tag=1|message=unknown parameter

You can use parameter .id instead:

ITikCommand monitor = conn.CreateCommandAndParameters("/interface/ethernet/monitor", ".id", "ether3");
 
perni
newbie
Posts: 30
Joined: Thu May 13, 2010 11:58 pm

Re: C# API - tik4net on GitHub

Tue Dec 15, 2020 5:07 pm

Thanks.
I also found a dedicated class for it - the EthernetMonitor
EthernetMonitor em = EthernetMonitor.GetSnapshot(connection, "ether3");
string linkspeed = em.Rate;
 
danielsp
just joined
Posts: 2
Joined: Sun Jan 26, 2020 5:33 pm

Re: C# API - tik4net on GitHub

Sat Mar 20, 2021 5:27 am

Hello, good afternoon. happily I was able to connect my vb.net application to Mikrotik. thank you for this.
From my application vb.net I try to be able to block an IP, that without problems.

Dim cmdmk As ITikCommand = connmk.CreateCommandAndParameters("/ip/firewall/address-list/add", "list", "Bloqueo", "address", mkip, "comment", mkcliente)
Dim id = cmdmk.ExecuteScalar()
TextBox2.Text = id

But when I want to remove the ip from the address list I get the error "of type" does not belong.

Dim findResponse = connmk.CallCommandSync("/ip/firewall/address-list/print", "?=address=", mkip)
Dim id = findResponse.OfType(Of ITikReSentence)().Single().GetId()
Dim deleteResponse = connmk.CallCommandSync("/ip/firewall/address-list/remove", $"=.id={id}")

They can give me an indication.
Thank you

Daniel
Last edited by danielsp on Sat Mar 20, 2021 8:46 am, edited 1 time in total.
 
danielsp
just joined
Posts: 2
Joined: Sun Jan 26, 2020 5:33 pm

Re: C# API - tik4net on GitHub

Mon Mar 22, 2021 2:02 am

solved.
Many thanks to the creator of this excellent application. danikf

I share the solution. the first code is to generate an address and the second is to eliminate it.


regards
daniel

Try
connmk2.Open(vhost, vuser, vpass)
Dim newAddressList = New FirewallAddressList() With {
.Address = Mkip,
.List = "Bloqueo",
.Comment = mkcliente
}
connmk2.Save(newAddressList)
connmk2.Close()
Catch ex As Exception
MsgBox("Error al Aplicar" + vbNewLine + ex.Message)
connmk2.Close()
End Try
---------------------------------------------
Try
connmk2.Open(vhost, vuser, vpass)
Dim buscaradd = connmk2.LoadList(Of FirewallAddressList)
For Each item In buscaradd
If item.Comment = mkcliente Then
connmk2.Delete(item)
End If
Next
connmk2.Close()
Catch ex As Exception
MsgBox("Error al Aplicar" + vbNewLine + ex.Message)
connmk2.Close()
End Try
 
geoandroid
just joined
Posts: 2
Joined: Sun Oct 25, 2020 6:23 am

Re: C# API - tik4net on GitHub

Mon Mar 29, 2021 6:58 am

I am looking for a way to enable and disable a connection peer
But I can't make it work
The commands are
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
/ip ipsec peer disable [find name =peer-A]
/ip ipsec peer enable [find name =peer-A]
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
Code c#
var cmdmkt = connection.CreateCommandAndParameters("/ip/ipsec/peer/enable", "[find name ='peer-A']");
cmdmkt.ExecuteNonQuery();
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Mon Mar 29, 2021 11:35 am

Since name is the primary identifier for the object, you can use .id=peer-A:

using (var conn = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", "password"))
{
  conn.CreateCommandAndParameters("/ip/ipsec/peer/disable", ".id", "peer-A").ExecuteNonQuery();
  conn.CreateCommandAndParameters("/ip/ipsec/peer/enable", ".id", "peer-A").ExecuteNonQuery();
}
 
s7004u
just joined
Posts: 1
Joined: Sun Jun 06, 2021 6:28 am

Re: C# API - tik4net on GitHub

Sun Jun 06, 2021 8:54 am

Hello
First of all, thank you for this very good work!
I have a question for you:
I want to delete the connections from the source 192.168.1.101 but I get an error please help

my cod:
            var firewallconnection = connection.LoadList<FirewallConnection>();
            foreach (var item in firewallconnection )
            {
                if (item.SrcAddress.Contains("192.168.1.101"))
                {
                    connection.Delete<FirewallConnection>(item);
                }
            }
            
 
nickoodk
just joined
Posts: 6
Joined: Tue Apr 27, 2021 11:46 am
Contact:

Re: C# API - tik4net on GitHub

Fri Jul 02, 2021 4:54 am

Hi, i get log "user login via api" and "user logout via api" when catch data every 1minuts from mikrotik
Last edited by nickoodk on Mon Jul 05, 2021 11:45 am, edited 1 time in total.
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Sat Jul 03, 2021 5:40 pm

Move the login logic out of the loop and keep the process running.
 
nickoodk
just joined
Posts: 6
Joined: Tue Apr 27, 2021 11:46 am
Contact:

Re: C# API - tik4net on GitHub

Tue Aug 24, 2021 6:46 am

how to get data from 2 different devices in 1 program?
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Tue Aug 24, 2021 6:59 am

You can create multiple clients in a single program.
 
nickoodk
just joined
Posts: 6
Joined: Tue Apr 27, 2021 11:46 am
Contact:

Re: C# API - tik4net on GitHub

Tue Aug 24, 2021 7:20 am

You can create multiple clients in a single program.
can i get an example?
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Tue Aug 24, 2021 7:45 am

var conn1 = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.1", 8728, "admin", "password");
var conn2 = tik4net.ConnectionFactory.OpenConnection(TikConnectionType.Api, "192.168.88.2", 8728, "admin", "password");

var list1 = conn1.LoadList<tik4net.Objects.Ip.IpAddress>();
var list2 = conn2.LoadList<tik4net.Objects.Ip.IpAddress>();

// List contains IP addresses of both devices.
var list = list1.Concat(list2);
 
ldkrjuger
just joined
Posts: 3
Joined: Fri Aug 06, 2021 3:00 pm

Re: C# API - tik4net on GitHub

Sat Sep 11, 2021 6:49 pm

hi. iam trying update my small tik's park.
iam trying
/system/package/update/install via low lvl api
and sometimes all ok. but sometimes app freeze in last section when tik start reboot
Untitled.png
You do not have the required permissions to view the files attached to this post.
 
nescafe2002
Forum Veteran
Forum Veteran
Posts: 897
Joined: Tue Aug 11, 2015 12:46 pm
Location: Netherlands

Re: C# API - tik4net on GitHub

Mon Sep 13, 2021 11:02 pm

ldkrjuger, probably the status is based on polling (internally), therefore the latest status (Downloaded, rebooting...) is sometimes not visible. Isn't the connection timing out?

Perhaps you want more control over the update process.. therefore you could split the update process to make sure the device reports download completion before reboot:

/system/package/update/check-for-updates
/system/package/update/download
/system/reboot
 
Djnonk
just joined
Posts: 1
Joined: Sun Feb 13, 2022 8:39 am

Re: C# API - tik4net on GitHub

Sun Feb 13, 2022 11:35 am

Hi everybody. i need help,I'm new to Mikrotik and i try to conecting my mikrotik via remote vpn. its work if use winbox. but no working if using api. iam use
Dim conn2 = tik4net.ConnectionFactory.CreateConnection(TikConnectionType.Api_v2)
conn2.Open("id.tunnel.my.id:5642", "admin", "passwd") and error no such host is known. what should i do?thanks for help..
 
tel7
just joined
Posts: 1
Joined: Sat Jul 22, 2017 10:31 pm

Re: C# API - tik4net on GitHub

Tue Jul 19, 2022 12:35 am

Greetings
I'm 45 years old, I live in the countryside of the Amazon, Brazil and I went back to programming after 20 years stopped.
I came back and a lot has changed, I need your help for a vb.net project with mikrotik, I already got the answer from the code below,
but I need it to return the information of the active PPP
can you help me?

I got the code below
Imports tik4net.Objects.Ppp


Dim HOST, USER, PASS As String
HOST = "192.168.2.1"
USER = "vb.net"
PASS = "Vb@N3t"
Using connection As ITikConnection = ConnectionFactory.CreateConnection(TikConnectionType.Api)
connection.Open(HOST, USER, PASS)

Dim cmd As ITikCommand = connection.LoadAll(Of PppActive)()
TextBox1.Text = cmd

End Using
 
User avatar
maxrate
Frequent Visitor
Frequent Visitor
Posts: 94
Joined: Mon Oct 23, 2006 10:55 pm
Location: Toronto

Re: C# API - tik4net on GitHub

Mon Feb 06, 2023 4:01 am

Hi all - I'm pretty new to programming C# / .NET. I'm having trouble isolating the code that actually makes the connection and speaks via 'terminal'. Is this all hidden inside of the DLL file? (not accessible). I was curious on learning about how the code actually worked to form a connection, not so much the abstracted layers. I suppose my question is: Is this low level code 'hidden'? Is the code not accessible? I'm interested in studying it.
 
altanbariscomert
just joined
Posts: 2
Joined: Sat Apr 01, 2023 12:34 am

Re: C# API - tik4net on GitHub

Sat Apr 01, 2023 2:05 am

hi, i'm trying to do remove hotspot user by id name but it's not working. I checked all the pages and couldn't make it. Here is my code

 try
            {
                string mikrotikAddress = ConfigurationManager.AppSettings["MikrotikIp"];
                string mikrotikUsername = ConfigurationManager.AppSettings["MikrotikUsername"];
                string mikrotikPassword = ConfigurationManager.AppSettings["MikrotikPassword"];

                string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
                using (SqlConnection connection = new SqlConnection(connectionString))
                using (ITikConnection connection1 = ConnectionFactory.OpenConnection(TikConnectionType.Api, mikrotikAddress, mikrotikUsername, mikrotikPassword))
                {
                    connection.Open();
                    string query = "SELECT TcNo,CheckIn,CheckOut FROM Mikrotik WHERE [TcNo] NOT LIKE N'%NULL%'";
                    SqlCommand command2 = new SqlCommand(query, connection);
                    SqlDataReader reader = command2.ExecuteReader();
                    while (reader.Read())
                    {
                        string TcNo = reader.GetString(0);
                        int CheckIn = reader.GetInt32(1);
                        int CheckOut = reader.GetInt32(2);

                      
                            ITikCommand printCmd = connection1.CreateCommand("/ip/hotspot/user/print");
                            printCmd.AddParameter("?.name", TcNo);
                            List<ITikReSentence> response = printCmd.ExecuteList().ToList();
                            bool userExists = (response != null && response.Count > 0);

                        if (userExists && CheckIn == 1 && CheckOut == 1)
                        {
                            // Find the user ID
                            ITikCommand printCmd = connection1.CreateCommand("/ip/hotspot/user/print");
                            printCmd.AddParameter("?.name", TcNo);
                            ITikSentence response = printCmd.ExecuteList();
                            string userId = response.FirstOrDefault()?[".id"];

                            if (!string.IsNullOrEmpty(userId))
                            {
                                // Remove the user from the hotspot
                                ITikCommand removeCmd = connection1.CreateCommand("/ip/hotspot/user/remove");
                                removeCmd.AddParameter(".id", userId);
                                removeCmd.ExecuteNonQuery();
                            }
                        }




                       else if (!userExists && CheckIn == 1 && CheckOut == 0)
                        {
                            // Create an API command to add a new hotspot user with the name from the SQL query
                            ITikCommand addCmd = connection1.CreateCommand("/ip/hotspot/user/add");
                            addCmd.AddParameter("name", TcNo);
                            addCmd.ExecuteNonQuery();
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                // Handle any errors that occur
                MessageBox.Show(ex.Message);
            }
 
altanbariscomert
just joined
Posts: 2
Joined: Sat Apr 01, 2023 12:34 am

Re: C# API - tik4net on GitHub

Mon Apr 03, 2023 4:01 pm

i solved it. here is my code for
        {


            try
            {

                string mikrotikAddress = ConfigurationManager.AppSettings["MikrotikIp"];
                string mikrotikUsername = ConfigurationManager.AppSettings["MikrotikUsername"];
                string mikrotikPassword = ConfigurationManager.AppSettings["MikrotikPassword"];

                string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
                using (SqlConnection connection = new SqlConnection(connectionString))
                using (ITikConnection connection1 = ConnectionFactory.OpenConnection(TikConnectionType.Api, mikrotikAddress, mikrotikUsername, mikrotikPassword))
                {
                    connection.Open();
                    string query = "SELECT TcNo,CheckIn,CheckOut FROM Mikrotik WHERE [TcNo] NOT LIKE N'%NULL%'";
                    SqlCommand command2 = new SqlCommand(query, connection);
                    SqlDataReader reader = command2.ExecuteReader();
                    while (reader.Read())
                    {
                        string TcNo = reader.GetString(0);
                        int CheckIn = reader.GetInt32(1);
                        int CheckOut = reader.GetInt32(2);




                        bool userExists = false;

                        // Check if the user already exists
                        foreach (HotspotUser user in connection1.LoadAll<HotspotUser>())
                        {
                            if (user.Name == TcNo)
                            {
                                userExists = true;
                                break;
                            }
                        }
                        if (!userExists && CheckIn == 1 && CheckOut == 0)
                        {
                            // Add the new user if it doesn't exist
                            var user = new HotspotUser()
                            {
                                Name = TcNo,
                            };
                            connection1.Save(user);
                        }
                        else if (CheckIn == 1 && CheckOut == 1)
                        {
                            // Remove the user if it exists
                            foreach (HotspotUser user in connection1.LoadAll<HotspotUser>())
                            {
                                if (user.Name == TcNo)
                                {
                                    connection1.Delete(user);
                                    break;
                                }
                            }
                        }





                    }

                }
            }
            catch (Exception ex)
            {
                // Handle any errors that occur
                MessageBox.Show(ex.Message);
            }
        } 




hi, i'm trying to do remove hotspot user by id name but it's not working. I checked all the pages and couldn't make it. Here is my code

 try
            {
                string mikrotikAddress = ConfigurationManager.AppSettings["MikrotikIp"];
                string mikrotikUsername = ConfigurationManager.AppSettings["MikrotikUsername"];
                string mikrotikPassword = ConfigurationManager.AppSettings["MikrotikPassword"];

                string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
                using (SqlConnection connection = new SqlConnection(connectionString))
                using (ITikConnection connection1 = ConnectionFactory.OpenConnection(TikConnectionType.Api, mikrotikAddress, mikrotikUsername, mikrotikPassword))
                {
                    connection.Open();
                    string query = "SELECT TcNo,CheckIn,CheckOut FROM Mikrotik WHERE [TcNo] NOT LIKE N'%NULL%'";
                    SqlCommand command2 = new SqlCommand(query, connection);
                    SqlDataReader reader = command2.ExecuteReader();
                    while (reader.Read())
                    {
                        string TcNo = reader.GetString(0);
                        int CheckIn = reader.GetInt32(1);
                        int CheckOut = reader.GetInt32(2);

                      
                            ITikCommand printCmd = connection1.CreateCommand("/ip/hotspot/user/print");
                            printCmd.AddParameter("?.name", TcNo);
                            List<ITikReSentence> response = printCmd.ExecuteList().ToList();
                            bool userExists = (response != null && response.Count > 0);

                        if (userExists && CheckIn == 1 && CheckOut == 1)
                        {
                            // Find the user ID
                            ITikCommand printCmd = connection1.CreateCommand("/ip/hotspot/user/print");
                            printCmd.AddParameter("?.name", TcNo);
                            ITikSentence response = printCmd.ExecuteList();
                            string userId = response.FirstOrDefault()?[".id"];

                            if (!string.IsNullOrEmpty(userId))
                            {
                                // Remove the user from the hotspot
                                ITikCommand removeCmd = connection1.CreateCommand("/ip/hotspot/user/remove");
                                removeCmd.AddParameter(".id", userId);
                                removeCmd.ExecuteNonQuery();
                            }
                        }




                       else if (!userExists && CheckIn == 1 && CheckOut == 0)
                        {
                            // Create an API command to add a new hotspot user with the name from the SQL query
                            ITikCommand addCmd = connection1.CreateCommand("/ip/hotspot/user/add");
                            addCmd.AddParameter("name", TcNo);
                            addCmd.ExecuteNonQuery();
                        }

                    }
                }
            }
            catch (Exception ex)
            {
                // Handle any errors that occur
                MessageBox.Show(ex.Message);
            }
 
User avatar
rextended
Forum Guru
Forum Guru
Posts: 11967
Joined: Tue Feb 25, 2014 12:49 pm
Location: Italy
Contact:

Re: C# API - tik4net on GitHub

Mon Apr 03, 2023 10:56 pm

Nice mess with the useless quote...
 
amirrahimi
just joined
Posts: 1
Joined: Mon Mar 04, 2024 6:42 am

I want copy file from mikrotik

Mon Mar 04, 2024 6:44 am

Hi i want copy file from mikrotik with tik4net is there any example
 
guidus
just joined
Posts: 1
Joined: Sat Mar 09, 2024 10:12 pm

Re: C# API - tik4net on GitHub

Sat Mar 09, 2024 10:18 pm

Hi guys

I need to connect from C# to router mikrotik using a VPN (remotewimbox) to access my routers remotely.

I can to access my router mikrotik on LAN, but using VPN i can not... please help me, thank you

Who is online

Users browsing this forum: ko00000000001 and 20 guests