SqlClient.SqlException: The wait operation timed out - c#

I'm currently trying to create a large amount of test data with numerous insert statements using code similar to below...
using (var connection = new SqlConnection(_connectionString))
{
using (var command = new SqlCommand(query.ToString(), connection))
{
try
{
connection.Open();
command.ExecuteNonQuery();
return true;
}
catch (Exception e)
{
......
}
}
}
My problem is that I keep getting an error
The wait operation timed out
and yet when I run the SQL statement that failed from within SQL Server Management Studio, it executes in less than 100ms. The error always seems to occur whilst inserting into the largest table which currently has 47,738,476 rows and is 1,970,696Kb in size.
I'm using:
Microsoft SQL Server 2012 (SP1) - 11.0.3128.0 (X64)
Express Edition (64-bit) on Windows NT 6.1 <X64> (Build 7601: Service Pack 1)
Any, help would be most appreciated.

Disclaimer: It may not be an answer but it solves the problem :)
Use Redgate Sql Data Generator
http://www.red-gate.com/products/sql-development/sql-data-generator/
It is not free but it is fully functional trial for some days and it will do the work for you what i want to
achieve.
It had lot of option and generate real looking data.

Related

C# Sql LocalDB Application Slow Performance

I am completely new sql/database applications and am trying out a simple contact management applicaton using Visual Studio 2015 C#. I am using 'SQL Express LocalDB'. I have read on google that it is meant for development purpose, but microsoft also mentions that it could be used for production purpose too.
My problem is that when I try out the application from my developement system, the application first time takes few seconds to load but after that every query runs quickly. When I tried this on one my friends system, it takes time everytime I try to use any query. The database is just with 20-30 records.
I create new connection using 'new SqlConnection' and then execute command created by 'new SqlCommand' and after executing query I close the connection.
Here is the code snippet from my app
SqlConnection sqlConnection = new SqlConnection(#"Data Source = (LocalDB)\MSSQLLocalDB; AttachDbFilename = ""C:\ContactsDB.mdf""; Integrated Security = True; Connect Timeout = 30";);
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.Connection = sqlConnection;
sqlCmd.CommandText = "SELECT Id, first_name, last_name from ContactsMaster ORDER BY first_name";
sqlConnection.Open();
SqlDataReader reader = sqlCmd.ExecuteReader();
try
{
while (reader.Read())
{
ListViewItem lvi = new ListViewItem(reader["first_name"]);
listViewItems.Add(lvi);
lvi.SubItems.Add(reader[0].ToString());
}
}
finally
{
reader.Close();
}
sqlConnection.Close();
Q. Should I keep the connection open all the time while app is running? I don't think this should be suggested. As if app crashes database can get corrupt.
One of the backdrop which ppl saying that LocalDB closes the connection every new milliseconds. So should I keep pinging the database every few milliseconds? Or I should not use localdb in production at all?
I want to make the app such that the requirement goes really low regaridng the database prerequisites. Like LocalDB installation is really seamless.
I have not used SQL Server Express, does Express installation is also seamless like LocalDB and can I use the connection string like LocalDB in Express too, giving the .mdf filename directly?
localdb has auto shutdown. default is 5 min. you can set it to higher value (ie: 12hour).
max is 65535 min.
see: How to prevent SQL Server LocalDB auto shutdown?
also sqlexpress autoshutdown is 1hour if im not wrong.
symptoms on my pc:
first open is 10- 30 seconds slow. if i reopen app right after it is below 1 second. if i wait for a while it is slow again
There are many things to take in count for ddbb performance, it's not a simple question. For such small amount of records there shouldn't be performance problems. Try storing the ddbb files in another disk different from OS disk, and even better, place data file and log file in different disks too.
About your question, connections must be always closed and disposed properly in a finally block or inside a using block.
Sql Express is very easy to install, and also use a connection string, been the biggest difference that it can be used across the network.
Finally moved to SQLite and that is much faster in compare to SQLLocalDB.

Uninstall SQL Server Express 2005 then install SQL Server 2008 R2 Express in C# ClickOnce Winform App

My app is deployed internally using ClickOnce and has a prerequisite of SQL Server 2005 Express.
I want to upgrade my user's to SQL Server 2008 R2 Express. What are my options that don't involve me 'touching' all 300 laptops?
My idea, in theory only, was to drop the SQL Server Express prereq completely, put an 'upgrade' prompt in my app and give the users a couple days to click it, then re-add SQL Server Express as a prereq but as the new version.
I think this would work though I am open to suggestions otherwise. However, my actual question is how I can accomplish my 'upgrade' prompt. How do I uninstall SQL Server Express in a C# Winform app?
Thanks,
See this MSDN article on how to install SQL Server 2008 R2 silently (but why not do 2012 instead? :)
A quick cheat is (I have done this with non express editions, but should be the same process) to go through manual upgrade first to gather all the answers for the config and settings, and just before executing actual upgrade, in the final step you should see towards the bottom a path to the answer (ini) file (see below image), if you cancel and grab that file, you can run it in command line like Setup.exe /ConfigurationFile=MyConfigurationFile.INI
Once you test it out, you should be able to create something that pulls the binaries and answer file into the user's pc, and spawn a process to run the setup in silent mode. Though you should make sure your users are admins first of course.
To Uninstall: Run setup with the uninstall option like Setup.exe /Action=Uninstall /FEATURES=SQL,AS,RS,IS,Tools /INSTANCENAME=MSSQLSERVER, see the Uninstall Parameters section. If my memory serves me well, you can actually just do Setup.exe /Action=Uninstall /INSTANCENAME=MSSQLSERVER to remove everything for the particular instance you wish to remove, but I may be wrong, so test first
I'm working on a similar requirement to automate an upgrade from SQL 2005 Express to SQL 2008 R2 Express from a WinForms application.
You don't actually have to uninstall SQL 2005 to do the upgrade. You can just upgrade straight from 2005 to 2008R2 without any uninstall required.
My code looks something like this (modified to simplify and remove proprietary stuff)...
try
{
//First, find the version of the currently installed SQL Server Instance
string sqlString = "SELECT SUBSTRING(CONVERT(VARCHAR, SERVERPROPERTY('productversion')), 0, 5)";
string sqlInstanceVersion = string.Empty;
//_database was initialized elsewhere - it's from Enterprise Library
using (DbCommand cmd = _database.GetSqlStringCommand(sqlString))
{
sqlInstanceVersion = cmd.ExecuteScalar().ToString();
}
if (sqlInstanceVersion.Equals(String.Empty))
{
//TODO throw an exception or do something else
}
//11.00 = SQL2012, 10.50 = SQL2008R2, 10.00 = SQL2008, 9.00 = SQL2005, 8.00 = SQL2000
switch (sqlInstanceVersion)
{
case "11.00":
case "10.50":
case "10.00":
//Log that the version is already up to date and return
return;
case "9.00":
case "8.00":
//We are on SQL 2000 or 2005, so continue with upgrade to 2008R2
break;
default:
//TODO throw an exception for unsupported SQL Server version
break;
}
string upgradeArgumentString = "/Q /ACTION=upgrade /INSTANCENAME={0} /ENU /IACCEPTSQLSERVERLICENSETERMS";
string instanceName = "YourInstanceNameHere";
string installerFilePath = AppDomain.CurrentDomain.BaseDirectory + "\\SQLEXPR_x86_ENU.exe";
if (!File.Exists(installerFilePath))
{
throw new FileNotFoundException(string.Format("Unable to find installer file: {0}", installerFilePath));
}
Process process = new Process
{
StartInfo = { FileName = installerFilePath, Arguments = String.Format(upgradeArgumentString, instanceName), UseShellExecute = false }
};
process.Start();
if (process.WaitForExit(SQLSERVER_UPGRADE_TIMEOUT))
{
//Do something here when the process completes within timeout.
//Probably look at exit code, or whatever to determine if it was successful
}
else
{
//The process exceeded timeout. Do something about it; like throw exception, or whatever
}
}
catch(Exception ex)
{
//Handle your exceptions here
}

Disparity between SqlReader execution times on same .NET project but different computers

I'm working on a team project that reads data from a MSSQL server. We are using an asynchronous call to fetch the data.
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
SqlCommand cmdData = new SqlCommand("get_report", conn);
cmdData.CommandType = CommandType.StoredProcedure;
conn.Open();
IAsyncResult asyResult = cmdData.BeginExecuteReader();
try
{
SqlDataReader drResult = cmdData.EndExecuteReader(asyResult);
table.Load(drResult);
}
catch (SqlException ex)
{
throw;
}
The project itself uses TFS source control with gated check-ins, and we have verified that both computers are running the exact same version of the project. We are also using the same user login and executing the stored procedure with the exact same parameters (which are not listed for brevity).
The stored procedure itself takes 1:54 to return 42000 rows under SQL Server Management Studio. While running on Windows 7 x86, the .NET code takes roughly the same amount of time to execute as on SSMS, and the code snippet above executes perfectly. However, on my computer running Windows 7 x64, the code above encounters an error at the EndExecuteReader line at the 0:40 mark. The error returned is "Invalid Operation. The connection has been closed."
Adding cmdData.CommandTimeout = 600 allows the execution to proceed, but the data takes over 4 minutes to be returned, and we are at a loss as to explain what might be going on.
Some things we considered: my computer has .NET 4.5 Framework installed, is running 64-bit OS against 32-bit assemblies, may be storing information in the local project file that isn't being synchronized to the TFS server. But we can't seem to figure out exactly what might actually be causing the disparity in times.
Anyone have any ideas as to why this disparity exists or can give me suggestions of where to look to isolate the problem?
Invalid Operation error is received when EndExecuteReader was called more than once for a single command execution, or the method was mismatched against its execution method.

SQL-CLR stored procedure doesn't return value

I looked through Stackoverflow and found almost identical question here. It was asked a year ago and nobody answered it yet. Maybe I'll be more lucky than user1038334 and somebody will help me.
I have a SQL CLR stored procedure which works fine for days until something weird happens. My stored proc updates tables and returns a value as a result code. So by looking at this value I can decide if something went wrong. The problem is in receiving this result value. C# code throws an exception at a point of receiving a return value.
var returnValue = new SqlParameter {Direction = ParameterDirection.ReturnValue};
command.Parameters.Add(returnValue);
connection.Open();
command.ExecuteNonQuery();
return (int)returnValue.Value; //<-- here is an exception
And the funniest thing is that if I connect SQL Profiler, catch the query and then execute this query inside of SQL Server Management Studio I still can get a result value without any problems:
DECLARE #RC INT
EXECUTE #RC = MyClrStoreProc
SELECT #RC
Once I republish the CLR assembly or restart SQL Server everything gets fixed.
I'm pretty sure there should be a reason for such weird behaviour but I can't find.
SQL Server version: Microsoft SQL Server Developer Edition (64-bit) - v.10.50.1765.0
Host OS version: Microsoft Windows NT 6.1 (7601)
.Net version: v4.0.30319
Any help would be greatly appreciated.
This is a SQL Server bug and Cumulative Update package 8 fixes the issue.

Server cannot connect to SQL server

I have a C# Service project where I am connectiong to SQL and retrieving data.
When I debug locally eg: in the Visual Studion Developement Server it works nice.
But when I upload to the server(simply localhost/MyProject/) The SqlCommand() is throws an exception. Are there way to get more information on SqlCommand()?
What permissions I should set to run web service on the server?
Maybe mode details:
The project within VS2008 envirenoment is works nice:
http://localhost:50301/GetJpeg.aspx?ra=224.5941&dec=-1.09&width=1000&height=1000&scale=1
but on the http://localhost/GetJpeg.aspx?ra=224.5941&dec=-1.09&width=1000&height=1000&scale=1 no.
The exception is not really exception the:
SqlDataReader reader does not return any result in second case:
reader = cmdCenter.ExecuteReader();
if (reader.Read())
{
//Do Something
reader.Close();
}
else
{
throw new Exception("Request is failed");
}
Thanks Arman.
EDIT
Just for information:
In one case the code is debugged via ASP.NET Developement Server and the second one is running on IIS 7.0
UPDATE
After deep digging I discovered: The connection is open and connected, usual queries is ok, but queries with stored functions are failing... can be that IIS miss configuration ?
If you are using the SqlCommand control (drag-dropped onto a page) instead of the SqlCommand object (code), your best bet will be to add a page-level error handler (http://msdn.microsoft.com/en-us/library/ed577840.aspx).
Most likely, the problem is that your connection string uses SSPI for authenticating to the SQL Server (integrated/domain security). That would allow you to connect via Visual Studio, but not once it is deployed. You might want to look at this article (http://msdn.microsoft.com/en-us/library/bsz5788z.aspx). The answers in that article are not ideal, but they will get you moving along. The better approaches can get pretty complicated. Read-up on those once you get your app working again.
You can attach the Debugger in VS to IIS on your box and continue debugging. To do this, go to Debug->Attach to Process and then find the W3wp.exe process that is running the Application Pool your application is running in.
try
{
using (SqlConnection connection = new SqlConnection("Your connection string here"))
{
using (SqlCommand command = new SqlCommand("your sql here", connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
}
}
}
}
catch (Exception exception)
{
System.Diagnostics.Debug.WriteLine(exception);
}
Breakpoint in the catch to see the exception in your debugger.

Categories

Resources