Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mono equivalent of ClientConnectionId

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?

like image 484
agstudy Avatar asked Jul 11 '15 06:07

agstudy


1 Answers

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();
}

P.S.:

The hash code may be repeated for 2 different instances at different points in time.

P.S.(2):

__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.

P.S.(3):

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.

like image 74
manji Avatar answered Nov 09 '22 03:11

manji