Exception is not Passed from API to Application - c#

I'm using a Web API MVC code, I get an exception in the database layer, but when it passed to the application layer, it's returning without any exception.
I am unable to handle the exception from web API
Database Layer
public int DBPostGeneralConfig(GeneralConfigtDets Getgencon)
{
int result = 0;
SqlConnection sqlConnection = null;
try
{
string user = !string.IsNullOrEmpty(System.Environment.UserName) ? System.Environment.UserName : string.Empty;
string sqlConnectString = MyConnectionString;
sqlConnection = new SqlConnection(sqlConnectString);
SqlCommand sqlCommand = new SqlCommand("InsertUpdateDeleGeneralConfig", sqlConnection);
sqlCommand.CommandTimeout = MySQLCommandTimeOut;
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.AddWithValue("#Action", "INSERT");
sqlCommand.Parameters.AddWithValue("#ID", System.Guid.NewGuid().ToString());
sqlCommand.Parameters.AddWithValue("#Name", Getgencon.Name);
sqlCommand.Parameters.AddWithValue("#Value", Getgencon.Value);
sqlCommand.Parameters.AddWithValue("#updatedBy", user);
sqlCommand.Parameters.AddWithValue("#updatedOn", DateTime.Now);
sqlConnection.Open();
result = sqlCommand.ExecuteNonQuery();
}
catch (Exception ex)
{
DBCall.LogError(ex, "DBPostGeneralConfig");
result = -1;
}
finally
{
if (sqlConnection.State != ConnectionState.Closed)
{
sqlConnection.Close();
}
}
return result;
}
Application Layer
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult AddNewGeneralConfig(GeneralConfigDets Configval)
{
if (ModelState.IsValid)
{
try
{
ServiceRepositary serviceObj = new ServiceRepositary();
HttpResponseMessage response = serviceObj.PostResponse("api/GeneralConfiguration/AddNewGeneralConfig", Configval);
response.EnsureSuccessStatusCode();
}
catch (Exception)
{
ModelState.AddModelError(string.Empty, "Server error. Please contact administrator.");
}
TempData["Message"] = "Added Successfully";
}
return RedirectToAction("GetGeneralConfig", "GeneralConfig");
}

Related

C# - Microsoft sql database | Can't add new user on my e-contact app

I tried to make an e-contact app with C# on Visual Studio 2019 connected to a Miscrosoft SQL database (local) following a youtube tutorial.
The app is not complete yet, anyway the btnAdd should work, but it doesn't add the user and the return of the method (Insert).
It always returns false - Can anyone help me?
private void BntAdd_Click(object sender, EventArgs e) {
//Get the value from the imput fields
c.Nome = txtBoxName.Text;
c.Cognome = txtBoxSurname.Text;
c.Telefono1= txtBoxPhone1.Text;
c.Telefono = txtBoxPhone.Text;
c.Email = txtBoxEmail.Text;
//Inserting Data into Database uing the method we created is previous episode
bool success = c.Insert(c);
if (success == true)
{
//Successfully Inserted
MessageBox.Show("New contact added!");
//Call the clear Method Here
Clear();
}
else
{
//Failed to add Contact
MessageBox.Show("ERROR!)");
}
//load Data on Data GRidview
DataTable dt = c.Select();
dgvRubrica.DataSource = dt;
}
public void Clear()
{
txtBoxName.Text = "";
txtBoxSurname.Text = "";
txtBoxPhone1.Text = "";
txtBoxPhone.Text = "";
txtBoxEmail.Text = "";
}
public bool Insert (rubricaClass c) {
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
try
{
string sql = "INSERT INTO tbl_Rubrica (Nome, Cognome, Telefono1, Telefono, Email) VALUES (#Nome, #Cognome, #Telefono1, #Telefono, #Email)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("#Nome", c.Nome);
cmd.Parameters.AddWithValue("#Cognome", c.Cognome);
cmd.Parameters.AddWithValue("#Telefono1", c.Telefono1);
cmd.Parameters.AddWithValue("#Telefono", c.Telefono);
cmd.Parameters.AddWithValue("#Email", c.Email);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
return isSuccess;
}
It doesn't give any errors, it work but when i type the ata into txtBoxes and then i press the add button it says Error (message box inserte in the else)
Step 1 is to remove the catch-all exception handling from the Insert method. Most of the ADO.NET database classes implement IDisposable, so you just need a using(...) block to make sure the command is disposed automatically (which will also close and dispose the connection instance):
public bool Insert (rubricaClass c)
{
bool isSuccess = false;
SqlConnection conn = new SqlConnection(myconnstrng);
string sql = "INSERT INTO tbl_Rubrica (Nome, Cognome, Telefono1, Telefono, Email) VALUES (#Nome, #Cognome, #Telefono1, #Telefono, #Email)";
using(SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#Nome", c.Nome);
cmd.Parameters.AddWithValue("#Cognome", c.Cognome);
cmd.Parameters.AddWithValue("#Telefono1", c.Telefono1);
cmd.Parameters.AddWithValue("#Telefono", c.Telefono);
cmd.Parameters.AddWithValue("#Email", c.Email);
conn.Open();
int rows = cmd.ExecuteNonQuery();
if (rows > 0)
{
isSuccess = true;
}
else
{
isSuccess = false;
}
}
return isSuccess;
}
Once that's squared away, Step 2 is to move your exception handling into the application. I don't recommend this "catch everything"-style code, but it works for now, I suppose:
private void BntAdd_Click(object sender, EventArgs e)
{
//Get the value from the imput fields
c.Nome = txtBoxName.Text;
c.Cognome = txtBoxSurname.Text;
c.Telefono1= txtBoxPhone1.Text;
c.Telefono = txtBoxPhone.Text;
c.Email = txtBoxEmail.Text;
try
{
//Inserting Data into Database uing the method we created is previous episode
bool success = c.Insert(c);
if (success == true)
{
//Successfully Inserted
MessageBox.Show("New contact added!");
//Call the clear Method Here
Clear();
}
else
{
//Failed to add Contact
MessageBox.Show("ERROR!)");
}
//load Data on Data GRidview
DataTable dt = c.Select();
dgvRubrica.DataSource = dt;
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This will likely tell you that you either have an error in your SQL syntax, or that the command itself could not be run (i.e. the connection string is invalid or the server can't be reached).

SQLException : Login Failed for user "xx" when using SQLHelper ExecuteNonQuery

I have a problem when using the SQLHelper class to execute an update stored procedure. I am using SqlTransaction as parameters in SQLHelper.ExecuteNonQuery.
This is my code :
// Create SQLTransaction
public bool Delete()
{
SqlConnection oConn = tsoDAL.OpenConnection();
SqlTransaction oTrans = oConn.BeginTransaction();
try
{
if (Delete(oTrans))
{
oTrans.Commit();
return true;
}
else
{
oTrans.Rollback();
return false;
}
}
catch (SqlException ex)
{
oTrans.Rollback();
throw (ex);
}
finally
{
tsoDAL.CloseConnection(ref oConn);
}
}
// Call SQLHelper
public bool Delete(SqlTransaction p_oTrans)
{
try
{
SqlParameter[] oParams = new SqlParameter[1];
oParams[0] = new SqlParameter("#p_iSalesSoId", m_iSalesSoId);
int iRowAffected = SqlHelper.ExecuteNonQuery(p_oTrans, "uspTSO_DeleteSalesOrder",oParams);
return iRowAffected >= 0;
}
catch (Exception ex)
{
throw ex;
}
}
The code throws an error when it reaches this code in SQLHelper.cs:
private static SqlParameter[] DiscoverSpParameterSet(string connectionString, string spName, bool includeReturnValueParameter)
{
using (SqlConnection cn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(spName,cn))
{
cn.Open(); // error happens here
cmd.CommandType = CommandType.StoredProcedure;
SqlCommandBuilder.DeriveParameters(cmd);
if (!includeReturnValueParameter)
{
cmd.Parameters.RemoveAt(0);
}
SqlParameter[] discoveredParameters = new SqlParameter[cmd.Parameters.Count];;
cmd.Parameters.CopyTo(discoveredParameters, 0);
return discoveredParameters;
}
}
Error that's shown is
Login Failed for User 'sa'.
I was searching for the solution for this problem, and I still didn't get the solution that can fix my problem.
I need your help, thank you
I have trace the problems and the really problem is SQLTransaction Connectionstring lost it password. So in my connectionstring i added
Persist Security Info=true; and thats solve my problem. Thank you

Using sessions in c#

This is my code using sessions in C# for login. I have business logic and data access layer written for this, but my code is not working as expected. Even if there is no record in DB, i am able to login and it redirects to error.aspx
Default.aspx.cs
public void LoginButton_Click(object sender, System.EventArgs e)
{
int id;
if (LoginName.Text!=""&& Password.Text!="")
{
try
{
sessionVars = BL_Authenticate.AuthenticateUser(sessionVars, LoginName.Text, Password.Text);
Response.Redirect("home.aspx");
}
catch (Exception ex)
{
Session["Exception"] = ex.Message.ToString();
Response.Redirect("error.aspx");
}
//else
//{
// Response.Redirect("error.aspx");
//}
if (sessionVars.Tables[0].Rows.Count >= 1)
{
try
{
Session["User"] = (string)sessionVars.Tables[0].Rows[0]["FirstName"];
Session["User"] += (string)" ";
Session["User"] += (string)sessionVars.Tables[0].Rows[0]["LastName"];
}
catch (Exception ex)
{
Session["Exception"] = ex.Message.ToString();
Response.Redirect("error.aspx");
}
id = (int)sessionVars.Tables[0].Rows[0][0];
if (id >= 1)
{
try
{
Session["Role"] = "Admin";
FormsAuthentication.Authenticate((string)sessionVars.Tables[0].Rows[0]["Login"], (string)sessionVars.Tables[0].Rows[0]["Password"]);
}
catch (Exception ex)
{
Session["Exception"] = ex.Message.ToString();
Response.Redirect("error.aspx");
}
if (FormsAuthentication.GetRedirectUrl("Admin", false) == "/UserInterface/home.aspx")
{
FormsAuthentication.RedirectFromLoginPage("admin", false);
Response.Redirect("home.aspx");
}
else
FormsAuthentication.RedirectFromLoginPage("admin", false);
}
else
{
Session["Role"] = "User";
FormsAuthentication.RedirectFromLoginPage("user", false);
}
}
else
{
errorMessage.Text = "Sorry, wrong username or password.";
}
}
}
}
BL_Authenticate
public class BL_Authenticate
{
public static DataSet AuthenticateUser(DataSet user, string login, string password)
{
return DAL_Authenticate.AuthenticateUser(user, login, password);
}
}
DAL_Authenticate
public static DataSet AuthenticateUser(DataSet dataset, string login, string password)
{
try
{
//Dispose all objects that have a .Dispose()
SqlDataAdapter adapter = new SqlDataAdapter();
conn = DAL_DataBaseConnection.GetConnection();
SqlCommand cmd = new SqlCommand("authentication", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter param = cmd.Parameters.Add("#Login", SqlDbType.VarChar, 255);
param.Value = login;
param = cmd.Parameters.Add("#Password", SqlDbType.VarChar, 255);
param.Value = password;
adapter.SelectCommand = cmd;
adapter.Fill(dataset);
}
finally
{
conn.Close();
}
return dataset;
}
One normal thing I see is that if the login fails, it redirect to an error page, so there is no mistake there, are you sure your login as work at that point ?

Object reference not set to an instance of an object while using stored procedures

This is a .cs page and I have two function to be executed, But the error is both the function are not being executed ,if I comment on one function the other will work, both are not executed,it giving a common error object reference not set to an instance of an object
Below specified is a .cs page.
Business bus = new Business();
try
{
intResult = bus.create_user(ua);
}
catch (Exception ex)
{
}
finally
{
bus = null;
}
int intres = 0;
try
{
intres = bus.fninsertuser_role_map(ua, role, i);
}
catch (Exception ee)
{
}
finally
{
bus = null;
}
Data access object
public int create_user(UserMaster ua)
{
// Connection connect = new Connection();
try
{
return cs.create_user(ua);
}
catch (Exception e)
{
throw e;
}
finally
{
cs = null;
}
}
public int fninsertuser_role_map(UserMaster ua, int[] role, int i)
{
// Connection connect = new Connection();
try
{
return cs.fninsertuser_role_map(ua, role, i);
}
catch (Exception e)
{
throw e;//**Throws the exception here.**
}
finally
{
//cs = null;
}
Business value object
public int create_user(UserMaster ua)
{
SqlConnection Con = new SqlConnection(str);
Con.Open();
SqlCommand Cmd = new SqlCommand("createuser", Con);
Cmd.CommandType = CommandType.StoredProcedure;
try
{
log.Debug("Inside Create user");
Cmd.Parameters.AddWithValue("#User_Id", ua.UserName);
Cmd.Parameters.AddWithValue("#Password", ua.Password);
Cmd.Parameters.AddWithValue("#Name", ua.Name);
Cmd.Parameters.AddWithValue("#Role_Id", ua.Role);
Cmd.Parameters.AddWithValue("#Department_Id", ua.Department);
Cmd.Parameters.AddWithValue("#Active", ua.Active);
log.Debug("Inside Create_User: New User created having ID: " + ua.UserName);
log.Info("user created");
return Cmd.ExecuteNonQuery();
}
catch (Exception e)
{
log.Debug("Error: Inside catch block of Create User");
log.Error("Error msg:" + e);
log.Error("Stack trace:" + e.StackTrace);
throw e;
}
finally
{
Cmd.Dispose();
Con.Close();
Con.Dispose();
}
}
/*Function to insert into user_role_map*/
public int fninsertuser_role_map(UserMaster u, int[] role, int i)
{
SqlConnection Con = new SqlConnection(str);
Con.Open();
transaction = Con.BeginTransaction();
int result = 0;
for (int a = 0; a < i; a++)
{
SqlCommand Cmd = new SqlCommand("create_UR_Map", Con, transaction);
Cmd.CommandType = CommandType.StoredProcedure;
Cmd.Parameters.Clear();
Cmd.Parameters.AddWithValue("#User_Id", u.UserName);
Cmd.Parameters.AddWithValue("#Role_Id", role[a]);
result = Cmd.ExecuteNonQuery();
}
transaction.Commit();
return result;
}
I just need to execute both the function in the same page.Any help are appreciated.
Problem : you are trying to put null into instance variable bus and then calling methods using the same variable as below:
try
{
intResult = bus.create_user(ua);
}
catch (Exception ex)
{
}
finally
{
bus = null;//bus becomes null here for sure even if there is no excption thrown
}
int intres = 0;
try
{
intres = bus.fninsertuser_role_map(ua, role, i);//throws exception here
}
that is why it throws object reference not set to an instance of an object.
Note : You should remember that finally block willbe executed irrespective of the situation means it will be executed in all the cases and your instance variable bus becomes null for sure even if there is no exception thrown.
Solution : i think you need to really refactor your code but your intension is to making instance variable bus to null if it throws exception if that is the case move that statement inside the catch block.
Try This:
try
{
intResult = bus.create_user(ua);
}
catch (Exception ex)
{
bus = null;
}
finally
{
//any code which needs to be executed for sure
}
int intres = 0;
try
{
intres = bus.fninsertuser_role_map(ua, role, i);
}
catch (Exception ee)
{
bus = null;
}
finally
{
//any code which needs to be executed for sure
}

How to select a value with results from another column

i am using C# and i need to develop a check system for a mysql user and password.
So far what ive come up with is this and the error i get is that it is the wrong syntax...
public bool VerifyUser(string username, string password)
{
string returnValue = "";
string Query = "SELECT Pass FROM Base_Character WHERE User='" + username + "'";
MySqlCommand verifyUser = new MySqlCommand(Query, this.sqlConn);
try
{
verifyUser.ExecuteNonQuery();
MySqlDataReader myReader = verifyUser.ExecuteReader();
while (myReader.Read() != false)
{
returnValue = myReader.GetString(0);
}
myReader.Close();
}
catch (Exception excp)
{
Exception myExcp = new Exception("Could not verify user. Error: " +
excp.Message, excp);
throw (myExcp);
}
if (returnValue == password)
{
return false;
}
else
{
return true;
}
}
ExecuteNonQuery is for DELETE, INSERT and UPDATE. Whenever you want data returned as rows from database, use ExecuteReader
Your query should check the username and password together, if they exist in one record then the row is returned else nothing is returned.
You still need more to learn about coding/database programming using .Net
public bool VerifyUser(string username, string password)
{
bool returnValue = false;
string Query = "SELECT 1 FROM Base_Character WHERE User='" + username + "' AND pass='"+password+"'";
try
{
MySqlCommand command = new MySqlCommand(Query, this.sqlConn);
MySqlDataReader myReader = command.ExecuteReader();
if(myReader.Read())
{
returnValue = true;
}
myReader.Close();
}
catch (Exception excp)
{
throw;
}
return returnValue;
}
You should probably not throw a custom exception since you are using boolean
if(VerifyUser("user123", "******"))
{
//Congratulations
}
else
{
//Unable to log you in
}
Thanks guys, but this calls for a custom encryption that mysql cant hold or process, my main error was ovrlooking the executenonquery(), so i had to make the code like this:
if (AuthorizeTools.Encrypt.Password(Database.getPassword) != Password) //Password is already encrypted
Then set the mysql function to:
public string getPassword(string username)
{
string returnValue = "";
string Query = "SELECT Pass FROM Base_Character where (User=" +
"'" + username + "') LIMIT 1";
MySqlCommand checkUser = new MySqlCommand(Query, this.sqlConn);
try
{
checkUser.ExecuteNonQuery();
MySqlDataReader myReader = checkUser.ExecuteReader();
while (myReader.Read() != false)
{
returnValue = myReader.GetString(0);
}
myReader.Close();
}
catch (Exception excp)
{
Exception myExcp = new Exception("Could not grab password: " +
excp.Message, excp);
throw (myExcp);
}
return (returnValue);
}

Categories

Resources