C# SQL connection timeout - c#

I have a very strange case of SQL connection timeout from an application written in C# .NET.
The SqlCommand.ExecuteNonQuery() is being used to sequentially execute several scripts in SQL Server, one after another. Each script contains a command to create just one table (no data update/insert/delete operations at all). For some reason, at one of the scripts, the SqlCommand.ExecuteNonQuery throws a timeout exception.
When I execute creation of all these tables in SQL Server Management Studio, they get executed just fine and almost instantaneously.
Does anyone has an idea what could be causing timeout when the tables are created from the application?
All sql scripts look similar like following:
SQL:
create table dbo.Test
(
Code varchar(10) not null
, Name varchar(50) not null
, other columns...
primary key
, unique key
, foreign key
)
The scripts are shipped from C# using this code:
try
{
using (SqlConnection conSQL = new SqlConnection ("[connection string]"))
{
using (SqlCommand cmdSQL = new SqlCommand(sSQL, conSQL))
{
cmdSQL.CommandTimeout = iTimeOut;
conSQL.Open();
cmdSQL.ExecuteNonQuery(); // this is where it jumps to catch part and
// throws out timeout exception
conSQL.Close();
}
}
}
catch(Exception ex)
{
throw (ex);
}
This is happening on the Test server, meaning nothing else is happening on the server while the application is executing these scripts.

You can override the default time out setting for sql transactions by updating the machine.config, which can be found here:
%windir%\Microsoft.NET\Framework\[version]\config\machine.config
64-bit
%windir%\Microsoft.NET\Framework64\[version]\config\machine.config
At the end of the machine.config add or update the following line:
<system.transactions>
<machineSettings maxTimeout="01:00:00" /> --> set this to desired value.
</system.transactions>
</configuration>
If the above doesn't work, you can specify the Timeout setting for SqlCommand through code as well:
using (SqlConnection connection = new SqlConnection(connectionString)) {
connection.Open();
SqlCommand command = new SqlCommand(queryString, connection);
// Setting command timeout in seconds:
command.CommandTimeout = 3600;
try {
command.ExecuteNonQuery();
}
catch (SqlException e) {
Console.WriteLine(e);
}
}
more information here

Just stop it from running and run again your problem will be solved.... It is generally occur first time only when their are lot of files to load maybe it is bug in visual studio.
New:
After stop try to refresh open Web page (in browser where error displays ) instead of relaunch it again...

Related

ERROR:There is already an open DataReader associated with this Command which must be closed first. Multiple Users

I have an asp.net C# application (.net 4.0) connected to SQL Server 2012 using ADO.Net and am encountering an error which says:
[InvalidOperationException: There is already an open DataReader associated with this Command which must be closed first.]
I very well know what a DataReader is but, my problem is getting this error in below conditions:
I have not at all used any DataReader in my application, I have only
used DataAdapters everywhere. The code works fine while running in
local environment and there is no errors.
Application works fine even after deployment in IIS7 when used by a
single user.
The error only occurs when multiple users starts using the website hosted in IIS7.
Kindly help, I am also doubting for any problems with my hosting in IIS7
After a lot of trial and error, finally I found out that it's a problem with SqlConnections. What I used to do was open a connection at the instantiation of my DAL layer object. So, whenever two methods from the same DAL object called together, it used to throw the error.
I solved it by opening and closing a connection in every call to the database. Now it all works fine. This also allows max number of users to use the application at a time. Below is my code sample from DAL:-
DataTable dt = new DataTable();
try
{
using (SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ToString()))
{
if (sqlcon.State == ConnectionState.Closed)
sqlcon.Open();
SqlCommand sqlCommand = new SqlCommand
{
Connection = sqlcon,
CommandType = CommandType.StoredProcedure,
CommandText = "MyStoredProc"
};
sqlCommand.Parameters.AddWithValue("#Parameter1", Parameter1);
using (SqlDataAdapter adapter = new SqlDataAdapter(sqlCommand))
{
adapter.Fill(dt);
}
}
return dt;
}
catch (Exception exp)
{
LogHelper.LogError(string.Concat("Exception Details: ", ExceptionFormatter.WriteExceptionDetail(exp)));
throw exp;
}
finally
{
dt.Dispose();
}
Please post a better way of doing it if you know any, thank you.

Sending time to SQL Server Management Studio table but it does not display?

I am currently writing an application which involves a user being able to write the time to a database by clicking a button. The problem is that the data will be send to the database table, but it does not show the time in SQL Server Management Studio.
This is my query:
{
string query = "insert into Sign_In_Out_Table(Sign_In)Values('"+ timetickerlbl.ToString()+ "')";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.AddWithValue("#SignIn", DateTime.Parse (timetickerlbl.Text));
//cmd.ExecuteNonQuery();
MessageBox.Show("Signed in sucessfully" +timetickerlbl);
con.Close();
}
The datatype in SQL Server is set to datetime.
I'm open for suggestions to find a better way to capture the PC's time and logging it in a database.
Don't wrap the variable in ' when you are setting value with Parameters.Add(), or Parameters.AddWithValue() as they would wrap if needed.
The variable in here would be the value of Sign_In and not the Sign_In itself.
Always use Parameters.Add() instead of Parameters.AddWithValue():
string query = "insert into Sign_In_Out_Table(Sign_In) Values(#value)";
SqlCommand cmd = new SqlCommand(query, con);
cmd.Parameters.Add("#value", SqlDbType.DateTime).Value = DateTime.Parse(timetickerlbl.Text);
Edit (Considering your comment):
If still it does not insert it, of course there is an error in your code, it could be a syntax error, invalid table or column name, connection problem ,... so put your code in a try-catch block (if it isn't already) and see what error you you get, it should give you a hint:
try
{
//the lines of code for insert
}
catch(Exception ex)
{
string msg = ex.Message;
// the above line you put a break point and see if it reaches to the break point, and what the error message is.
}
Your table does not contain your timestamp because you have commented the execution of your query. Presumably you added the comment because this line was throwing an error, remove the comment and share the error with us.
cmd.ExecuteNonQuery();

Update SQL table through C# code

I want to update a table through sql code executed in a c# application. To do this, I've used the alter data generated my MSSMS and manually saved it as an sql-file. The c# then reads the file and tries to execute it but it can't. If I use the sql code by itself it works, but not when read by the c# funtion. What's wrong with my c# code?
The sql code generated my MSSMS:
/* To prevent any potential data loss issues, you should review this script in detail before running it outside the context of the database designer.*/
BEGIN TRANSACTION
SET QUOTED_IDENTIFIER ON
SET ARITHABORT ON
SET NUMERIC_ROUNDABORT OFF
SET CONCAT_NULL_YIELDS_NULL ON
SET ANSI_NULLS ON
SET ANSI_PADDING ON
SET ANSI_WARNINGS ON
COMMIT
BEGIN TRANSACTION
GO
ALTER TABLE dbo.tTest ADD
NewColumn int NULL
GO
ALTER TABLE dbo.tTest SET (LOCK_ESCALATION = TABLE)
GO
COMMIT
The c# code that reads it:
string content = string.Empty;
try
{
content = File.ReadAllText(string.Format(#"C:\temp\{0}.sql", name));
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand command = new SqlCommand(content, conn);
command.Connection.Open();
command.ExecuteNonQuery();
command.Connection.Close();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
The output that comes from the c# function (the console message):
A first chance exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Incorrect syntax near 'GO'.
Incorrect syntax near 'GO'.
Each batch (ended with GO) should be sent separately in one command.ExecuteNonQuery(). This method is not to be used for multiple batches.
Split your query into several pieces (where GO is) and execute it step by step.
The core issue with the script you are trying to run is wrapping a transaction around query batches (A query batch is terminated with a GO statement in SQL Server Management Studio).
To do the operations in C# you can execute both statements in one query batch. They do not require to be separate. If you wrap them in one query in a SqlCommand object you do not need to handle transactions as there is an "implicit" transaction created.
A last point to look out for is proper disposal of the objects implementing IDisposable. The easiest way to do this in C# is by wrapping them in a using clause. Once you did that, there is no more need to call the Close method on the command/connection objects.
Combining all these remarks gives you the following code:
try
{
using(var conn = new SqlConnection(ConnectionString))
using(var command = new SqlCommand(
#"ALTER TABLE dbo.tTest ADD NewColumn int NULL;
ALTER TABLE dbo.tTest SET (LOCK_ESCALATION = TABLE);", conn))
{
conn.Open();
command.ExecuteNonQuery();
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Using database connection in separate form

I have my main form which has a datagrid view connected to a database. Then I have a button that opens a separate form and I've got a few buttons etc on that secondary form.
I need to query the database from the secondary form but I'm not sure how to do that without creating a whole new connection, which I don't think I need since the program is already connected to the database. I'm just not sure how to reference the oleDB connection I made in that first form (I didn't code it in, I used the little arrow on the datagridview to connect it to the database using visual studio)
Now instead of creating that new connection, how do I reference the first connection made in the primary form?
Here is my code:
//parameterized update query
string updateCommandString = "UPDATE RoomsTable SET [Date Checked]=#checkedDate WHERE ID = #id";
using (OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\users\spreston\documents\visual studio 2012\Projects\roomChecksProgram\roomChecksProgram\roomsBase.accdb"))
{
using (OleDbCommand updateCommand = new OleDbCommand())
{
OleDbTransaction transaction = null;
updateCommand.Connection = conn;
updateCommand.Transaction = transaction;
updateCommand.CommandText = updateCommandString;
updateCommand.CommandType = CommandType.Text;
updateCommand.Parameters.AddWithValue("#checkedDate", this.dateTimePicker1.Value.ToShortDateString());
updateCommand.Parameters.AddWithValue("#id", row.roomID);
try
{
conn.Open();
transaction = conn.BeginTransaction();
updateCommand.Transaction = transaction;
updateCommand.ExecuteNonQuery();
transaction.Commit();
conn.Close();
conn.Dispose();
}
catch(OleDbException ex)
{
MessageBox.Show(ex.Message.ToString());
}
}
}
From a design standpoint, you should consider making a data access layer for your forms to utilize. You can create methods to retrieve those Db results for you so you consolidate that code and separate it from your form functionality. It may be just a small project, but it's good practice and if it's a project you want to grow, you'll want it laid out to be extendable.
Something like
class SomethingDA {
static DataTable GetMyStuff(your params) {
// establish connection, get your results
}
}
You can then call SomethingDa.GetMyStuff() to get what you need.
If you are Using the "Using" statement, your connection is closed after this code is run. You don't in fact need the conn.Close() and conn.Dispose() statements. Using does that for you.
Your best bet is to open up the connection again. It is generally a good practice to open and close connections as quickly as possible, although likely less important if your Access DB local. This generally does not impact performance too much as the OLE DB driver behind the scene will pool the connection and keep it open for a period of time.

c# application crashes on ShowDialog() after running oledbconnection

I have been working on a c# project that connects to a access database, but a certain sequence of events causes it to crash with a AccessViolationException
The issue comes after calling a database connection using oledb in a separate form than the savefiledialog, and than calling savefiledialog1.ShowDialog()
Note: This also applies to the open file dialog.
It might be a bug in Access Database Engine 2010. Use 2007 instead.
connect.microsoft.com: oledb-operations-cause-accessviolationexception-during-savefiledialog
Codeproject: OpenFileDialog + OleDbConnection = AccessViolationException
Be sure you are using System.Data.OleDb from System.data.dll
Then try something like this:
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// Declare Command
OleDbCommand command = new OleDbCommand(YourSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
I had a similar issue, too, and this helped me:
I added "OLE DB Services=-1" in my connectionstring, now the problem is solved.
See: http://www.codeproject.com/Questions/106826/OpenFileDialog-plus-OleDbConnection-equals-AccessV.aspx SOLUTION 8

Categories