When I try to connect to the database, I get the following error:
An error has occurred with the network or a specific instance while establishing a connection to SQL Server. The server was not found or was unavailable. Verify that the instance name is correct and SQL Server is configured for a remote connection. (provider: Named Pipes Provider, error: 40 - Could not open connection to SQL Server)
Now sometimes I get this error, and sometimes not, for example: When I run my program for the first time, it successfully opens the connection, and when I run the second time, I get this error the next time I start my program again, then I do not get the error.
When I try to connect to one database server via SSMS, then I can successfully connect, but I get this network problem only in my program.
The database is not in my LOCALLY . She is on AZURE .
I am not getting this error with my local database.
Code:
public class AddOperation { public void Start() { using (var processor = new MyProcessor()) { for (int i = 0; i < 2; i++) { if(i==0) { var connection = new SqlConnection("Connection string 1"); processor.Process(connection); } else { var connection = new SqlConnection("Connection string 2"); processor.Process(connection); } } } } } public class MyProcessor : IDisposable { public void Process(DbConnection cn) { using (var cmd = cn.CreateCommand()) { cmd.CommandText = "query"; cmd.CommandTimeout = 1800; cn.Open();
So, I am confused with two things:
1) ConnectionTimeout: Should I increase the connection time for the connection and this will solve my unusual connection problem?
2) Retry attempts policy:. Should I implement a retry join mechanism as shown below:
public static void OpenConnection(DbConnection cn, int maxAttempts = 1) { int attempts = 0; while (true) { try { cn.Open(); return; } catch { attempts++; if (attempts >= maxAttempts) throw; } } }
I am confused with these two options above.
Can someone suggest me what would be the best way to deal with this problem?