danikf / tik4net

Manage mikrotik routers with .NET C# code via ADO.NET like API or enjoy O/R mapper like highlevel api.
Apache License 2.0
178 stars 93 forks source link

ExecuteScalarOrDefault: Sequence contains no matching element #97

Open Deantwo opened 8 months ago

Deantwo commented 8 months ago

When calling /snmp/print with a ExecuteScalarOrDefault method and the /snmp location value is empty string, the API throws an exception.

System.InvalidOperationException: Sequence contains no matching element
   at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source, Func`2 predicate)
   at tik4net.Api.ApiCommand.ExecuteScalarInternal(String target, Boolean allowReturnDefault, String defaultValue)
   at tik4net.Api.ApiCommand.ExecuteScalarOrDefault()
   at ...

According to the stacktrace, it looks like it is happening in one of the .Single calls in: https://github.com/danikf/tik4net/blob/e286e11b69b967d7ef8979e6b799302563846610/tik4net/Api/ApiCommand.cs#L305

It probably means that the code isn't checking for empty string output correctly and or should be using SingleOrDefault instead of Single when allowReturnDefault is true.

RouterOS version: 7.9.2 MikroTik config:

/snmp set location=""

Example code:

TikConnection con = ConnectionFactory.OpenConnection(Type.Api, _host, _username, _password);
ITikCommand cmd = conn.CreateCommand("/snmp/print");
System.Diagnostics.Debug.WriteLine("reading SNMP Location");
string address = cmd.ExecuteScalarOrDefault("location");
System.Diagnostics.Debug.WriteLine("SNMP Location read");
Deantwo commented 8 months ago
>/snmp/print
>=.proplist=location
<!re
<=location=
<
<!done
<