SQL database Connection does not Work Properly - c#

Here i put some code... this code related to login system. here i have some problem.... when i enter right User id and Password or even Wrong User ID and Password both are authorized and display message Login successfully.......how can be this... i don't understand why SQLConnection give authorization to Unknown user which are not in database....
See the Code....
string SQlcons = "Data Source=(LocalDB)\v11.0;AttachDbFilename='|DataDirectory|Database1.mdf';Integrated Security=True"
private void button1_Click(object sender, EventArgs e)
{
String UN = txtUsername.Text;
String PW = txtPassword.Text;
string loginstr = "SELECT * FROM Login Where UserName = '" + UN + "' and Password = '" + PW + "'";
SQLconn = new SqlConnection(SQLcons);
SQLconn.Open();
try
{
SqlCommand cmd = new SqlCommand(loginstr, SQLconn);
cmd.ExecuteNonQuery();
MessageBox.Show("Welcome " + txtUsername.Text);
Records rcd = new Records();
this.Hide();
rcd.ShowDialog();
}
catch
{
MessageBox.Show("Enter Correct Password and ID :(");
txtUsername.Text = "";
txtPassword.Text = "";
}
SQLconn.Close();
}
Plz... Give the solution and Suggestion to me..

int result = cmd.ExecuteNonQuery();
if(result == 0)
{
//wrong login info,
} else {
MessageBox.Show("Login Success");
}
ExecuteScalar() function returns the row count with given SQL String. In your case, you should check the returned integer value from ExecuteScalar(). If result is 0, user entered wrong login info. If result is 1, user entered right information.

Related

Visual Studio error "Invalid attempt to read when reader is closed" when trying to authenticate login credentials in login form. C# MySQL

I am trying to create a login form that will authenticate the user's credentials before letting them proceed to another form. I am getting an error message where it says "invalid attempt to read when reader is closed"
Error Message
Code:
private void btn_Login_Click(object sender, EventArgs e)
{
sqlConnection.ConnectionString = "server=" + server + ";" + "username=" + username + ";" + "password=" + password + ";" + "database=" + database;
sqlConnection.Open();
sqlCommand.Connection = sqlConnection;
sqlCommand.CommandText = "Select tunapunaboysrc.addregister.Username, tunapunaboysrc.addregister.Password "
+ "from tunapunaboysrc.addregister";
sqlDataReader = sqlCommand.ExecuteReader();
sqlData.Load(sqlDataReader);
dg_Login.DataSource = sqlData;
if (sqlDataReader.Read() == true)
{
new frmDashboard().Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid Username or Password, Please Try Again", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtbx_username.Text = "";
txtbx_password.Text = "";
txtbx_username.Focus();
}
sqlDataReader.Close();
sqlConnection.Close();
new frmDashboard().Show();
this.Hide();
}
I also use this at the beginning also, incase if its needed.
public partial class frmLogin : Form
{
MySqlConnection sqlConnection = new MySqlConnection();
MySqlCommand sqlCommand = new MySqlCommand();
DataTable sqlData = new DataTable();
MySqlDataAdapter SqlAdapter = new MySqlDataAdapter();
DataSet sqlSet = new DataSet();
MySqlDataReader sqlDataReader;
String server = "localhost";
String username = "root";
String password = "cybers";
String database = "tunapunaboysrc";
Can someone help me figure out why my reader is closing, and how i can solve it?
i tried pasting the authentication code
if (sqlDataReader.Read() == true)
{
new frmDashboard().Show();
this.Hide();
}
else
{
MessageBox.Show("Invalid Username or Password, Please Try Again", "Login Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtbx_username.Text = "";
txtbx_password.Text = "";
txtbx_username.Focus();
}

Is there any way to fetch table record data from sql server to web form from another form?

I have two Web forms. One is LoginForm and Second is StudentStatus Form by Login with id and password in LoginForm i want to show Student Status record from StatusTable in StudentStatus Form...
Is there any way to fetch data from squal server from one form to another?
This is my LoginForm Code...
protected void LoginBtn_Click(object sender, EventArgs e)
{
string cs = "Data Source = SAAD_EBAD\\SQLEXPRESS; Database = Custom Test; Trusted_Connection = Yes";
SqlConnection con = new SqlConnection(cs);
con.Open();
string _sqlQuery = "Select count(*) from Student_Status where User_Name='" + Usertxt.Text + "'";
SqlCommand cmd = new SqlCommand(_sqlQuery, con);
int temp = Convert.ToInt32(cmd.ExecuteScalar().ToString());
con.Close();
if (temp == 1)
{
con.Open();
string _checkPasswordQuery = "Select Student_Password From Student_Status Where User_Name='" + Usertxt.Text + "'";
SqlCommand command = new SqlCommand(_checkPasswordQuery, con);
string _password = command.ExecuteScalar().ToString().Replace(" ", "");
**if (_password == PasswordTxt.Text)
{
Session["New"] = Usertxt.Text;
Response.Redirect("~/Student Status.aspx");
if (_password.Equals(PasswordTxt.Text))
{
Student_Status.CreateHtmlTextWriterFromType(,"select Student_Degree_Status from Student_Status" );
}**
}
else
{
string str = "Sorry,Password is not correct";
ClientScript.RegisterStartupScript(this.GetType(), "My alert", "alert('" + str + "');", true);
}
}
else
{
string str2 = "User Name is not correct";
ClientScript.RegisterStartupScript(this.GetType(), "My alert", "alert('" + str2 + "');", true);
}
}
The code in bold (quoted) form i am having concern and issue it is not working. ihust want to show data from sql server from one form to another by login

How do I actually login user

Im very new to C#, im working on a login system. The program can verify the user information but I dont get how your suppose to log the user in. Beacuse now you get a success message and thats it.
And how do you redirect the user to the rest of the application. This is a native app and all I could find was information about how to redirect in asp.net instad of c#.net.
private void button1_Click(object sender, EventArgs e)
{
string user = textBox1.Text;
string pwd = textBox2.Text;
MySqlConnection conn = new MySqlConnection("server = localhost; user id = root; database = bot");
MySqlDataAdapter sda = new MySqlDataAdapter("select count(*) from license where user = '" + textBox1.Text + "' and pwd = '" + textBox2.Text + "'", conn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString() == "1")
{
MessageBox.Show("Successful login!", "info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("Info is not valid", "alter", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
You just need to define an object of the class and the use Show(); after you use this.Hide(); for ASP.NET use Response.Redirect("Dashboard.aspx")
For increasing the security of your login form you should read this to preventing SQL injection attacks: https://www.codeproject.com/Articles/9378/%2FArticles%2F9378%2FSQL-Injection-Attacks-and-Some-Tips-on-How-to-Prev
https://www.mikesdotnetting.com/article/113/preventing-sql-injection-in-asp-net
For the session setting
How to set security on Login Page in asp.net
For encryption :
C# encrypted Login
private void button1_Click(object sender, EventArgs e)
{
string user = textBox1.Text;
string pwd = textBox2.Text;
MySqlConnection conn = new MySqlConnection("server = localhost; user id = root; database = bot");
string query = "Select * from license Where user = '" + textBox1.Text.Trim() + "' and pwd = '" + textBox2.Text.Trim() + "'";
SqlDataAdapter sda = new SqlDataAdapter(query, conn );
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count == 1)
{ //change the name of the form depend on the form that you need to show.
frmMain objFrmMain = new frmMain();
this.Hide();
objFrmMain.Show();
}
else
{
MessageBox.Show("Check your username and password");
}
}
For ASP.NET
protected void btnLogin_Click(object sender, EventArgs e)
{
using (SqlConnection sqlCon = new SqlConnection("server = localhost; user id = root; database = bot");
{
sqlCon.Open();
string query = "Select * from license Where user = '" + textBox1.Text.Trim() + "' and pwd = '" + textBox2.Text.Trim() + "'";
SqlCommand sqlCmd = new SqlCommand(query, sqlCon);
sqlCmd.Parameters.AddWithValue("#user",textBox1.Text.Trim());
sqlCmd.Parameters.AddWithValue("#pwd", textBox2.Text.Trim());
int count = Convert.ToInt32(sqlCmd.ExecuteScalar());
if (count == 1)
{
Session["user"] = textBox1.Text.Trim();
Response.Redirect("Dashboard.aspx");
}
else { lblErrorMessage.Visible = true; }
}
}
Download the code from here:https://drive.google.com/drive/folders/17KvHSTJvvD5jmcufr35-V8TV67pHL7D8

Unable to Make this log in Form in c# / SqlDataReader Issue

I am trying to make a windows Form Application with a login screen,Form3 Will open Form1 if the username and password are correct.
The code is linked to a database
The code is as follows:
private void button1_Click(object sender, EventArgs e)
{
string u_id = textBox1.Text;
string u_pwd = textBox2.Text;
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XXX.XXXXX.ac.uk;Initial Catalog=mmt12-186;User ID=XXXXXX;Password=XXXXXX");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = ("SELECT * FROM UsersData WHERE User = '" + textBox1.Text + "'");
cmd.Parameters.AddWithValue("un", u_id);
SqlDataReader reader = cmd.ExecuteReader();
if (reader.Read() == false)
{
label3.Text = "Invalid Username or Password !";
return;
}
string realpwd = reader.GetString(0);
if (u_pwd == realpwd)
{
Form1 formload = new Form1();
formload.Show();
}
}
Every time I run this code, I get an exception on with the line:
string realpwd = reader.GetString(0);
The exception is:
Invalid attempt to read when no data is present.
The UsersData table has 3 columns, Id, User, Password
Thanks goes to "Alfred Sanz" who answered the question, the problem now is that no error is present but no data is shown, as if the button1_click has no method, the current code is:
private void button1_Click(object sender, EventArgs e)
{
string u_id = textBox1.Text;
string u_pwd = textBox2.Text;
SqlConnection conn = new SqlConnection("Data Source=mmtsql.XX.XXX.ac.uk;Initial Catalog=XXXXXXX ;User ID=XXXX;Password=XXXXX");
conn.Open();
SqlCommand cmd = conn.CreateCommand();
cmd.CommandText = ("SELECT * FROM UsersData WHERE User = #un");
cmd.Parameters.AddWithValue("#un", u_id);
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
if (reader["Password"].ToString() == u_pwd)
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}
you already set the value of USER as '" + textBox1.Text + "'" but you are also setting a value cmd.Parameters.AddWithValue("un", u_id); which really does not exist, change your code into
cmd.CommandText = "SELECT * FROM UsersData WHERE User = #un";
cmd.Parameters.AddWithValue("#un", u_id);
and also you can change the reader part to:
while (reader.Read())
{
if (reader["Password"].ToString() == u_pwd.Text
{
Form1 formload = new Form1();
formload.Show();
}
else
{
label3.Text = "Invalid Username or Password !";
}
}

Table is not getting updated , when used executeNonquery

I am trying to change the user password. I am not able to update the password :(. The message i am getting is password changed where as its not getting changed. .
My code is as follow.. Please if anyone can suggest where i am going wrong . I am just a beginner ...
protected void Button1_Click(object sender, EventArgs e)
{
DatabaseLayer data = new DatabaseLayer();
string username = Session["Authenticate"].ToString();
string password = TextBox1.Text;
string newpass = TextBox2.Text;
string confirm = TextBox3.Text;
string flag = "";
if (newpass.ToString() == confirm.ToString())
{
flag = data.passwordChange(username, password, newpass);
Literal1.Text = flag.ToString();
}
else
{
Literal1.Text = "New Password does not match the Confirm Password ";
}
}
The above click event must change my password, and the function passwordChange is as follows..
public string passwordChange(string username, string password, string newPasswd)
{
string SQLQuery = "SELECT password FROM LoginAccount WHERE username = '" + username + "'";
string SQLQuery1 = "UPDATE LoginAccount SET password = ' " + newPasswd + " ' WHERE username = ' " + username + "'";
SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
SqlCommand command1 = new SqlCommand(SQLQuery1, sqlConnection);
sqlConnection.Open();
string sqlPassword = "";
SqlDataReader reader;
try
{
reader = command.ExecuteReader();
if (reader.Read())
{
if (!reader.IsDBNull(0))
{
sqlPassword = reader["password"].ToString();
}
}
reader.Close();
if (sqlPassword.ToString() == password.ToString())
{
try
{
int flag = 0;
flag = command1.ExecuteNonQuery();
if (flag > 0)
{
sqlConnection.Close();
return "Password Changed Successfully";
}
else
{
sqlConnection.Close();
return "User Password could not be changed";
}
}
catch (Exception exr)
{
sqlConnection.Close();
return "Password Could Not Be Changed Please Try Again";
}
}
else
{
sqlConnection.Close();
return "User Password does not Match";
}
}
catch (Exception exr)
{
sqlConnection.Close();
return "User's Password already exists";
}
}
I had put a break point near
if(flag>0)
it still shows that executeNonquery aint returning the updated rows value and also in the Back end of SQL server, its not changing,
Please if anyone could correct me... Should i use other execute command or something?
I am doing this with VS 2008 and SQL server 2005..
1: It's your spacing between your single and double quotes: (Like: ' " + username + " ')
2) You are begging for SQL Injection.
Try this in your PasswordChange method:
public string PasswordChange(string userName, string oldPass, string newPass)
{
using(SqlConnection sqlConnection = new SqlConnection(
ConfigurationManager.ConnectionStrings["LoginDb"].ConnectionString))
{
string sqlToConfirmOldPass =
"SELECT password FROM LoginAccount WHERE username = #userName";
string sqlToUpdatePassword =
"UPDATE LoginAccount SET password = #newPass WHERE username = #userName";
SqlCommand confirmOldPass = new SqlCommand(sqlToConfirmOldPass, sqlConnection);
confirmOldPass.Parameters.AddWithValue("#userName", userName);
SqlCommand updatePassword = new SqlCommand(sqlToUpdatePassword, sqlConnection);
updatePassword.Parameters.AddWithValue("#newPass", newPass);
updatePassword.Parameters.AddWithValue("#userName", userName);
[Rest of your code goes here]
}
}
I also didn't see where you set your SqlConnection, so I've added a line for that. You'll need to modify it according to your needs.
Maybe try this code instead.
public string passwordChange(string username, string password, string newPasswd)
{
string SQLQuery = "SELECT password FROM LoginAccount WHERE username = #username";
string SQLQuery1 = "UPDATE LoginAccount SET password = #newPassword WHERE username = #username";
SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);
command.Parameters.AddWithValue("#username", username);
SqlCommand command1 = new SqlCommand(SQLQuery1, sqlConnection);
command1.Parameters.AddWithValue("#username", username);
command1.Parameters.AddWithValue("#newPassword", newPasswd);
sqlConnection.Open();
string sqlPassword = "";
SqlDataReader reader;
try
{
reader = command.ExecuteReader();
if (reader.Read())
{
if (!reader.IsDBNull(0))
{
sqlPassword = reader["password"].ToString();
}
}
reader.Close();
if (sqlPassword.ToString() == password.ToString())
{
try
{
int flag = 0;
flag = command1.ExecuteNonQuery();
if (flag > 0)
{
sqlConnection.Close();
return "Password Changed Successfully";
}
else
{
sqlConnection.Close();
return "User Password could not be changed";
}
}
catch (Exception exr)
{
sqlConnection.Close();
return "Password Could Not Be Changed Please Try Again";
}
}
else
{
sqlConnection.Close();
return "User Password does not Match";
}
}
catch (Exception exr)
{
sqlConnection.Close();
return "User's Password already exists";
}
}
If you're getting zero rows affected double check that your WHERE clause actually works. I'd bet that if you SELECTed WHERE username = '" + username + "'", you won't find the row you're looking for. That'd, at least, be the first thing I would confirm.

Categories

Resources