Community discussions

MikroTik App
 
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: cosinguyen93, diamuxin, JDF, philipp84 and 24 guests