private static SqlConnection GetDbConnection(string connectionString, bool tryDecrypt) { var builder = new SqlConnectionStringBuilder(); try { builder = new SqlConnectionStringBuilder(connectionString); //decrypting the user id and password used, if applicable... if (tryDecrypt) { builder.UserID = StringEncryptor.DecryptWithPassword(builder.UserID, StringEncryptor.DefaultPassword); builder.Password = StringEncryptor.DecryptWithPassword(builder.Password, StringEncryptor.DefaultPassword); } } catch (Exception) { throw new DatabaseException($"The format for the connection string '{builder.ConnectionString}' is invalid."); } SqlConnection conn = null; var retry = 0; var sb = new StringBuilder(); while (retry < MAX_RETRIES) { try { conn = new SqlConnection(builder.ConnectionString); conn.Open(); if (conn.State != ConnectionState.Open) { conn.Open(); } return(conn); } catch (Exception e) { conn?.Dispose(); sb.AppendLine(e.ToString()); retry++; } } sb.AppendLine($"Could not obtain a connection to database '{builder.InitialCatalog}' on server '{builder.DataSource}'."); throw new DatabaseException(sb.ToString()); }