change password in asp.net,c#,ms-access database - asp.net

i am desiging a change password screen in asp.net,c#,MS-access database
i m having 4 fields
userid,
oldpassword,
newpassword
confirm password
NOW I M NOT GETTING RESULT THE COUNT RETURNS 0 I HAVE UPDATED MY CODE
my code is as follows
try
{
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["vhgroupconnection"]
.ConnectionString);
myCon.Open();
string userid = txtuserid.Text;
string oldpass = txtoldpass.Text;
string newPass = txtnewpass.Text;
string conPass = txtconfirmpass.Text;
string q = "select user_id,passwd from register where user_id = #userid and passwd = #oldpass";
OleDbCommand cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#oldpass", txtoldpass.Text);
OleDbDataReader re = cmd.ExecuteReader();
re.Read();
if (re["user_id"].ToString() != String.Empty && re["passwd"].ToString() != String.Empty)
{
if (newPass.Trim() != conPass.Trim())
{
lblmsg.Text = "New Password and old password does not match";
}
else
{
q = "UPDATE register SET passwd = #newPass WHERE user_id =#userid";
cmd = new OleDbCommand(q, myCon);
cmd.Parameters.AddWithValue("#userid", txtuserid.Text);
cmd.Parameters.AddWithValue("#newPasss", txtnewpass.Text);
int count = cmd.ExecuteNonQuery();
if (count > 0)
{
lblmsg.Text = "Password changed successfully";
}
else
{
lblmsg.Text = "password not changed";
}
}
}
}
catch(Exception ex)
{
throw ex;
}
plz help me to solve the error

You're getting the error, No constructor is defined, because you can't directly instantiate this object. As stated on MSDN:
To create an OleDbDataReader, you must call the ExecuteReader method
of the OleDbCommand object, instead of directly using a constructor.
Essentially, you'd do something like the following after creating your connection and specifying your query:
OleDbDataReader re = cmd.ExecuteReader();

Related

New to ASP and SQL server, How does the condition: IF(dtble.Rows.Count>0) work to match username and password?

Can anyone explain me how does it matches username and password from data table and logs in the user?
DataTable dtForNameAndRole = LoadDataByQuery(sql);
try
{
**if (dtForNameAndRole.Rows.Count > 0)**
{
Session["username"] = dtForNameAndRole.Rows[0]["username"].ToString(); //userID;
Session["password"] = dtForNameAndRole.Rows[0]["password"].ToString(); //userID;
txtpassword.Text = string.Empty;
txtusername.Text = string.Empty;
Response.Redirect("Dashboard.aspx");
Can you please use the below code it'll help you!
using (SqlConnection sqlcon = new SqlConnection(connectionString)){
//string user = txtEmail.Text;
//string pass = txtPassword.Text;
sqlcon.Open();
SqlCommand cmd = new SqlCommand("select count(*) from [dbo].[Register] where Email=#Email and Password=#Password", sqlcon);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Password", ToSHA2569(txtPassword.Text));
var isCorrectPassword = cmd.ExecuteScalar();
if ((int)isCorrectPassword >= 1)
{
//sqlcon.Close(); //taken care of because of the using command
Response.Redirect("default.aspx");
}
else
{
// sqlcon.Close();
lblWrong.Text = "Password not correct";
}
}

change/forgot password with a hashed password possible?

i have implemented my user passwords to be hashed. And what i want is to implement a forgot/change password. However i am not able to convert the hashed password to the original password and that gives me a failure to do the forgot/change password feature. Here is my code from my registration page:
cmd.Parameters.AddWithValue("#Password", BusinessLayer.ShoppingCart.CreateSHAHash (txtPW.Text));
Here is my creathash code:
public static string CreateSHAHash(string Phrase)
{
SHA512Managed HashTool = new SHA512Managed();
Byte[] PhraseAsByte = System.Text.Encoding.UTF8.GetBytes(string.Concat(Phrase));
Byte[] EncryptedBytes = HashTool.ComputeHash(PhraseAsByte);
HashTool.Clear();
return Convert.ToBase64String(EncryptedBytes);
}
and my changepassword page:
protected void btn_update_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(conn);
con.Open();
str = "select * from UserData ";
com = new SqlCommand(str, con);
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
if (txt_cpassword.Text == reader["Password"].ToString())
{
up = 1;
}
}
reader.Close();
con.Close();
if (up == 1)
{
con.Open();
str = "update UserData set Password=#Password where UserName='" + Session["New"].ToString() + "'";
com = new SqlCommand(str, con);
com.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar, 500));
com.Parameters["#Password"].Value = (txt_npassword.Text);
com.ExecuteNonQuery();
con.Close();
lbl_msg.Text = "Password changed Successfully";
}
else
{
lbl_msg.Text = "Please enter correct Current password";
}
}
What i want to do is to be able to convert my hashed password to the original password for it to be changed. Any tricks? or is it possible though?

Data Reader and Invalid attempt to read when no data is present

This is my code:
protected void logujButton_Click(object sender, EventArgs e)
{
string user = "data source=myHostServer; database = myDataBase; user id=myLogin; password=myPassword";
SqlConnection con2 = new SqlConnection(user);
con2.Open();
string loguj = "select count(*) from uzytkownik where Login = '"+ logujTextBox.Text +"'";
SqlCommand command = new SqlCommand(loguj, con2);
int wartosc = Convert.ToInt32(command.ExecuteScalar().ToString());
con2.Close();
if (wartosc == 1)
{
con2.Open();
SqlCommand pobierzHaslo = new SqlCommand("select Haslo from uzytkownik where Login = '" + logujTextBox.Text + "'", con2);
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
string haslo = rdr["Haslo"].ToString();
if (haslo == hasloTextBox.Text)
{
errorLabel.Text = "Prawidlowe Haslo !";
}
else
{
errorLabel.Text = "Zle haslo !";
}
}
else
{
errorLabel.Text = "Taki uzytkownik nie istnieje !";
}
}
When I press button, this error is appearing: "Invalid attempt to read when no data is present". Could You tell me, where i made mistake ?. Thanks for advise !
You haven't read anything from the reader yet. You have to call the Read() method:
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
if (rdr.Read())
{
string haslo = rdr["Haslo"].ToString();
....
}
If you have access to SSMS, run the query directly in a query window and make sure that you get data back. Your query may be bad. It is most likely an error from the ExecuteReader method of your SqlDataReader, based on the text of the error message.

ASP.Net insert data from form to a database Exception

I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);

loop in select statment

protected void Button1_Click(object sender, EventArgs e)
{
if (firstname_tb.Text == "" || lastname_tb.Text == "" || email_tb.Text == "" || reemail_tb.Text == "" || pass_tb.Text == "" || gender_ddl.SelectedItem.Text == "" || day_ddl.SelectedItem.Text == "" || year_ddl.SelectedItem.Text == "")
{
Label9.Text = "please fill all data";
Label9.Visible = true;
}
else
{
str = email_tb.Text;
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT email from reg ",con);
con.Open();
comsel.ExecuteNonQuery();
con.Close();
foreach (var v in comsel.Parameters.ToString())
{
if (v.ToString() == str)
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
b = false;
break;
}
else
{
b = true;
}
}
if (b==true)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand com = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", con);
con.Open();
com.Parameters.AddWithValue("#fn", firstname_tb.Text);
com.Parameters.AddWithValue("#ln", lastname_tb.Text);
com.Parameters.AddWithValue("#email", email_tb.Text);
com.Parameters.AddWithValue("#reemail", reemail_tb.Text);
com.Parameters.AddWithValue("#pass", pass_tb.Text);
com.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
com.Parameters.AddWithValue("#birth", birthday);
com.ExecuteNonQuery();
con.Close();
Label9.Text = "thank you for registration";
Label9.Visible = true;
}
else
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
}
}
There is a problem that is when I try to enter email allready exist in the database it enterd while it must show to the user that this email already exist in the data base. Can any one help me?
OK as far as I can understand, you only want the INSERT to occur if the email is unique in the [reg].[email] field. This will happen if b == true. The logic you use for this is basically correct, but you are not retrieving the results of the database correctly. Try something like:
con.Open();
System.Data.SqlClient.SqlDataReader objReader = comsel.ExecuteReader();
while (objReader.Read())
{
if ((String)objReader("email") == str)
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
b = false;
break;
}
else
{
b = true;
}
}
con.Close();
Hopefully that will work as intended.
On a side note, I would be remiss not to mention that this approach is pretty inefficient. A better idea would be to use a query like this:
SELECT [email] FROM [reg] WHERE [email] = #email;
In which you specify your variable "str" as a parameter in a similar manner to the INSERT operation below. Then instead of iterating through the results, simply check to see if the SqlDataReader has any rows:
SqlConnection con = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True");
SqlCommand comsel = new SqlCommand("SELECT [email] FROM [reg] WHERE [email] = #email;",con);
comsel.Parameters.AddWithValue("#email", str);
System.Data.SqlClient.SqlDataReader objReader = comsel.ExecuteReader();
if (objReader.HasRows())
{
b = false;
}
else
{
b = true;
}
con.Close();
Remove the if statement checking for field entries and add RequiredValidators to your form:
https://web.archive.org/web/20211020145950/https://www.4guysfromrolla.com/webtech/090200-1.shtml
As for the second part.. if email already exists... create a custom validator for this and use this to display the message to your user if the email already exists. Note that you're using ExecuteNonQuery() here for what is essentially a query...
You also need some "separation of concerns". For example, put the connection string in the Web.Config. Do your data access from a DAL class, etc
For the first query, you can just use ExecuteScalar as that will return a single value from your query. I rewrote your query so that it will do a count of the emails that match the email the user is trying to use. If the count returned is 0, then you know that the email is currently not in use.
string strEmail = email_tb.Text.Trim();
try
{
using(SqlConnection conn = new SqlConnection(#"Data Source=SAMA-PC\SQLEXPRESS;Initial Catalog=meral10;Integrated Security=True"))
{
conn.Open();
SqlCommand cmd = new SqlCommand("SELECT COUNT(1) FROM reg WHERE email = #email", conn);
cmd.Parameters.AddWithValue("#email", strEmail);
int count = (int)cmd.ExecuteScalar();
if(count==0)
{
birthday = day_ddl.Text + "/" + month_ddl.Text + "/" + year_ddl.Text;
SqlCommand cmdInsert = new SqlCommand("INSERT INTO reg(first_name,last_name,email,email_ver,pass,gender,birthday) values(#fn,#ln,#email,#reemail,#pass,#gen,#birth)", conn);
cmdInsert.Parameters.AddWithValue("#fn", firstname_tb.Text);
cmdInsert.Parameters.AddWithValue("#ln", lastname_tb.Text);
cmdInsert.Parameters.AddWithValue("#email", email_tb.Text);
cmdInsert.Parameters.AddWithValue("#reemail", reemail_tb.Text);
cmdInsert.Parameters.AddWithValue("#pass", pass_tb.Text);
cmdInsert.Parameters.AddWithValue("#gen", gender_ddl.SelectedItem.Text);
cmdInsert.Parameters.AddWithValue("#birth", birthday);
cmdInsert.ExecuteNonQuery();
Label9.Text = "thank you for registration";
Label9.Visible = true;
}
else
{
Label9.Text = "this email already exist choose another one";
Label9.Visible = true;
}
}
}
catch(SqlException ex)
{
// log your exception then display a friendly message to user
Label9.Text = "An error occurred while trying to save your registration";
}

Resources