I would like to run this function under mono ( my current version is 4.0.2)
public Object GetConnectionProperty(SqlConnection _conn, string prop)
{
if (_conn.State == ConnectionState.Closed &
prop == "ServerVersion")
return string.Empty;
if (prop == "ClientConnectionId")
{
Guid guid = _conn.ClientConnectionId;
return guid.ToString();
}
return _conn.GetType().GetProperty(prop).GetValue(_conn);
}
But it fails with the error :
error CS1061: Type `System.Data.SqlClient.SqlConnection' does not contain a
definition for `ClientConnectionId' and no extension method
`ClientConnectionId' of type `System.Data.SqlClient.SqlConnection' could be
found. Are you missing an assembly reference?
What is the Mono equivalent of ClientConnectionId
? Or how can I fix it?
ClientConnectionId
is not implemented in mono SqlConnection class. If you really want to have some unique identifier for each instance, you can do it yourself as having an id constructed from the hashcode for example:
public static class SqlClientExtensions {
#if __MonoCS__
private static Dictionary<int, string> _connIds = new Dictionary<int, string>();
#endif
public static string GetClientConnectionId(this SqlConnection conn) {
if(conn == null) {
return Guid.Empty.ToString();
}
#if __MonoCS__
if(!connIds.ContainsKey(conn.GetHashCode())) {
connIds.Add(conn.GetHashCode(), Guid.NewGuid().ToString());
}
return connIds[conn.GetHashCode()];
#else
return conn.ClientConnectionId.ToString();
#endif
}
}
then you can use it in your method:
if (prop == "ClientConnectionId")
{
return _conn.GetClientConnectionId();
}
The hash code may be repeated for 2 different instances at different points in time.
__MonoCS__
is defined only by the mono compiler. The portion calling the ClientConnectionId
property wil not be seen by mono compiler and vice versa for the other portion and .net compiler.
Another solution would be to subclass SqlConnection
and implement ClientConnectionId
but it's sealed... And also that would require subclassing some other classes that instantiate the SqlConnection
class internally.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With