Community discussions

MikroTik App
 
janmohammadi
just joined
Topic Author
Posts: 5
Joined: Thu Oct 30, 2014 2:06 pm

Api for C# - Mikrotik.Net

Fri Mar 30, 2018 12:55 am

I recently published my small API library on GitHub
it's a lightweight, fast and super simple API library for Mikrotik.

https://github.com/janmohammadi/MikrotikDotNet

Nuget:
Install-Package Mikrotik.Net

Simple command with parameters (ExecuteNonQuery):
using (var conn = new MKConnection(IPADDRESS, USERNAME, PASSWORD))
{
    conn.Open();
    var cmd = conn.CreateCommand("interface pppoe-client add");
    cmd.Parameters.Add("interface", "ether1");
    cmd.Parameters.Add("Name", "Test"); // You can use PascalCase or kebab-case in parameter name.
    cmd.Parameters.Add("user","Test");
    cmd.Parameters.Add("password", "Test");
    cmd.ExecuteNonQuery();
}
Read response: (ExecuteReader):
using (var conn = new MKConnection(IPADDRESS, USERNAME, PASSWORD))
{
  conn.Open();
  var cmd = conn.CreateCommand("ip address print");
  var result = cmd.ExecuteReader();
  foreach (var line in result)
    Console.WriteLine(line);
  
}
The result (Raw API response):
!re=.id=*4=address=10.20.1.19/16=network=10.20.0.0=interface=bridge1=actual-interface=bridge1=invalid=false=dynamic=false=disabled=false
!re=.id=*5=address=172.16.0.1/30=network=172.16.0.0=interface=bridge1=actual-interface=bridge1=invalid=false=dynamic=false=disabled=false
!re=.id=*6=address=172.19.1.19/19=network=172.19.0.0=interface=bridge1=actual-interface=bridge1=invalid=false=dynamic=false=disabled=false
To query data at API level:

Filtering at API level decreases network payload and improves the performance.


using (var conn = new MKConnection(IPADDRESS, USERNAME, PASSWORD))
{
     conn.Open();
     var cmd = conn.CreateCommand("ip address print where address=172.16.0.1/30");
     var result = cmd.ExecuteReader();
     foreach (var line in result)
          Console.WriteLine(line);

}

Result:
!re=.id=*5=address=172.16.0.1/30=network=172.16.0.0=interface=bridge1=actual-interface=bridge1=invalid=false=dynamic=false=disabled=false
OR:

conn.Open();
var cmd = conn.CreateCommand("ip address print");
var condition = new MKCommandParameterCollection()
{
     new MKCommandParameter("address","172.16.0.1/3"),
     new MKCommandParameter("address","172.19.1.19/19")
};

var result = cmd.ExecuteReader(queryConditions: condition, logic: MKQueryLogicOperators.Or);
foreach (var line in result)
     Console.WriteLine(line);
Result:
!re=.id=*5=address=172.16.0.1/30=network=172.16.0.0=interface=bridge1=actual-interface=bridge1=invalid=false=dynamic=false=disabled=false
!re=.id=*6=address=172.19.1.19/19=network=172.19.0.0=interface=bridge1=actual-interface=bridge1=invalid=false=dynamic=false=disabled=false
To deserialize response: (ExecuteReader)

class MyIpAddress
{
    public string MKID { get; set; }  //MKID alwase referce to .id field in response.
    public string Address { get; set; } // Use PascalCase naming style for properties. it will convert from/to kebab-case naming.
    public string Interface { get; set; }
}
//------------------------------------------------
using (var conn = new MKConnection(IPADDRESS, USERNAME, PASSWORD))
{
    conn.Open();
    var cmd = conn.CreateCommand("ip address print");
    var result = cmd.ExecuteReader<MyIpAddress>();

    foreach (var ip in result)
        Console.WriteLine($"{ip.MKID} - {ip.Address} - {ip.Interface}");

}

Result:

*4 - 10.20.1.19/16 - bridge1
*5 - 172.16.0.1/30 - bridge1
*6 - 172.19.1.19/19 - bridge1

Note: Using method ExecuteReader only reads the fields that are present in the given type, using the .proplist field in the query.

To get dynamic object response: (ExecuteReaderDynamic)

you can get response object without defining any model class.
using (var conn = new MKConnection(IPADDRESS, USERNAME, PASSWORD))
{
    conn.Open();
    var cmd = conn.CreateCommand("ip address print");
    var result = cmd.ExecuteReaderDynamic();

    foreach (var ip in result)
        Console.WriteLine($"{ip.Id} - {ip.Address} - {ip.Interface}"); //MKID switched to Id
}
Result:

*4 - 10.20.1.19/16 - bridge1
*5 - 172.16.0.1/30 - bridge1
*6 - 172.19.1.19/19 - bridge1
Note: Using method ExecuteReaderDynamic reads all fields from the router it will increase response payload.

Read data from background commands: (ExecuteBackground)
Some commands work in the background ( like ping, bandwidth test, discovery,...)

using (var conn = new MKConnection(IPADDRESS, USERNAME, PASSWORD))
{
    conn.Open();
    var cmd = conn.CreateCommand("ping");
    cmd.Parameters.Add("address", "10.20.0.4");
    cmd.Parameters.Add("count", "3");
    cmd.Parameters.Add("interval", "1");
    cmd.ExecuteBackground();

    Thread.Sleep(5000); 
    
    var result = cmd.ExecuteReaderDynamic();
    foreach (var ip in result)
        Console.WriteLine($"{ip.Host} - {ip.Time} - {ip.Ttl}");

}
Result:

10.20.0.4 - 13ms - 128
10.20.0.4 - 6ms - 128
10.20.0.4 - 4ms - 128
 
User avatar
ammarabbasi
just joined
Posts: 10
Joined: Wed Oct 04, 2017 8:34 am
Location: Lahore

Re: Api for C# - Mikrotik.Net

Sat Oct 20, 2018 2:23 pm

Nice Effort! Appreciated.

can you guide me in general, how can I use this API to make dynamic speed monitoring app, that can display up/d n, refreshing after 5 sec.
I already know to program in c# but not an experienced programmer. just your directions will help me.

Thanks.
Ammar Abbasi.
MTCNA, MTCRE, MTCWE, MTCUME, MTCTCE, MTCINE
Lahore, Pakistan.
 
TiPoReII
just joined
Posts: 2
Joined: Mon Mar 09, 2020 2:43 am

Re: Api for C# - Mikrotik.Net

Wed Mar 25, 2020 2:06 pm

Helpe error
MikrotikDotNet.Exceptions.MKConnectionException não foi manipulada
  HResult=-2146233088
  Message=Invalid UserName or Password failed for 192.168.15.7 With User:admin and Pass:************.
  Source=MikrotikDotNet
  StackTrace:
       em MikrotikDotNet.MKConnection.Open()
       em CardHotSpot.frm_inicial.EscreverImagem() na D:\Documentos\Programacao\Visual Studio\CardHotSpot\CardHotSpot\Form1.cs:linha 719
       em CardHotSpot.frm_inicial.bt_gerar_Click(Object sender, EventArgs e) na D:\Documentos\Programacao\Visual Studio\CardHotSpot\CardHotSpot\Form1.cs:linha 705
       em System.Windows.Forms.Control.OnClick(EventArgs e)
       em System.Windows.Forms.Button.OnClick(EventArgs e)
       em System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       em System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       em System.Windows.Forms.Control.WndProc(Message& m)
       em System.Windows.Forms.ButtonBase.WndProc(Message& m)
       em System.Windows.Forms.Button.WndProc(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       em System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       em System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       em System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       em System.Windows.Forms.Application.Run(Form mainForm)
       em CardHotSpot.Program.Main() na D:\Documentos\Programacao\Visual Studio\CardHotSpot\CardHotSpot\Program.cs:linha 19
       em System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       em System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       em Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       em System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       em System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       em System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       em System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

Who is online

Users browsing this forum: No registered users and 43 guests