Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerating through claims causes HttpException SqlException

I have an issue when I'm going through a 'foreach' loop on some Claims in a ClaimsIdentity. When I step through it - at the point it should finish enumerating, I see it go back into the 'in' and then a get a ten second delay before I get an HttpException regarding connection to SQL Server. I know it sounds odd, but that's when it occurs according to debugging - in the foreach loop in my FindAllClaimsByType method (I do connect to the database soon after using Entity Framework, but my breakpoints there never get hit). Edit: I should mention I can connect to my database fine if I skip over this and do something in a controller. This is in ASP.NET MVC 4

Edit 2: I've narrowed it down a little. It's only ever when it can't find a Claim. It doesn't matter how I enumerate through the claims (if I use ClaimsPrincipal.HasClaim() or a foreach loop or a .Any() LINQ expression) - it'll always throw this exception if it can't find the claim.

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

My code is as follows:

public class ClaimsService
{

    private ClaimsIdentity _identity;

    public ClaimsService(ClaimsIdentity identity)
    {
        _identity = identity;
    }

    private Claim FindFirstClaimByType(string claimtype)
    {
        return FindAllClaimsByType(claimtype).FirstOrDefault();
    }

    private IEnumerable<Claim> FindAllClaimsByType(string claimtype)
    {
        ICollection<Claim> claims = new Collection<Claim>();
        foreach (Claim claim in _identity.Claims)
        {
            if (claim.Type == claimtype)
            {
                claims.Add(claim);
            }
        }

        return claims;
    }

    public School FindSchoolFromClaims()
    {
        string realm = FindFirstClaimByType(Data.Configuration.RealmClaimType).Value.ToString();

        using (SqlDatabaseContext db = new SqlDatabaseContext())
        {
            School school = null;


            school = db.Schools.Where(s => s.Realm == realm).FirstOrDefault();

            return school;
        }
    }

    public Developer FindDeveloperFromClaims()
    {
        string realm = FindFirstClaimByType(Data.Configuration.RealmClaimType).Value.ToString();
        string nameidentifier = FindFirstClaimByType(ClaimTypes.NameIdentifier).Value.ToString();

        using (SqlDatabaseContext db = new SqlDatabaseContext())
        {
            Developer developer = null;


            if (realm == Data.Configuration.SoloDeveloperRealmMsft)
            {
                developer = db.Developers.OfType<SoloDeveloper>().Where(dev => dev.NameIdentifier == nameidentifier).FirstOrDefault();
            }
            else
            {
                developer = db.Developers.OfType<CompanyDeveloper>().Where(dev => dev.Realm == realm).FirstOrDefault();
            }

            return developer;
        }
    }
}

Stack trace:

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)] System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action1 wrapCloseInAction) +5296071 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +558 System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +5308555 System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +145 System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +920 System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +307 System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions) +434 System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +5311099 System.Data.ProviderBase.DbConnectionFactory.CreateNonPooledConnection(DbConnection owningConnection, DbConnectionPoolGroup poolGroup, DbConnectionOptions userOptions) +38 System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +5313314 System.Data.ProviderBase.DbConnectionClosed.TryOpenConnection(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource1 retry, DbConnectionOptions userOptions) +143 System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource1 retry) +83 System.Data.SqlClient.SqlConnection.Open() +96 System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +76

[HttpException (0x80004005): Unable to connect to SQL Server database.] System.Web.Management.SqlServices.GetSqlConnection(String server, String user, String password, Boolean trusted, String connectionString) +131 System.Web.Management.SqlServices.SetupApplicationServices(String server, String user, String password, Boolean trusted, String connectionString, String database, String dbFileName, SqlFeatures features, Boolean install) +89 System.Web.Management.SqlServices.Install(String database, String dbFileName, String connectionString) +27 System.Web.DataAccess.SqlConnectionHelper.CreateMdfFile(String fullFileName, String dataDir, String connectionString) +386

like image 990
Nick Darvey Avatar asked Mar 16 '13 11:03

Nick Darvey


1 Answers

I had the same issue with a brand-new ASP MVC web role in an Azure cloud solution. No SQL was setup yet, and no other functionality, except Azure ACS federated signon had been implemented yet. I was just testing the functionality of ACS, WIF, and multiple identity providers.

It seems that RoleManager functionality is baked in by default. Once I removed it in the web.config - no more attempts at SQL Server access when enumerating claims.

Add this line:

  <modules>
     <remove name="RoleManager" />
     ...

Hope That helps.

Rick Shuri

like image 176
Rick Shuri Avatar answered Oct 23 '22 23:10

Rick Shuri