Page 1 of 1

Re: C# API - tik4net on GitHub

Posted: Mon Oct 01, 2018 6:29 pm
by danikf
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);

Re: C# API - tik4net on GitHub

Posted: Thu Oct 04, 2018 12:48 pm
by saputra19
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

Re: C# API - tik4net on GitHub

Posted: Wed Oct 10, 2018 6:55 am
by phamthinh2707
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.

Re: C# API - tik4net on GitHub

Posted: Thu Oct 11, 2018 4:59 pm
by giguard
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?

Re: C# API - tik4net on GitHub

Posted: Thu Oct 11, 2018 5:08 pm
by nescafe2002
/ip/ipsec/remote-peer is not valid.
/ip/ipsec/remote-peers is.

Re: C# API - tik4net on GitHub

Posted: Thu Oct 11, 2018 5:34 pm
by giguard
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

Re: C# API - tik4net on GitHub

Posted: Thu Oct 11, 2018 6:03 pm
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Thu Oct 11, 2018 6:06 pm
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Thu Oct 11, 2018 6:25 pm
by giguard
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?

Re: C# API - tik4net on GitHub

Posted: Thu Oct 11, 2018 6:28 pm
by giguard
In case any one wondering what caused that execption,
            ITikReSentence id = connection.CreateCommandAndParameters("/ip/ipsec/remote-peers/print", "id", username).ExecuteSingleRow();

Re: C# API - tik4net on GitHub

Posted: Thu Oct 11, 2018 6:53 pm
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Fri Oct 12, 2018 9:41 am
by giguard
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?

Re: C# API - tik4net on GitHub

Posted: Fri Oct 12, 2018 10:57 am
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Mon Oct 15, 2018 6:49 am
by javierur10
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

Re: C# API - tik4net on GitHub

Posted: Mon Oct 15, 2018 12:11 pm
by nescafe2002
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

Re: C# API - tik4net on GitHub

Posted: Mon Oct 15, 2018 2:06 pm
by saputra19
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

tik4net, SSL connection exception

Posted: Wed Oct 24, 2018 5:18 pm
by khisrav
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.

Re: C# API - tik4net on GitHub

Posted: Thu Oct 25, 2018 12:12 pm
by danikf
Is your mikrotik router properly configured? Which version of routeros do you use?

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

D

Re: C# API - tik4net on GitHub

Posted: Thu Oct 25, 2018 12:43 pm
by khisrav
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! :)

Re: C# API - tik4net on GitHub

Posted: Sat Oct 27, 2018 7:10 pm
by danikf
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; }
    }
}

Re: C# API - tik4net on GitHub

Posted: Sat Nov 10, 2018 12:23 pm
by shaun12
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"));

Re: C# API - tik4net on GitHub

Posted: Sat Nov 10, 2018 3:38 pm
by nescafe2002
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

Re: C# API - tik4net on GitHub

Posted: Sat Nov 10, 2018 6:17 pm
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Tue Nov 13, 2018 1:37 am
by murdochs
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

Re: C# API - tik4net on GitHub

Posted: Tue Nov 13, 2018 1:09 pm
by nescafe2002
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
}

Re: C# API - tik4net on GitHub

Posted: Tue Nov 13, 2018 11:47 pm
by murdochs
thank-you. Was trying "GetResponseFieldOrDefault" but didn't have the second parameter.

Re: C# API - tik4net on GitHub

Posted: Fri Nov 16, 2018 10:51 pm
by BigTrumpet
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

Re: C# API - tik4net on GitHub

Posted: Sat Nov 17, 2018 12:25 pm
by danikf
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;
        }
    }
}

Re: C# API - tik4net on GitHub

Posted: Sun Nov 18, 2018 9:31 pm
by BigTrumpet
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!

Re: C# API - tik4net on GitHub

Posted: Tue Nov 20, 2018 1:26 am
by murdochs
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.

Re: C# API - tik4net on GitHub

Posted: Sat Dec 01, 2018 11:52 pm
by BigTrumpet
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

Re: C# API - tik4net on GitHub

Posted: Mon Dec 03, 2018 11:12 pm
by nescafe2002
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; }

Re: C# API - tik4net on GitHub

Posted: Thu Jan 10, 2019 5:48 pm
by ValiSXP
Hi

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

Thank you

Valentin

Re: C# API - tik4net on GitHub

Posted: Fri Jan 11, 2019 1:09 pm
by ValiSXP
Hi

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

Thank you

Re: C# API - tik4net on GitHub

Posted: Sat Jan 12, 2019 1:26 pm
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Sat Jan 12, 2019 1:38 pm
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Thu Feb 14, 2019 1:50 pm
by shooka
hi ;
I want to connect to mikrotik router by mobile app and after confirm connect to internet.
please suggest me solution

Re: C# API - tik4net on GitHub

Posted: Mon Feb 18, 2019 10:10 pm
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Tue Jun 11, 2019 10:20 pm
by fbritop
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

Re: C# API - tik4net on GitHub

Posted: Tue Jun 11, 2019 11:23 pm
by nescafe2002
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

Re: C# API - tik4net on GitHub

Posted: Wed Jun 12, 2019 12:11 am
by fbritop
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

Re: C# API - tik4net on GitHub

Posted: Thu Jun 13, 2019 3:40 pm
by warez
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<>

Re: C# API - tik4net on GitHub

Posted: Thu Jun 13, 2019 4:47 pm
by nescafe2002
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; }
}

Re: C# API - tik4net on GitHub

Posted: Wed Jul 10, 2019 2:25 pm
by MarkLFT
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?

Re: C# API - tik4net on GitHub

Posted: Wed Jul 24, 2019 10:14 am
by saputra19
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

Re: C# API - tik4net on GitHub

Posted: Wed Jul 24, 2019 11:21 am
by nescafe2002
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"]);
}

Re: C# API - tik4net on GitHub

Posted: Sat Sep 14, 2019 11:03 am
by supportingit
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.

Re: C# API - tik4net on GitHub

Posted: Sat Sep 21, 2019 6:27 pm
by saputra19
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 :)

Re: C# API - tik4net on GitHub

Posted: Sat Nov 09, 2019 5:12 pm
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Fri Nov 22, 2019 7:37 pm
by andreazanini
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

Re: C# API - tik4net on GitHub

Posted: Sat Nov 23, 2019 4:35 pm
by nescafe2002
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.

Re: C# API - tik4net on GitHub

Posted: Mon Dec 02, 2019 1:17 am
by danikf
/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

Re: C# API - tik4net on GitHub

Posted: Mon Dec 02, 2019 5:15 pm
by andreazanini
Many thanks nescafe, this works perfectly. Sorry if I didn't find the answer before, but now it is better documented! :)

Re: C# API - tik4net on GitHub

Posted: Sat Dec 21, 2019 5:04 pm
by bumbatik
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.

Re: C# API - tik4net on GitHub

Posted: Sun Dec 22, 2019 3:46 pm
by danikf
Can be used everywhere with supported .NET/.NETCore version.
D

Re: C# API - tik4net on GitHub

Posted: Mon Dec 23, 2019 8:28 am
by bumbatik
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.

Re: C# API - tik4net on GitHub

Posted: Tue Dec 24, 2019 9:07 pm
by bumbatik
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.

Re: C# API - tik4net on GitHub

Posted: Sun Dec 29, 2019 1:06 pm
by bumbatik
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.

Re: C# API - tik4net on GitHub

Posted: Sun Dec 29, 2019 1:28 pm
by nescafe2002
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

Re: C# API - tik4net on GitHub

Posted: Wed Jan 01, 2020 5:21 pm
by danikf
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

Re: C# API - tik4net on GitHub

Posted: Mon Jan 13, 2020 12:38 pm
by iDeedz
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?