danikf/tik4net

ExecuteScalarOrDefault: Sequence contains no matching element

Deantwo opened this issue · 1 comments

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:

private string ExecuteScalarInternal(string target, bool allowReturnDefault, string defaultValue = null)

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");
>/snmp/print
>=.proplist=location
<!re
<=location=
<
<!done
<