Unable to Bubble user-defined Sql RAISERROR(...) to c# exception - sql-server-2008

Unable to Bubble user-defined Sql RAISERROR(...) to c# exception.
Evidence or clues: Sql generated errors bubble to c# but Sql user-defined errors do not bubble to c#. Both are logged in the sql server logs.
EXEC sp_addmessage
#msgnum = 50001,
#severity = 16,
#msgtext = N'This is a user defined error message test_2_sp',
#lang = 'us_english';
DECLARE #FirstNum int = 1
DECLARE #SecondNum int = 0
DECLARE #RowCount int
BEGIN TRY
--SELECT #FirstNum / #SecondNum -- This sql error (not user defined) always comes through by itself with out try ... catch
SELECT #FirstNum + #SecondNum as Result
WHERE #FirstNum = 0 --Un-comment me and watch the error come and go???
--SET #RowCount = ##ROWCOUNT
--SELECT #RowCount AS '#RowCount' -- to see ##ROWCOUNT in SSMS
--RAISERROR('OutSide', 16, 1) WITH Log;
IF ##ROWCOUNT = 0
RAISERROR (50001, -1,-1) WITH Log; --https://msdn.microsoft.com/en-us/library/ms178592.aspx
END TRY
BEGIN CATCH
declare #ErrorMessage nvarchar(max), #ErrorSeverity int, #ErrorState int;
select #ErrorMessage = ERROR_MESSAGE() + ' LineNo ' + cast(ERROR_LINE() as nvarchar(5)), #ErrorSeverity = ERROR_SEVERITY(), #ErrorState = ERROR_STATE();
raiserror (#ErrorMessage, #ErrorSeverity, #ErrorState) WITH Log;
END CATCH
EXEC sp_dropmessage 50001, 'all';
END
C#
protected void Page_Load(object sender, EventArgs e)
{
string ConnectionStringName = "SQLUTLtest";
//string con = #"Data...";
SqlConnection sqlcon = new SqlConnection(ConfigurationManager.ConnectionStrings[ConnectionStringName].ToString());
using (SqlCommand cmd = new SqlCommand("Test_2_Sp", sqlcon))
{
cmd.CommandType = CommandType.StoredProcedure;
sqlcon.Open();
try
{
SqlDataAdapter adp = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adp.Fill(dt);
Response.Write("Hello");
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
Response.Write("</br>finally");
}
}
}

Sharing the same response as I did on EE (https://www.experts-exchange.com/questions/28979394/Bubble-user-defined-Sql-RAISERROR-to-c-exception.html):
I think the code will be unable to catch SQL standard Exceptions as well. For example, if I add a SELECT 1/0 (critical divide by zero error) after performing the addition, the code will continue to populate the Data Table and not catch the exception.
Can you update your C# code to the following? Basically, rather than just filling up the DataTable, I am trying to get a DataSet first. This would fail if an exception has been generated. (I tried this on a WinForms App, hence the MessageBoxes. Request you to update the code as necessary).
using (SqlCommand mySqlCommand = new SqlCommand("Test_2_Sp", myCustomConnection))
{
mySqlCommand.CommandType = CommandType.StoredProcedure;
mySqlCommand.Parameters.AddWithValue("#firstnum", "1");
mySqlCommand.Parameters.AddWithValue("#secondnum", "0");
myCustomConnection.Open();
try
{
SqlDataAdapter adp = new SqlDataAdapter(mySqlCommand);
DataSet myDataSet = new DataSet();
adp.Fill(myDataSet);
if (myDataSet.Tables.Count > 0)
{
DataTable dt = myDataSet.Tables[0];
}
MessageBox.Show("Hello World!");
}
catch (Exception ex)
{
MessageBox.Show("Ouch!");
}
finally
{
MessageBox.Show("Good Bye!");
}
}

Related

Update stored procedure in mysql does not work with asp.net?

Here's my code :
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (pass1.Text != pass2.Text)
{
lblerror.Text = "Passwords do not match.";
}
else
{
DB db = new DB();
string pass = db.Encrypt(pass2.Text.Trim());
MySqlConnection sqlcon = new MySqlConnection(db.sqlstring());
MySqlCommand cmd = new MySqlCommand("changepassword", sqlcon);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.Add(#"pass", MySqlDbType.VarChar).Value = pass;
cmd.Parameters.Add(#"user1", MySqlDbType.Int16).Value = Convert.ToInt16(Session["userKey"]);
sqlcon.Open();
cmd.ExecuteNonQuery();
//Response.Redirect("regex.aspx", false);
//Context.ApplicationInstance.CompleteRequest();
}
catch (Exception ex)
{
lblerror.Text = ex.Message;
}
finally
{
sqlcon.Close();
Session.Abandon();
Session.RemoveAll();
}
}
}
and My stored procedure is like this.
delimiter $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `changepassword`(IN pass varchar(100),IN user1 varchar(100))
begin
update users set Password = 'pass' where UserID = user1;
end;
When I update using call in mysql workbench it works well.
But when I call from backend in asp.net
The value of password is changed 'pass' in table but not actual value which is passed as 'string = pass';
What is wrong in my code? I didn't find any exception in above code.

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding

This is my stored procedure for update teacher detail
ALTER procedure [dbo].[sp_update_teacher]
(#teacherid int,
#name varchar(50),
#gender int,
#email varchar(50),
#phone varchar(50),
#address varchar(50),
#timage image)
as
update teacher_info
set teacher_name = #name,
gender_id = #gender,
teacher_mail = #email,
phone = #phone,
teacher_address = #address,
image = #timage
where teacher_id = #teacherid
This is ado.net class code for update teacher detail
public void update_info(int teacher_id, string teacher_name, int teacher_gender, string email, string teacher_phone, string teacher_address, byte[] image)
{
SqlConnection con = new SqlConnection("server=ARMAAN;database=smsystem;integrated security=true;");
SqlCommand cmd = new SqlCommand("sp_update_teacher", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#teacherid", teacher_id);
cmd.Parameters.AddWithValue("#name", teacher_name);
cmd.Parameters.AddWithValue("#gender", teacher_gender);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#phone", teacher_phone);
cmd.Parameters.AddWithValue("#address", teacher_address);
cmd.Parameters.AddWithValue("#timage", image);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
This is update page code where i call the function that i i have made in class code
protected void update_Click1(object sender, EventArgs e)
{
try
{
FileUpload img = (FileUpload)FileUpload2;
Byte[] imgbyte = null;
HttpPostedFile file = FileUpload2.PostedFile;
imgbyte = new Byte[file.ContentLength];
file.InputStream.Read(imgbyte, 0, file.ContentLength);
tic.update_info(Convert.ToInt32(txt_id.Text), txt_name.Text, Convert.ToInt32(txt_genders.SelectedValue),txt_email.Text,txt_phone.Text, txt_address.Text, imgbyte);
Response.Write("<script language='javascript'>alert('Teacher detail Update successfully') </script>");
GridView1.DataSource = tic.getdata();
GridView1.DataBind();
}
catch (Exception ex)
{
Response.Write("<script language='javascript'>alert('some error') </script>");
}
}
and it give me this error please tell me what should I do?
Try increasing the command timeout of the command:
cmd.CommandTimeout = 120;
CommandTimeout

MySQL System.FormatException: Input string was not in a correct format

Currently, I am creating an application using ASP.NET MVC3 and MySQL and when I try to retrieve a user's first name from the databse I receive a System.FormatException: Input string was not in a correct format.
This is my code:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
object result = cmd.ExecuteScalar();
if (result != null)
{
string fname = Convert.ToString(result);
return fname;
}
else
{
string fname = "friend";
return fname;
}
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
This is MySQL Stored Procedure:
CREATE DEFINER=`0001`#`%` PROCEDURE `SP_GET_FNAME`(IN id BIGINT(20), OUT first_name VARCHAR(60))
BEGIN
DECLARE user_id BIGINT(20) DEFAULT id;
DECLARE output VARCHAR(60);
SELECT `FName` FROM `users` WHERE USERID=user_id INTO output;
SET first_name = output;
END
The problem seems to be when executing cmd.ExecuteScalar().
What is my problem here?
Thank you in advance!
Copy and paste error on my part. The correct code that works as expected is:
public string GetUserFirstName(UInt64 id)
{
DBConnections databaseCnnString = new DBConnections();
string connectionString = "server=123.123.com;user=me;database=db1;port=3306;password=abcdef";
MySqlConnection cnn = new MySqlConnection(connectionString);
try
{
cnn.Open();
string sp_GetFName = "SP_GET_FNAME";
MySqlCommand cmd = new MySqlCommand(sp_GetFName, cnn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("id", id);
cmd.Parameters["id"].Direction = ParameterDirection.Input;
cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
cmd.Parameters["first_name"].Direction = ParameterDirection.Output;
cmd.ExecuteScalar();
string fname = Convert.ToString((cmd.Parameters["first_name"].Value));
return fname;
}
catch (Exception ex)
{
throw (ex);
}
finally
{
cnn.Close();
cnn.Dispose();
}
}
CORRECTION: cmd.Parameters.Add(new MySqlParameter("first_name", MySqlDbType.VarChar));
NOT: cmd.Parameters.AddWithValue("first_name", MySqlDbType.VarChar);
In my case, the FNAME field in the user table cannot be NULL; therefore, checking for NULL values returned in the code is not necessary.
I would guess that the user is not found or the fname is null.
And I really hope you're not querying the database for each user column.
Good luck.
An additional comment.
When trying to return a string value the AddWithValue appears to be trying to convert the output from a string into a number. This results in the string format exception.

Input string was not in a correct format

Can anyone please advise where i have gone wrong with the following method / stored proceedure? I keep getting the following error...
**
> Input string was not in a correct
**
This is the Stored proceedure i using and the method.
-- --------------------------------------------------------------------------------
-- Routine DDL
-- --------------------------------------------------------------------------------
DELIMITER $$
CREATE DEFINER=`Admin`#`%` PROCEDURE `test`(
IN p_idExceptionLog INT(32) ,
IN p_ExceptionDate DATETIME ,
IN p_User VARCHAR(45) ,
IN p_ExceptionMessage VARCHAR(4000)
)
BEGIN
INSERT INTO ExceptionLog
(
id ,
Date ,
User ,
Message
)
VALUES
(
p_idExceptionLog ,
p_ExceptionDate ,
p_User ,
p_ExceptionMessage
) ;
END
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
MySqlConnection NasDB = null;
// MySqlCommand inputError1 = new MySqlCommand();
MySqlCommand inputError = null;
int rows = 0;
string spName = "test";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new MySqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new MySqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_idExceptionLog", MySql.Data.MySqlClient.MySqlDbType.Int32, (1)));
inputError.Parameters[0].Value = "";
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[1].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[2].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[3].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
}
Thanks
Err you are declaring paramter[0] (idExceptionLog) as an Int32 and then setting it to a string in your script? perhaps not setting it will help if it's supposed to be auto-generated or giving it a valid int value if you are manually generating it.
Worked the problem out.
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
MySqlConnection NasDB = null;
MySqlCommand inputError = null;
int rows = 0;
string spName = "ExceptionInsert";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new MySqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new MySqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_idExceptionLog", MySql.Data.MySqlClient.MySqlDbType.Int32, (0)));
inputError.Parameters[0].Value = null;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[1].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[2].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[3].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
}

The SqlParameterCollection only accepts non-null SqlParameter type objects, not MySqlParameter objects

I have created a method that will insert any exceptions thrown into a table on "ExceptionLog" on MySql server.
ExceptionLog Table format
idExceptionLog int (AI)
User (varchar 45)
ErrorMessage (varchart 4000)
The problem is i keep getting the following error. Does anyone know why?
The SqlParameterCollection only
accepts non-null SqlParameter type
objects, not MySqlParameter objects.
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
SqlConnection NasDB = null;
SqlCommand inputError = null;
int rows = 0;
string spName = "ExceptionInsert";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new SqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new SqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[0].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[1].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[2].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
All the classes inside System.Data.SqlClient are used for SQL Server database & not mysql.
In your code, replace SqlCommand with MySqlCommand and SqlConnection with MySqlConnection.
EDIT: See this page for the classes, you could use in this case.
I have made some slight changes and am now getting the following error.
**
Input string was not in a correct
**
This is the Stored proceedure i using and the method.
-- --------------------------------------------------------------------------------
-- Routine DDL
DELIMITER $$
CREATE DEFINER=Admin#% PROCEDURE test(
IN p_idExceptionLog INT(32) ,
IN p_ExceptionDate DATETIME ,
IN p_User VARCHAR(45) ,
IN p_ExceptionMessage VARCHAR(4000)
)
BEGIN
INSERT INTO ExceptionLog
(
id ,
Date ,
User ,
Message
)
VALUES
(
p_idExceptionLog ,
p_ExceptionDate ,
p_User ,
p_ExceptionMessage
) ;
END
private void showErrorBox(String errorMsg, MessageBoxButtons btnokshow)
{
MessageBox.Show(errorMsg, "FS Manager Error", MessageBoxButtons.OK);
// write to DB
string username = System.Environment.UserName.ToString();
string timestamp = DateTime.Now.ToString();
// Locals
MySqlConnection NasDB = null;
// MySqlCommand inputError1 = new MySqlCommand();
MySqlCommand inputError = null;
int rows = 0;
string spName = "test";
try
{
//Instantiate the DB connection setting the conn string
using (NasDB = new MySqlConnection(getConnectionString(ConnectionType.NAS)))
{
// Instantiate the command object that will fire the SP.
using (inputError = new MySqlCommand(spName, NasDB))
{
// Finish setting up the command object
inputError.CommandType = CommandType.StoredProcedure;
// Set up the SP params.
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_idExceptionLog", MySql.Data.MySqlClient.MySqlDbType.Int32, (1)));
inputError.Parameters[0].Value = "";
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionDate", MySql.Data.MySqlClient.MySqlDbType.DateTime, (1)));
inputError.Parameters[1].Value = timestamp;
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_User", MySql.Data.MySqlClient.MySqlDbType.VarChar, (45)));
inputError.Parameters[2].Value = System.Environment.UserName.ToString();
inputError.Parameters.Add(new MySql.Data.MySqlClient.MySqlParameter("p_ExceptionMessage", MySql.Data.MySqlClient.MySqlDbType.VarChar, (4000)));
inputError.Parameters[3].Value = errorMsg;
// Now that the SP is completely set up and ready to go open the conn and fire the SP.
inputError.Connection.Open();
rows = inputError.ExecuteNonQuery();
// Close ASAP
inputError.Connection.Close();
}
}
}
catch (Exception ex)
{
//showErrorBox(ex.ToString());
throw ex;
}
}