Limit ConnectionTimeout for Oracle Database - c#

How can I limit timeout for connecting to Oracle Database? I use devart dotConnect Express Edition on data access layer. I tried add Connection timeout=30; to connection string but it doesn't give right result (even a little weird, first time it really limits to 30 seconds, but not on all connection attempts). Then I find out that
Connection Timeout Time (in seconds) to wait while trying to establish
a connection before terminating the attempt and generating an error. A
value of 0 indicates no limit. The default value is 15 seconds.
Available in Direct mode only.
from Devart site
I can't use direct mode because I use Express Edition. Then I tried to set this parameters in TNSNAMES.ORA
DB1 =
(DESCRIPTION =
(CONNECT_TIMEOUT=11)
(TRANSPORT_CONNECT_TIMEOUT=10)
(ADDRESS_LIST =
(ADDRESS = (PROTOCOL = TCP)(HOST = 10.10.100.8)(PORT = 1521)
)
)
(CONNECT_DATA =
(SERVICE_NAME = DB1)
)
)
Still works incorrect. OK, going down and try yo set connection timeout in SQLNET.ORA
SQLNET.INBOUND_CONNECT_TIMEOUT = 5
Another one fail! Does anyone know how can I set timeout restricting allowing time to connect to DB1? It now finishes connection (connection fails) for approximately 20 seconds.

I've never used Devart's dotConnect library, but looking at the OracleConnection class it seems that you should be able to close the connection after a certain period of time by calling OracleConnection.Close(). This should take you out of the blocking state while you're trying to Open the connection.
This is not exactly like setting the timeout, but it may work. Furthermore, check the ConnectionTimeout property when you're debugging this code in order to confirm that the timeout is properly set.

OracleConnection.ConnectionTimeout works in Direct mode only. It is ignored when connection is established via Oracle client, which manages connection in this case.

Related

Adding Keepalive option to MySQL connection causes error "Unable to connect to any of the specified MySQL hosts"

I am working on a project where a thread is run and opens a permanent database connection. The reason for this, is potentially as the project grows it could receive more and more requests so it's more efficient to keep the database open and usable instead of opening and closing the database.
Basically what the thread does is look for events in a queue, and if there is an event it starts working on the database to store and process the event. At its peak this thread could receive 50,000-100,000 requests a day potentially a lot more, as more and more users (hopefully) use the service.
However, because it's new, there are times where this thread doesn't have anything to do, so I end up hitting the exception "The connection must be valid and open" and I believe this is because the connection to the database is automatically dropped over 8 hours of inactivity. At the moment this can happen so I am trying to add a Keepalive option to the connection so this doesn't happen but for some reason, as soon as I add this, I then get the error "Unable to connect to any of the specified MySQL hosts".
I am using a MysqlConnectionStringBuilder as follows:
MySqlConnectionStringBuilder connectionBuilder = new MySqlConnectionStringBuilder();
connectionBuilder.Server = server;
connectionBuilder.UserID = username;
connectionBuilder.Password = password;
connectionBuilder.Port = 3306;
//Open the connection
MySqlConnection conn = new MySqlConnection(connectionBuilder.ConnectionString);
conn.Open();
This above works perfectly fine until I add the following:
connectionBuilder.Keepalive = 60;
When the above line is added is when I then get the error.
I am using a TCP connection as it's a remote connection from my Dev PC to a dev server - is there a setting on the server to enable this? as everything I've found on Google this option is all that's required.

SQL Server TimeOut in C# After Adjusting timeout

I have a windows form application written in C# that passes a query to a SQL Server database and then displays the results in a dataviewgrid. The query that is passed to the database depends on the option selected in the form.
One particular query takes a little over a minute to run in management studio, but timeouts when it is passed to the database from the program. here are the steps I have done to try to resolve the situation:
Added a 5 minute timeout in the program by setting the connection timeout option to 300 seconds in the sql connection string. Example: Data Source=ab;Initial Catalog=abc;User ID=user; Password =pw; Connection Timeout=300
Setting the remote query timeout in the SQL Server instance to 0 (meaning, no timeout). Example: EXEC sp_configure 'remote query timeout', 0 ; GO
Neither of these options work. Despite implementing both of them, the c# program throws back a sql timeout error after less than a minute.
Is there a workaround for this? I have searched for this topic on stack overflow and so far all of the suggestions have been to do either 1 or 2 (which I have done).
For reference, I am using Visual Studio 17 Community edition and SQL Server 2016 Developer edition.
Any help would be greatly appreciated.
Thanks!
There's a "CommandTimeout" property on the SQL command. Try setting that.
Connection timeout and command timeout are two different things.
A connection timeout occurs when a connection cannot be retrieved from the connection pool within the allotted timeout period.
A command timeout occurs when a connection has been retrieved, but the query being executed against it doesn't return results within the allotted command timeout period. The default command timeout period in ADO.NET is 30 seconds.
If you've set the connection timeout to 300 seconds and you're still getting a timeout, it's likely a command timeout. As walkers01 said, set your command timeout to a suitable number of seconds. 300 seconds should be far more than sufficient; if your query executes in one minute in SSMS, a timeout of 90 seconds should suffice.
Try this for unlimited time of query execution if you are using SqlDataAdapter. I have use this one, solved my problem.
SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
dscmd.SelectCommand.CommandTimeout = 0;

How to prevent connection time out when trying to select big data through looping in C#?

Recently,I have to develop a system which will fetch huge data from SQL Server 2008 R2. And then need to create HL7 messages using these data and send these HL7 messages to another application. I need to fetch data and create HL7 messages within looping also. The problem I am facing is that connection time out when 1 or 2 minutes after running the application.How can I prevent this problem? What should I do?
Modifying the connection string in the web.config , you could append ;Connection Timeout=30. The timeout value set in the Connection Timeout property is a time expressed in seconds.
Please Refer Connection Time out
setting the timeout value to 0, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string.
A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.

Connection.open for hangs indefinitely, no exception is thrown

When I try to do the following code, the program hangs indefinitely. I don't know why and there seems to be other unanswered topics on the matter. Although, if the IP\website cannot be reached, then it works as intended.
private void DoStuff()
{
string connectionString = "Data Source=www.google.com;Connection Timeout=5";
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open(); //Hangs here indefinitely
Console.WriteLine("Test");
}
}
For example, if I set the connection string to
connectionString = "Data Source=www.nonexistentsite.com;Connection Timeout=5";
then it will throw an exception. How do I get it to throw an exception for an active site? ... Also google is just for testing purposes, obviously.
EDIT :
If I try to connect to an unreachable server name or IP address I WILL get this exception...
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: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
UPDATE :
After letting the program run for quite a while, it usually times out finally after 3-5 minutes and gives me the error I posted above. How can I get it to timeout quicker?
If you have set an FQDN (Fully Qualified Domain Name) for your Data Source such as example.com and the DNS server is unable to resolve this FQDN for a long time it is pretty obvious that your request will hang out. Make sure that the machine from which you are running your application can reach the SQL server and resolve it without any issues. Also you probably want to make sure that there is no firewall that might be blocking the request.
Another possible cause for those symptoms is if you have exhausted the connection pool of ADO.NET. This could happen if you have many slow SQL queries running in parallel, each of them taking a physical connection to the database. There is a limit in the number of available connections on this pool and when this limit is reached the next call to connection.Open() might wait for an available connection to be returned to the pool.
Remark: you might also need to specify in your connection string how you want to authenticate against the SQL server. Checkout connectionstrings.com for more examples.
All this is to say that there is absolutely nothing wrong in the C# code you have posted in your question. It looks more like a network related problem that you could bring to the attention of your network administrators.
To get the connection to exit after a specified amount of time without success, you can use the Connection Timeout parameter in the connection string. The number you specify is in seconds, so for example, Connection Timeout=240 is equal to 240 seconds\60 seconds = 4 minutes.
Sample connection string:
<add name="MyConnectionString"
connectionString="
Data Source=MyServer\MSSQL2017;
Initial Catalog=MyDatabase;
Integrated Security=True;
Connection Timeout=10;"/>
In the above connection string, the Open() command will timeout after 10 seconds.

Solving a timeout error for SQL query

I am getting this error:
Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
I know there are already guides out there to help solve this but they are not working for me. What am I missing or where should I add the code to these SQL statements in my C# program:
String sql = project1.Properties.Resources.myQueryData;
SqlDataAdapter sqlClearQuestDefects = new SqlDataAdapter(sql,
"Data Source=ab;Initial Catalog=ac;User ID=ad; Password =aa");
DataSet lPlanViewData = new DataSet();
sqlClearQuestDefects.Fill(lPlanViewData, "PlanViewData");
I am getting the timeout error at this line:
SqlDataAdapter sqlClearQuestDefects = new SqlDataAdapter(sql,
"Data Source=ab;Initial Catalog=ac;User ID=ad; Password =aa");
SqlDataAdapter adp = new SqlDataAdapter();
adp.SelectCommand.CommandTimeout = 0; // Set the Time out on the Command Object
You're trying to connect to a SQL Server, and it is taking longer than ADO.NET is willing to wait.
Try connecting to the same server, using the same username and password, using SQL Server Management Studio. If you get the same error, there is either something wrong with your connection string, the server you specify is not running, or you can't get to the server across the network from where you are (maybe you're on a public IP address trying to get in to an internal server name). I can't think of a scenario in which you'd enter the exact same server and credentials into SSMS and connect, then do the same in ADO.NET and fail.
If you're on a slow network, you can try increasing the timeout value. However, if a connection is going to happen at all, it should happen pretty quickly.
Take a look at both your SQL Native Client settings, and the SQL Server settings on the server. There is a section for allowed protocols; SQL can connect using a variety of protocols. Usually, you want TCP/IP for a server on the network, and Named Pipes for a server running on your own computer.
EDIT FROM YOUR COMMENT: Oh, that's normal; happens all the time. From time to time on a TCP network, packets "collide", or are "lost" in transmission. It's a known weakness of packet-switching technologies, which is managed by the TCP protocol itself in most cases. One case in which it isn't easily detected is when the initial request for a connection is lost in the shuffle. In that case, the server doesn't know there was a request, and the client didn't know their request wasn't received. So, all the client can do is give up.
To make your program more robust, all you have to do is expect a failure or two, and simply re-try your request. Here's a basic algorithm to do that:
SqlDataAdapter sqlClearQuestDefects;
short retries = 0;
while(true)
{
try
{
sqlClearQuestDefects = new SqlDataAdapter(sql, "Data Source=ab;Initial Catalog=ac;User ID=ad; Password =aa");
break;
}
catch(Exception)
{
retries++;
//will try a total of three times before giving up
if(retries >2) throw;
}
}
Since the exact command to increase connection time out wasn't mentioned in the other answers (of yet)- if you do determine a need to increase your connection time out, you would do so in your connection string as follows:
Data Source=ab;Initial Catalog=ac;User ID=ad; Password =aa; Connection Timeout=120
Where 120 = 120 seconds. Default is 20 or 30 as I recall.
This is probably a connection issue with your database, for example if you had the following connection string:
"Data Source=MyDatabaseServer...
Then you need to make sure that:
The machine MyDatabaseServer is connected to the network and is accessible from the machine you are running your application from (under the name "MyDatabaseServer")
The database server is running on MyDatabaseServer
The database server on MyDatabaseServer is configured to accept connections from remote machines
The firewall settings both on the local machine and MyDatabaseServer are correctly set up to allow SQL Server connections through
Your username / password etc... are correct
You can also try connecting to the given database instance using SQL Server Management Studio from the client machine as a diagnosis step.
There are plenty of articles that address SQL Server connectivity issues - do a Google search for the specific error message that comes up or failing that as a specific question on Server Fault
Faced this problem recently and found the resolution that worked for me.
By the way, setting Timeout = 0 helped to avoid the exception, but the execution time was unreasonable, while manual execution of the store procedure took a few seconds.
Bottom line:
I added SET IMPLICIT_TRANSACTIONS OFF to the stored procedure that is used to fill the data set.
From MSDN:
The SQL Server Native Client OLE DB Provider for SQL Server and the
SQL Server Native Client ODBC driver automatically set
IMPLICIT_TRANSACTIONS to OFF when connecting. SET
IMPLICIT_TRANSACTIONS defaults to OFF for connections with the
SQLClient managed provider, and for SOAP requests received through
HTTP endpoints.
[...]
When SET ANSI_DEFAULTS is ON, SET IMPLICIT_TRANSACTIONS is ON.
So I believe that in my case defaults weren't as required. (I couldn't check that. Don't have enough privileges on SQL server). But adding this line to my SP solved the problem.
IMPORTANT: In my case I didn't need the transaction, so I had no problem to cancel the implicit transaction setting. If in your case transaction is a must you, probably, shouldn't use this solution.

Categories

Resources