I have this code:
string TmpMakat, TmpIsShakil, TmpDes;
SqlCeDataReader read;
public bool LOOK()
{
try
{
TmpMakat = "";
TmpIsShakil = "";
TmpDes = "";
Cmd.CommandType = CommandType.TableDirect;
Cmd.CommandText = "Items";
Cmd.IndexName = "A";
Cmd.SetRange(DbRangeOptions.Match, new object[] { txtMakat.Text }, null);
try
{
read = Cmd.ExecuteReader(); // <--- This is the Error
}
catch
{
MessageBox.Show("Error");
return false;
}
while (read.Read())
{
TmpMakat = read[0].ToString();
TmpIsShakil = read[1].ToString();
TmpDes = read[2].ToString();
}
read.Dispose();
if (TmpMakat == "")
{
TmpMakat = "";
TmpIsShakil = "";
TmpDes = "";
lblDes.Text = "";
lblQty.Text = "";
return false;
}
else
{
IsShakil = (TmpIsShakil == "1") ? true : false;
lblQty.Text = (IsShakil == true) ? "B" : "A";
lblDes.Text = TmpDes;
return true;
}
}
catch
{
return false;
}
}
but if there is any error - it never goes into the catch
I get this error sometime:
Error
A native exception has occurred in
myProg.exe.
Select Quit and then restart this program, or select Details
for more information.
and when I press for more Details I see this:
Error
ExceptionCode: 0xc0000005
EceptionAddress: 0x41efaf7c
Reading: 0x00000000
Faulting module: sqlcese35.dll
Offset: 0x0005af7c
ExceptionCode: 0xc0000005
That's a nasty one, AccessViolationException in .NET speak. Clearly SQL Compact is crashing, it is probably doing so in a worker thread or your catch clause would have caught it. Diagnosing this is going to be difficult but start by mistrusting the database file content, it might be corrupted. Consider an out-of-memory problem, it is bombing on a null pointer dereference. Look for updates from Microsoft.
The error happens in native code (SQL CE), so
either the .NET compact framework is unable to catch this kind of error (don't know, would be strange, but hard to ignore)
or the error happens in the first line, which is outside the try/catch block.
As you are calling a CreateCommand method, which we can assume, calls down to SQL CE, the 2nd possibility is more likely.
Can you put the assignment in the try/catch block ?
I had exactly the same error and was pulling my hair out with frustration, not getting anywhere. I references the SQL CE dlls directly and copied them all to the device during deploy, so after I read the above solution I tried to remove all the files and redeploy from scratch. That also did not work. In the end I installed SQL Server CE 3.5 SP2 directly on to the device with the CAB file found in
C:\Program Files (x86)\Microsoft SQL Server Compact Edition\v3.5\Devices\wce500\armv4i\sqlce.wce5.armv4i.cab
(ARMv4 in my case, your's may vary). After installing this to the device everything ran fine.
Related
EDIT: It only took a week but I eventually found out the issue, primarily due to pure luck and another error with a more specific fix.
The issue was with the connStr I had made, which for some reason on this machine gave me the error randomly of "System.ArgumentException: Keyword not supported: 'datasource'." during runtime. I then found out a fix for that was to rename the connStr as follows:
connStr = #"server = (server name); Initial Catalog = AutoTestDB; Integrated Security = true";
Should you have this error as I have, try that method of connection. END EDIT
I'm currently working on Automated Testing using Katalon Automated Testing, essentially Selenium for Chrome, and whenever I'm attempting to add the results of the test to our Test Results Database the SQL Exception "A network-related or instance-specific error occurred while establishing a connection to SQL Server. " keeps popping up. TCP/IP is open, as is firewall and remote connections, and I have the SQL-SMS open and running while I run the database with the SQL connection.
However it only happens whenever I'm using a certain machine to access the database which is stored within the machine itself, as it is with every other machine that I use and they all work perfectly fine. The only difference I can think of for this machine is that it uses SQL Express while all the others that I use have the full version of Microsoft SQL-SMS-17.
It's a genuine case of "It works on my machine", except with the caveat that it works on several others and even across different users as we are all working on this automated testing, this machine is the lone exception for this code not working, with the only difference being that it uses SQL Express which should be accounted for with the \\SQLExpress.
C# code with SQL connetions to edit the values into an already made table within the database.
public void testDBAdd(String testName, Boolean pass, String testComment)
{
SqlConnection con;
SqlDataAdapter daAutoTest;
DataSet dsAutoTestDB = new DataSet();
SqlCommandBuilder cmdBAutoTest;
String connStr, sqlAutoTest;
connStr = #"datasource = .\\sqlexpress; Initial Catalog = AutoTestDB; Integrated Security = true";
con = new SqlConnection(connStr);
sqlAutoTest = #"SELECT * FROM TestResults";
daAutoTest = new SqlDataAdapter(sqlAutoTest, connStr);
cmdBAutoTest = new SqlCommandBuilder(daAutoTest);
daAutoTest.FillSchema(dsAutoTestDB, SchemaType.Source, "AutoTest");
daAutoTest.Fill(dsAutoTestDB, "AutoTest");
foreach (DataRow drAutoTest in dsAutoTestDB.Tables["AutoTest"].Rows)
{
if (pass == true && drAutoTest["testName"].ToString() == testName)
{
drAutoTest.BeginEdit();
drAutoTest["testName"] = testName;
drAutoTest["testResult"] = 1;
drAutoTest["testComment"] = testComment;
drAutoTest.EndEdit();
daAutoTest.Update(dsAutoTestDB, "AutoTest");
}
else if (pass == false && drAutoTest["testName"].ToString() == testName)
{
drAutoTest.BeginEdit();
drAutoTest["testName"] = testName;
drAutoTest["testResult"] = 0;
drAutoTest["testComment"] = "Exception: " + testComment;
drAutoTest.EndEdit();
daAutoTest.Update(dsAutoTestDB, "AutoTest");
}
}
}
Code which runs the actual test and gathers if it has passed or failed due to the presence of certain elements, in this case is a certain page displayed when the user logs in and clicks a button.
public void settingTest<TestNumber>()
{
IWebDriver driver = new ChromeDriver();
ChromeOptions options = new ChromeOptions();
options.AddArguments("--start-maximized");
driver = new ChromeDriver(options);
String testName = "<Test Number>", testComment = "";
Boolean pass = false;
try
{
settingsLogin(driver);
settingsClick(driver);
Assert.IsTrue(driver.FindElement(ElementLocator).Displayed);
if (driver.FindElement(ElementLocator).Displayed == true)
{
testComment = "Pass";
pass = true;
testDBAdd(testName, pass, testComment);
}
}
catch (Exception ex)
{
testComment = "" + ex.TargetSite + "" + ex.Message;
testDBAdd(testName, pass, testComment);
}
finally
{
driver.Close();
}
}
Not sure, but I think your connection string has an extraneous backslash. You've prefaced the string with a "#" but then used "\\" in the Data Source. You might also try "(localdb)\SQLExpress" as the data source.
It only took a week but I eventually found out the issue, primarily due to pure luck and another error with a more specific fix. The issue was with the connStr I had made, which for some reason on this machine gave me the error randomly of "System.ArgumentException: Keyword not supported: 'datasource'." during runtime. I then found out a fix for that was to rename the connStr as follows:
connStr = #"server = (server name); Initial Catalog = AutoTestDB; Integrated Security = true";
Should you have this error as I have, try that method of connection. And thanks to the users who tried to help in both the comments of the post and in the answers section of this post.
The following function is used for the newer version of my app which needs to add a column to the existing database.
public void AddColumnIfNotexist()
{
try
{
using (SQLiteCommand cmd = _DBConnection.CreateCommand())
{
cmd.CommandText = string.Format("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'myTable'");
bool hascol = false;
using (SQLiteDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
//does column exists?
hascol = reader.GetString(0).Contains(String.Format("\"{0}\"", "myNewColumn"));
reader.Close();
}
}
if (!hascol)
{
StringBuilder sql = new StringBuilder(SQLMAXLENGTH);
sql.Append("ALTER TABLE Groups ADD COLUMN IsStayingRatio BIT NOT NULL DEFAULT 0");
cmd.CommandText = sql.ToString();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message + "\r\n\r\n" + ex.StackTrace);
LogApp.Write("Exception ex:" + ex.Message +"stacktrace "+ex.StackTrace, LogApp.Level.Error);
}
}
}
When I execute this gets an exception as
database is locked
Stacktrace
at System.Data.SQLite.SQLite3.Step(SQLiteStatement stmt)
at System.Data.SQLite.SQLiteDataReader.NextResult()
at System.Data.SQLite.SQLiteDataReader..ctor(SQLiteCommand cmd, CommandBehavior behave)
at System.Data.SQLite.SQLiteCommand.ExecuteReader(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery(CommandBehavior behavior)
at System.Data.SQLite.SQLiteCommand.ExecuteNonQuery()
at DataPlus.DB.AddColumnIfNotexist() in D:\Projects\DB.cs:line 343
But this is not always happened. this happens if the size of the DB Fil is large. Also, the issue is not there while debugging from the IDE.
Is there any limitations for the Alter Table query?
Can anyone spot out the issue which makes the DB locked?
I would suggest to start a new SQLiteCommand
Note that an SQLITE_LOCKED error is distinct from SQLITE_BUSY (5).
SQLITE_BUSY means that another database connection (probably in
another process) is using the database in a way that prevents you from
using it. SQLITE_LOCKED means the source of contention is internal and
comes from the same database connection that received the
SQLITE_LOCKED error.
Sometimes people think they have finished with a SELECT statement because sqlite3_step() has returned SQLITE_DONE. But the SELECT is not really complete until sqlite3_reset() or sqlite3_finalize() have been called
Error Code SQLITE_LOCKED (6): Database Is Locked
Adding the following lines after reader.Close() worked for me.
GC.Collect();
GC.WaitForPendingFinalizers();
It seems that the DB was not released on executing the ALTER query.
Got the hint from here.
I have developed a desktop application in C# with Microsoft SQL Server Compact Edition 3.5.
It works fine when I run .exe file from solution folder (bin\release or debug) but when I tried to deploy it by creating its setup it shows unhandled exception:
You don't have permission to access CustomersDB.sdf file.
Note there is no path error it is correct.
string lokasifile = Environment.CurrentDirectory + "\\CustomersDB.sdf";
string stringkoneksi = "Data Source = \"" + lokasifile + "\"";
SqlCeConnection koneksi = new SqlCeConnection(stringkoneksi);
koneksi.Open();
SecurityException
This is nothing but caller does not have the appropriate permission.
Environment.CurrentDirectory Property
try
{
//Call Path here you will get to what the exactly error is
}
catch (Exception ex)
{
if (ex is DirectoryNotFoundException|| ex is IOException|| ex is SecurityException)
{
//Your handling here
}
else
{
throw;
}
}
We have two servers. An application server and a SQL server.
When running this simple program from the application server:
static void Main(string[] args)
{
OleDbCommand cmd;
OleDbConnection cnn;
string connectionString = "Provider=SQLNCLI10;Integrated Security=SSPI;User ID=***;Password=***;Persist Security Info=False;Initial Catalog=MCS_BATCH;Data Source=CD6S01;Initial File Name=;";
string sql = "EXEC [msp].[MasterMSP] #BTYPE = N'B_PVM_KNN', #AC_KEY = NULL, #RUN_TS = '2014-05-02 17:29:31.1400555', #CHUNK_ID = 8794";
System.IO.StreamWriter file = new System.IO.StreamWriter("MasterMSP_output.txt");
cnn = new OleDbConnection(connectionString);
try
{
cnn.Open();
cmd = new OleDbCommand(sql, cnn);
try
{
OleDbDataReader reader = cmd.ExecuteReader();
int numberOfFields = reader.VisibleFieldCount;
StringBuilder sb = new StringBuilder();
while (reader.Read())
{
for (int i = 0; i < (numberOfFields - 1); i++)
{
file.Write(reader[i].ToString());
}
file.WriteLine("");
}
file.Close();
}
catch (Exception ex)
{
file.Write("Execption ex at : {0}", System.DateTime.Now);
file.Write(ex.Message.ToString());
Console.WriteLine("Exception ex time is : {0}", System.DateTime.Now);
throw;
}
cmd.Dispose();
cnn.Close();
}
catch (Exception exx)
{
file.Write("Execption exx at : {0}", System.DateTime.Now);
file.Write(exx.Message.ToString());
Console.WriteLine("Exception exx time is : {0}", System.DateTime.Now);
throw;
}
}
We get - after some time - a "Protocol error in TDS stream" error:
We ran a network trace, and we can see that the "TCP Window size" is decreasing after 10 mins and then it's sending a TCP Window size = 0 (close window).
This means that the SQL server can't send more data until it has gotten a update window size, bigger than 0, from the application server.(right?):
The SQL server is trying to send 1 byte keepalive, but the application server is never responding. (The problem is that the application server never raise TCP Windows Size again. At the end the application server is terminating the session.)
We except that it's the application server fault and it could be that the networks buffer is not being empty(flushed) anymore. The only thing the TCP stack can do is to close the TCP Windows Size until the application again empties the buffer - but it never does that.
Any hints, ideas on what the issue can be?
The problem actually came up in 3rd party program. This program is calling a stored procedure on the SQL server. So I just tried to reproduce the logic in a C# program and was able to reproduce the error.
Any help, ideas or comments are highly appreciated.
Thanks
Adding this to the connectionstring fixed the error: MARS Connection=True
Link
I have a problem with a customer. I have this code:
var conn = new SqlConnection(Util.GetConnectionString());
var DataCommand = new SqlCommand();
var sql = "";
// subseccion
try
{
sql = "TRUNCATE TABLE preview_" + tablename;
DataCommand = new SqlCommand(sql, conn);
DataCommand.Connection.Open();
int numcol = DataCommand.ExecuteNonQuery();
sql = "insert into preview_" + tablename+ " select * from " + tablename;
DataCommand = new SqlCommand(sql, conn);
DataCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
var latest_error = ex.Message;
Util.Add_Event_Log(latest_error);
}
finally
{
DataCommand.Dispose();
if (conn.State == ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
This do the next thing, I give a name of a table, it TRUNCATE a table then copy the information from "table" to "preview_table" and it works as expected.
However, we found that if we don't give TRUNCATE permission for the table, it fail. But, my problem is that it does not only fail but also deleting the current session (and may be also restart the server process).
My bet it is a server problem (server 2003) may be it is not patched or anything because I am working inside a try-catch part so it should not fail in this fashion.
My customers says the problem is in the code.
But I am not sure, maybe I should not a sql command in a chain.
Is this happening in the development environment as well as production environment? If so, you need to step through your code with the VS debugger and pin point the line at which the session is being deleted.
You should also check the event logs on the production server to see if they can provide any information.
As stated in the comments by msergey, it may be the Util.Add_Event_Log throwing an exception but you should test this by stepping through the code.
If it is Util.Add_Event_Log causing the issue, move this code out of the catch into its own try/catch statement by declaring an exception variable in the outer scope.
If it does wind up that the use of TRUNCATE is the culprit you might try swapping that out in favor of using a DELETE statement instead. Performance won't be as great, but you wouldn't require elevated user permissions in SQL Server either.