I have a loop where I call stored procedure with different parameter value.
Next call cmd.ExecuteNonQuery();
I use transaction to save all or rollback, and checkBox2 - save always.
I found one problem and I can't find solution.
After first problem when catch block is fired transaction object loses its connection.
t.connection
is null!
Everything is good but transaction object is without connection at start it has!
try
{
while (!sr.EndOfStream)
{
strLine.Remove(0, strLine.Length);
//c = sr.ReadLine();
while (c != "-")
{
c = sr.ReadLine();
strLine.Append(c );
if (sr.EndOfStream) break;
}
//strLine.Append("Nowa pozycja");
try
{
cmd.Parameters["@s"].Value = strLine.ToString();
cmd.Parameters["@Return_value"].Value = null;
cmd.ExecuteNonQuery();
}
catch
{
if (cmd.Parameters["@Return_value"].Value == null)
{
cmd.Parameters["@Return_value"].Value = -100;
}
if (((int)cmd.Parameters["@Return_value"].Value == 100) || (checkBox2.Checked))
{
if ((int)cmd.Parameters["@Return_value"].Value != 100)
{
MessageBox.Show("Są błedy! " + cmd.Parameters["@s"].Value);
};
}
}
if (!checkBox2.Checked)
{
if ((Int32)cmd.Parameters["@Return_value"].Value != 100)
{
break;
}
}
c = "";
}
textBox1.Text = strLine.ToString();
}
catch
{
// t.Rollback();
// t = null;
textBox1.Text = strLine.ToString();
textBox1.Visible = true;
MessageBox.Show("Wystąpiły problemy w czasie importu " + cmd.Parameters["@s"].Value);
//return;
}
finally
{
if (cmd.Parameters["@Return_value"].Value == null)
{
cmd.Parameters["@Return_value"].Value = -100;
}
if (((int)cmd.Parameters["@Return_value"].Value==100)||(checkBox2.Checked))
{
t.Commit();
if ((int)cmd.Parameters["@Return_value"].Value!=100)
{
MessageBox.Show("Transakcja zapisana ale w pliku były błedy! " + cmd.Parameters["@s"].Value);
};
}
else
{
if (t!=null) {t.Rollback();}
MessageBox.Show("Transakcja odrzucona!");
}
conn2.Close();
aFile.Close();
}
I also met this odd problem (converting nvarchar to integer exception).
In my solution, I rebuild the transacton if found the underlying connection is null. But it's a dirty work.
Ran into a similar issue. In my case it was happening for a specific SqlException. Most exceptions would be caught and handled just fine, but whenever I got a conversion error (such as trying to convert a string to a number) it would automatically end the transaction.
To fix this, I had to implement data checking (good idea anyway) prior to building/submitting the command object. Hope this helps others seeing this weird error.