command failing in login code in C# on ASP.NET - asp.net

I am making a website using ASP.NET framework.
My code for login page is as below, it is very simple since I'm trying to see step by step where it is going wrong. The C# code is:
protected void userLogin(object sender, EventArgs e)
{
string encoded_pass = encrypt_pass(Password.Text);
SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Khulna_website"].ConnectionString);
connection.Open();
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password"))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
try
{
cmd.ExecuteNonQuery();
//SqlDataAdapter da = new SqlDataAdapter(cmd);
//DataTable dt = new DataTable();
//da.Fill(dt);
////Session["User"] = dt.Rows[0]["user_email"];
//Session["User_name"] = dt.Rows[0]["user_f_name"];
//loginlabel.Text = "Welcome, " + Session["User_name"];
}
catch
{
loginlabel.Text = "login error";
}
}
connection.Close();
}
Now every time I enter an email and password it always gives "login errorr".. Why the command is not executed?

Looks like you have declared the connection but haven't assigned it to the SqlCommand
using (SqlCommand cmd = new SqlCommand ("Select * from users where user_email= #email and user_password = #password",connection))
{
cmd.Parameters.AddWithValue("#email", Email.Text);
cmd.Parameters.AddWithValue("#password", encoded_pass);
Note i added the connection variable in the cmd declaration.
In future you may also like catching your errors in development:
catch (Exception ex)
{
loginlabel.Text = "login error: "+ ex.Message;
}
This will help you know what is going wrong.

Related

Using stored procedure to login Asp.net

I'm using asp.net to create a login page; in debugging I see the correct inputted data but I keep gettting the error message Invalid Username or Password even when it is valid. I have also executed the stored procedure with values and shows the correct result. I'm not sure what is happening.
protected void login_Click(object sender, EventArgs e)
{
String username = txtUserName.Text.ToString();
String password = txtPassword.Text;
string con = ConfigurationManager.ConnectionStrings["LoginConnectionString"].ToString();
SqlConnection connection = new SqlConnection(con);
connection.Open();
string passwords = encryption(password);
SqlCommand cmd1 = new SqlCommand("spLogin", connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#UserName", username);
cmd1.Parameters.AddWithValue("#password", passwords);
SqlDataReader sqldr = cmd1.ExecuteReader();
if (sqldr.Read())
{
Session["UserName"] = username.ToUpper();
Response.Redirect("~/Home/Welcome.aspx");
}
else
{
lblError.Text = "Invalid Username or Password";
}
connection.Close();
sqldr.Close();
}
StoredProcedure
select * from Users u where UserName=#UserName and password=#password

ASP.Net db connection issue

I'm new to ASP.Net & SQL Server and have the following code:
protected void btnShowData_Click(object sender, EventArgs e)
{
string connectionString;
SqlConnection cnn;
connectionString = #"Data Source=DESKTOP-RV7DDL4;Initial Catalog=Demodb
;User ID=DESKTOP-RV7DDL4\dbname;Password=test123";
cnn = new SqlConnection(connectionString);
SqlCommand command;
SqlDataReader dataReader;
String sql, Output = "";
sql = "Select TutorialID, TutorialName from demotb";
command = new SqlCommand(sql, cnn);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();
lblName.Visible = false;
txtName.Visible = false;
lstLocation.Visible = false;
chkC.Visible = false;
chkASP.Visible = false;
rdMale.Visible = false;
rdFemale.Visible = false;
btnSubmit.Visible = false;
}
When I run the project I receive the following error:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: ExecuteReader requires an open and available Connection. The connection's current state is closed.
I thought the connection was made so not sure why it says the db is closed?
Try to to explicitly open the connection via the Open method on the SQL connection class.
Perhaps a using statement is more appropriate here. Like so:
using (var cnn = new SqlConnection(connectionString))
{
// Use the connection
}
Thanks for your help. I re-jigged things around and added the .Open method and it works!
string connectionString = null;
SqlConnection cnn;
SqlCommand command;
string sql, Output = "";
connectionString = #"Data Source=DESKTOP-RV7DDL4\SQLEXPRESS;Initial Catalog=DemoDBase
;User ID=sa;Password=test1234";
cnn = new SqlConnection(connectionString);
sql = "Select TutorialID, TutorialName from demoTable";
cnn.Open();
command = new SqlCommand(sql, cnn);
SqlDataReader dataReader;
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
Output = Output + dataReader.GetValue(0) + " - " + dataReader.GetValue(1) + "</br>";
}
Response.Write(Output);
dataReader.Close();
command.Dispose();
cnn.Close();

Show error message on webpage if there trying to add duplicate value into database?

I have the interface to create a new customer with both customer code and customer name which will be insert into the Customer table. The code could not be duplicate in the table. What I want to do is to show a error message on the webpage if there is duplicate code being typed into the Customer code area and submit. How could i do this? Following is my code, thanks!
protected void btnOk_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(GetConnectionString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Connection = conn;
cmd.CommandText = "dbo.InsertCustomer";
cmd.Parameters.AddWithValue("#CCode", txtCustomerCode.Text);
cmd.Parameters.AddWithValue("#CName", txtRemark.Text);
try
{
conn.Open();
cmd.ExecuteNonQuery();
string message = "New Customer Created!";
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.Append("<script type = 'text/javascript'>");
sb.Append("window.onload=function(){");
sb.Append("alert('");
sb.Append(message);
sb.Append("')};");
sb.Append("</script>");
ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", sb.ToString());
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
conn.Close();
conn.Dispose();
}
}
You could set a label to the message. Something like.
if(ex.Message.ToString().Contains("Duplicate"))
this.lblMessage.Text = "Code "+txtCustomerCode.Text+" is already taken."
else
this.lblMessage.Text = msg;
Not sure of the exact text to look for. You would also not rethrow the exception.
Going with the route you're taking using the ClientScript.RegisterClientScriptBlock you can put this in the catch block if you have written your procedure to cause an exception when duplicate occurs
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "popup", "alert('Customer code already exists !!');", true);
Refer my another post for the similar problem like yours

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack when I use scope identity

Here is ehat I try to do
on button_click I read the values from the text boxes and insert them in them in the database.
as tourist number for example maybe two or three tourists with ExecuteScalar; i get the ids of teh tourists which are inserted!
public void cmdInsert_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
string numtourist = (string)Session["tourist_number"];
for (int i = 0; i < Int32.Parse(numtourist); i++)
{
TextBox tx888 = (TextBox)FindControl("txtNameK" + i.ToString());
TextBox tx888_1 = (TextBox)FindControl("txtMidNameK" + i.ToString());
TextBox tx888_2 = (TextBox)FindControl("txtLastNameK" + i.ToString());
string insertSQL = "INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)";
insertSQL += " VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#Excursion_ID", Convert.ToInt32(mynew2));
cmd.Parameters.AddWithValue("#Excursion_date_ID", Convert.ToInt32(mynewnewstring));
cmd.Parameters.AddWithValue("#Name_kir", tx888.Text);
cmd.Parameters.AddWithValue("#MidName_kir", tx888_1.Text);
cmd.Parameters.AddWithValue("#LastName_kir", tx888_2.Text);
int added;
try
{
con.Open();
added = (int)cmd.ExecuteScalar();
lblproba.Text = "";
Tourist.Add(added);
lblproba.Text += Tourist.Count();
}
catch (Exception ex)
{
lblproba.Text += ex.Message;
}
finally
{
con.Close();
}
}
createReservation();
}
}
I call CreateReservationFunction AND i CREATE A NEW RESERVAION WITH THE ID OF THE USER WHO HAS MADE THE RESERVATION. wITH SELECT IDENTITY I TRY TO GET THE RESERVATION_ID of the reservation and here I get the exception "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack". So I wonder can this exception has something commn with the fact that in my solution exceptthe asp.net web projectI got library class in which I has .edmx file The entity framework model of my database and in my last form I don't use Ado,net but Entity framework
public void createReservation()
{
string insertSQL = "Insert INTO RESERVATIONS (User_ID) values (#User_ID) SELECT ##IDENTITY";
string connectionString = "Data Source = localhost\\SQLExpress;Initial Catalog=excursion;Integrated Security=SSPI";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand(insertSQL, con);
cmd.Parameters.AddWithValue("#User_ID", 9);
try
{
con.Open();
string added = cmd.ExecuteScalar().ToString();
createTouristReservation(added);
}
catch (Exception ex)
{
lblproba.Text+= ex.Message;
}
}
Don't use ##IDENTITY but SCOPE_IDENTITY and add a semicolon between the insert and the select.
string insertSQL = #"INSERT INTO Tourist (Excursion_ID, Excursion_date_ID, Name_kir,Midname_kir, Lastname_kir)
VALUES (#Excursion_ID, #Excursion_date_ID, #Name_kir,#Midname_kir, #Lastname_kir)
;SELECT CAST(scope_identity() AS int)";

How to check if email is already in use in asp.net and making sure email is available before allowing the user to register?

I need to check an SQL Server database (not asp.net membership) to see if an email is already in use before allowing the user to register.
I have tried using the information in this website but it does not seem to work.
Your help will be much appreciated
You can try
protected void txtUsername_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUsername.Text))
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like " + txtUsername.Text.Trim(), con);//I changed
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = "NotAvailable.jpg";
lblStatus.Text = "UserName Already Taken";
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = "Icon_Available.gif";
lblStatus.Text = "UserName Available";
}
con.Close();//I added
}
else
{
checkusername.Visible = false;
}
}

Resources