I am trying to log on with a username and original password that already stored in the database with a hashed password.
But, when I am trying to log on, I received the message says that value cannot be null on if (salt == null) {
throw new ArgumentNullException("salt");
}
I am using BCrypt.cs for hashing the password in the database. BCrypt.cs
Here is my code for register the user:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
Password.Hashed = BCrypt.HashPassword(this.textBox2.Text, BCrypt.GenerateSalt(12));
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "INSERT INTO [Member] ([Username], [Password], [UserType]) VALUES (#Username, #Password, #UserType)";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = Password.Hashed;
cmd.Parameters.Add("#UserType", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#UserType"].Value = this.comboBox1.SelectedItem;
cmd.ExecuteNonQuery();
System.Media.SoundPlayer _sound = new System.Media.SoundPlayer(#"C:\Windows\Media\Windows Exclamation.wav");
_sound.Play();
DialogResult _dialogResult = MessageBox.Show("Added Successfully!", "Success", MessageBoxButtons.OK);
if (_dialogResult == DialogResult.OK)
{
this.Hide();
Login _login = new Login();
_login.ShowDialog();
this.Close();
}
}
conn.Close();
}
Here is my code for log on the user:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Username], [Password], [UserType] FROM [Member] WHERE [Username] = #Username AND [Password] = #Password";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
cmd.Parameters.Add("#Password", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Password"].Value = BCrypt.CheckPassword(this.textBox2.Text, Password.Hashed);
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
if (dReader.Read())
{
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
this.Hide();
this.Close();
}
else
{
Validation(sender, e);
RecursiveClearTextBoxes(this.Controls);
}
dReader.Close();
conn.Close();
}
}
}
Here is the password class:
public static string Hashed
{
get;
set;
}
Any help would be appreciated and your answer much appreciated!
Thank you so much.
EDITED:
My database looks like this:
That password was hashed (salt) and my original password that I use for the login is Kaoru. That password was generated from original password, which is Kaoru
Try the following code:
string connectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=..\db1.accdb";
using (OleDbConnection conn = new OleDbConnection(connectionString))
{
string query = "SELECT [Username], [Password], [UserType] FROM [Member] WHERE [Username] = #Username";
conn.Open();
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.Add("#Username", System.Data.OleDb.OleDbType.VarChar);
cmd.Parameters["#Username"].Value = this.textBox1.Text;
using (OleDbDataReader dReader = cmd.ExecuteReader())
{
bool isValidPassword = false;
if (dReader.Read())
{
string password = (string)dReader["Password"];
bool isValidPassword = BCrypt.CheckPassword(this.textBox2.Text, password);
if (isValidPassword)
{
UserInformation.CurrentLoggedInUser = (string)dReader["Username"];
UserInformation.CurrentLoggedInUserType = (string)dReader["UserType"];
this.Hide();
this.Close();
}
}
if (!isValidPassword)
{
Validation(sender, e);
RecursiveClearTextBoxes(this.Controls);
}
}
}
}
Related
string constr = #"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\jettp\Downloads\MockTest\MockTest\Database1.mdf;Integrated Security=True";
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT Name, Weight FROM MyWeight where Name ='" + txt_Name.Text + "'"))
{
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (txt_Name.Text != null)
{
sdr.Read();
MessageBox.Show("Username is found");
txt_Name.Text = sdr["Name"].ToString();
txt_Weight.Text = sdr["Weight"].ToString();
con.Close();
}
else
{
lbl_WarningMsg.Text = "Name not found";
con.Close();
}
}
}
}
I tried using this command to search for the username which is in not found database, but database message kept saying that the name is found in the database. This is the error I get:
System.InvalidOperationException: 'Invalid attempt to read when no data is present.'
You are getting that Username is found because your if condition is always true. Change your if condition to this :
if (sdr.HasRows)
{
//your code
}
Finally got the app to connect to the SQL DB on the server. But now the test data won't insert.
I'm getting no errors
private void BtnUpload_Click(object sender, EventArgs e)
{
btnUpload.Enabled = false;
Application.DoEvents();
UploadFile(txtFTPAddress.Text, txtFilePath.Text, txtUsername.Text, txtPassword.Text);
btnUpload.Enabled = true;
string connString = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using (SqlConnection Conn = new SqlConnection(connString))
try
{
Conn.Open();
string insertURL = "insert into modelGEOmodelData (ID, Name, Location, modelGeoURL) values (#ID, #Name, #Location, #modelGeoURL)";
SqlCommand command = new SqlCommand(insertURL, Conn);
string id = "1234";
string name = "pump";
string local = "redford";
command.Parameters.Add(new SqlParameter("#ID", id));
command.Parameters.Add(new SqlParameter("#Name", name));
command.Parameters.Add(new SqlParameter("#Location", local));
command.Parameters.Add(new SqlParameter("#modelGeoURL", FileURLtxt.Text));
Conn.Close();
}
catch
{
}
It shows invalid user credentials even though I inputted the right one. I don't know if I made the parameters wrong or if my query is wrong. I want to learn about parameterized queries but I don't know what I'm doing wrong here.
con.OpenConnection();
using (con.connection)
{
String query = "SELECT * FROM tblUser WHERE Username = #Username and Password = #Password";
try
{
MySqlCommand cmd = new MySqlCommand(query, con.connection);
cmd.Parameters.Add("#Username", MySqlDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = txtPassword.Text;
cmd.ExecuteNonQuery();
DataTable dt = new DataTable();
MySqlDataAdapter da = new MySqlDataAdapter(cmd);
da.Fill(dt);
i = Convert.ToInt32(dt.Rows.Count.ToString());
if (i == 0)
{
MessageBox.Show("Invalid user credentials.");
}
else
{
//Do stuff
}
}
catch (MySqlException mse)
{
MessageBox.Show(mse.Message);
}
finally
{
con.CloseConnection();
}
Not sure why it is not working but if you use AddWithValue, it will work. Something like this
cmd.Parameters.AddWithValue("#Username", txtUsername.Text);
cmd.Parameters.AddWithValue("#Password", txtPassword.Text);
Change your code so that it's calls a method, when you click on a Button, pass the Username and Password variable into this Method. Create a AutoProperty for UserName and Password at the Class Level
private DataTable PopulateSomeDatatSet(DataSet aDataset, string UserName, string Password)
{
var query = "SELECT * FROM tblUser WHERE Username = #Username and Password = #Password";
MySqlDataAdapter sda;
using (SqlConnection connStr = new SqlConnection(ConnString)) //replace with your ConnectionString Variable
{
using (MySqlCommand cmd = new MySqlCommand(query, connStr))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("#Username", MySqlDbType.VarChar).Value = UserName;
cmd.Parameters.Add("#Password", MySqlDbType.VarChar).Value = Password;
sda = new MySqlDataAdapter(cmd);
new MySqlDataAdapter(cmd).Fill(aDataset);
}
}
((IDisposable)sda).Dispose();
return aDataset.Tables[0];
}
I have a FileUpload control and when I don't insert an image, I want to insert DBNull into the database. So far I have only errors with DBNull.Value. The table allow null for column ImageData.
Here is the code:
protected void button_sign_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile == true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
string Image = "~/userimage/" + str.ToString();
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
string CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("insert into Register values(#Username, #Email, #Password, #ImageData)", con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.Parameters.AddWithValue("#ImageData", Image);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
}
}
else
{
lblMsg.Text = "Error";
}
}
This should be enough
cmd.Parameters.AddWithValue("#ImageData", FileUpload1.HasFile ? Image: DbNull.Value);
Also refactor your code a little bit:
string image = "";
if (FileUpload1.HasFile==true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
image = "~/userimage/" + str.ToString();
}
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
String connString = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("insert into Register values(#Username,#Email,#Password,#ImageData)", con);
cmd.Parameters.AddWithValue("#Username", name);
cmd.Parameters.AddWithValue("#Email", email);
cmd.Parameters.AddWithValue("#Password", pass);
cmd.Parameters.AddWithValue("#ImageData", FileUpload1.HasFile ? image: DbNull.Value);
con.Open();
cmd.ExecuteNonQuery();
}
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
Don't start your variables with UpperCase letters.
If you set the value of Image at the beginning the rest of the code could stay generic.
protected void button_sign_Click(object sender, EventArgs e)
{
object Image;
if (FileUpload1.HasFile==true)
{
string str = FileUpload1.FileName;
FileUpload1.PostedFile.SaveAs(Server.MapPath("~/userimage/" + str));
Image = "~/userimage/" + str.ToString();
}
else {
Image = System.DBNull.Value;
}
string name = username_textbox.Text;
string email = email_textbox.Text;
string pass = password_textbox.Text;
String CS = ConfigurationManager.ConnectionStrings["MyDatabase"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
using(SqlCommand cmd = new SqlCommand("insert into Register values(#Username,#Email,#Password,#ImageData)", con))
{
// pick the appropriate SqlDbType type for each parameter
cmd.Parameters.Add(new SqlParameter("#Username", SqlDbType.VarChar){Value = name});
cmd.Parameters.Add(new SqlParameter("#Email", SqlDbType.VarChar){Value = email});
cmd.Parameters.Add(new SqlParameter("#Password", SqlDbType.VarChar){Value = pass});
cmd.Parameters.Add(new SqlParameter("#ImageData", SqlDbType.VarChar){Value = Image});
con.Open();
cmd.ExecuteNonQuery();
lblMsg.Text = "Înregistrare cu succes";
Response.AddHeader("REFRESH", "2;URL=login.aspx");
}
Some other notes though
You should specify the Database types using the SqlDbType in your parameters to make sure that the values are translated correctly by the ado.net code.
Wrap you Command in a using block as well
No need to close the connection, the using block will handle that for you.
Do not store passwords in clear text. Instead store a salted hash of the password.
I am trying to run a SQL query based on who's logged in which gets the Team_ID and assigns it to the session variable. I am having trouble assigning the result to the variable.
protected void ButtonLogin_Click(object sender, EventArgs e)
{
//check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("select * from Team_User where Email = #username and Password_1 = #password", con);
cmd.Parameters.AddWithValue("#username", UserName.Text);
cmd.Parameters.AddWithValue("#password", Password.Text);
SqlCommand cmdID = new SqlCommand("select Team_ID from Team_User where Email = #username and Password_1 = #password", con);
cmdID.Parameters.AddWithValue("#username", UserName.Text);
cmdID.Parameters.AddWithValue("#password", Password.Text);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
SqlDataReader reader = cmdID.ExecuteReader();
int Team_ID = reader.GetInt32(1);
Session["Team_ID"] = Team_ID;
Response.Redirect("AddPlayer.aspx");
}
else
{
ClientScript.RegisterStartupScript(Page.GetType(), "validation", "<script language='javascript'>alert('Invalid Username and Password')</script>");
}
}
}
Your code doesn't make a whole lot of sense....
If you only want the Team_ID - why are you loading the whole row first, and then call the database again to get just the Team_ID???
I tried to simplify your code a good bit:
protected void ButtonLogin_Click(object sender, EventArgs e)
{
// check what user category was selected and login to appropriate page
if (DropDownListUserType.SelectedIndex == 1)
{
// define connection string and SQL query as strings
string connectionString = ConfigurationManager.ConnectionStrings["Web_FussConnectionString"].ConnectionString;
string query = "SELECT Team_ID FROM dbo.Team_User WHERE Email = #username AND Password_1 = #password";
// set up SqlConnection and SqlCommand in "using" blocks
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, con))
{
// define and fill parameters - DO NOT use .AddWithValue!
cmd.Parameters.Add("#username", SqlDbType.VarChar, 100).Value = UserName.Text;
cmd.Parameters.Add("#password", SqlDbType.VarChar, 100).Value = Password.Text;
// open connection, execute scalar, close connection
con.Open();
object result = cmd.ExecuteScalar();
// if we got back a result ....
if(result != null)
{
int teamID = Convert.ToInt32(result.ToString());
Session["Team_ID"] = teamID;
Response.Redirect("AddPlayer.aspx");
}
else
{
// if result is NULL, then the username+password
// were NOT found - do what needs to be done in that case here
}
}
}
}